text
stringlengths
8
267k
meta
dict
Q: JBoss AS7 + RestEasy : How to enable a custom MessageBodyReader using @Provider did nothing I have a wierd problem. I'm using @Provider to annote my Mapper Exception and it's work fine, but when I'm using it to annote the class below it won't work at all. @Consumes("application/x-java-serialized-object") @Provider public class JAXBSpecificMarshaller implements MessageBodyReader { @PersistenceContext(unitName = "primary", type = PersistenceContextType.EXTENDED) private EntityManager em; @Override public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) { return type.isAnnotationPresent(XmlRootElement.class); } @Override public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { try { // DataAdapter dataAdapter = new DataAdapter(em); //unmarshaller.setAdapter(dataAdapter); System.out.println(type.getName()); JAXBContext ctx = JAXBContext.newInstance(type); Unmarshaller unmarshaller = ctx.createUnmarshaller(); return unmarshaller.unmarshal(entityStream); } catch ( JAXBException ex ) { throw new RuntimeException(ex); } } } My main reason is to be able to use specific adapter to retrieve an object by passing its id in the input xml. I followed this Serialize a JAXB object via its ID? . But to initialize the adapter with my enitymanger I was told to use MessageBodyReader to do so. Thank you for your help. A: Can you provide some context on what application server you are deploying to and what JAX-RS implementation you are using? I had a similar problem with RESTeasy on JBoss AS 7 trying to implement a @Produces @Provider for some JAXB annotated classes, but the provided JAXB marshaller provider from RESTeasy always took precedence, and my marshaller never got executed. My solution was to write implementations for custom JAXBContextFinder, ContextResolver and JAXBContext. I used resteasy-jettison-provider source code as a recipe for implementing my own handlers. http://docs.jboss.org/resteasy/docs/2.0.0.GA/userguide/html/Built_in_JAXB_providers.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7583640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to write jQuery inside XUL file? I want to use jQuery for my XUL files. Generally I use XUL Explorer to create and text each page individually & it's really to use script blocks inside the XUL files like this: We can write scripts inside script blocks in XUL file itself. <script type="application/x-javascript"> <![CDATA[ // your code here ]]> </script> or <script> </script> To use jQuery we have to link the files like this: <script type="application/x-javascript" src="chrome://axead/content/jquery.js" /> <script type="application/javascript" src="chrome://myapp/content/js/jquery-1.4.4.min.js"/> I use XUL Explorer a lot to create & test XUL files using JavaScript but when I started using XUL files with jQuery in XUL Explorer isn't working. I referred this thread/post: Is it possible to use jQuery to manipulate XUL elements? Is there any way to use/write jQuery inside XUL file?
{ "language": "en", "url": "https://stackoverflow.com/questions/7583644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Python module with a dash, or hyphen (-) in its name I have an existing python module with a dash in its name, foo-bar.py Changing the module name is something I would prefer to avoid as the module is shared, and I would have to chase down all the places it is used so that my special case will work. Is there a way to load a module whose name contains the typically forbidden '-'? (I do understand that this isn't a best practice. But for this situation I would prefer not to redesign and test a much larger set of applications. Also I don't think my corporate masters would approve of my taking the time to implement such a change.) A: I know this question has already been answered to satisfaction of the asker, but here is another answer which I believes has some merit above using __import__(). import importlib mod = importlib.import_module("path.to.my-module") # mod.yourmethod() According to the docs: "This provides an implementation of import which is portable to any Python interpreter. This also provides an implementation which is easier to comprehend than one implemented in a programming language other than Python." Python 2.7 + only A: You can do that using __import__(). For example: foobar = __import__("foo-bar") But you really should rename the module instead. That way you can avoid confusion where the filename of the module is different from the identifier used in the program.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "126" }
Q: What is the best way to edit XML file data? I have some xml files from an external client and i would like to edit the data within them NOT the xml parts. Does anyone one know the best (preferably free) way to achieve this? I have tried excel but I do not have the xslt style sheet and it will not let me save the file once I edit it. Any ideas welcome. A: Since XML is text, any text editor will work fine. With XML, "data" can be just about anything in the file, including the structure, so what you will need to edit is entirely dependent on your application. In general, however, anything non inside angle brackets (< and >) is data, and also attributes on the elements (the things in the angle brackets) is also often data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583666", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Loop through all elements with class name 'blah' in jquery and use the contents of the element in a function This is what i'm trying to do in pseudo code Find all <td> Elements with Class name 'OSGridRef' For each <td> element pass the text of that <td> element into a function called ConvertToLatLong Update an <td> element in the same table row that has the class name 'LatLong' with the results of the function. I haven't the foggiest how to do this in regular JavaScript or in jQuery. Any Ideas? A: This should do it. When you say 'content' I assume you mean all the text inside? $(function() { $('tr:has(.OSGridRef)').each(function() { var content = $(this).find('.OSGridRef').text(); var result = ConvertToLatLong($.trim(content)); $(this).find('.LatLong').text(result); }); }); A: Hmm, this isn't going to be pretty considering that we're working with pseudocode only, but here goes: $('.OSGridRef').each(function() { var $t = $(this); $t.closest('tr').find('.LatLong').text( ConvertToLatLong($t.text()) ); }); A: Use each to do the iteration over the elements. $(function() { $('.OSGridRef').each( function() { var content = $(this).text(), // or .html() if you need the HTML latlong = ConvertToLatLong(content), $latlongholder = $(this).closest('tr').find('.LatLong'); $latlongholder.text(latlong); }); }); A: In jquery you can use selectors to find all elements needed then you can use the each() function to be able to call your "ConverttoLatLong" function. To update a element, you need to select it (with selector as seen before) then modify it value/text/etc. The documentation on jQuery.com could help you a lot A: $('.OSGridRef').each(function() { $('.LatLong').val(ConvertToLatLong($(this).val())); }) this is my first guess, i don't know if they are inputs or something else, but if you could give more details (like html) i could edit this
{ "language": "en", "url": "https://stackoverflow.com/questions/7583667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regex to replace file extension I would like a regex to replace the .html file extension with a / so www.example.com/page.html becomes www.example.com/page/. I want to also exclude a folder from this rule so anything within www.example.com/specialdir/ should be excluded. EDIT: This will be used in php A: Better to use htaccess: RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ $1.html [L,QSA] Source: Snipplr So it will change all http://somesite/someurl to http://somesite/someurl.html in server side. A: Search for (www\.example\.com/(?!specialdir/).*)\.html$ and replace all with \1 or $1, depending on your regex implementation. EDIT: In PHP: $result = preg_replace('%(www\.example\.com/(?!specialdir/).*)\.html$%', '\1', $subject);
{ "language": "en", "url": "https://stackoverflow.com/questions/7583669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to free Generic list object memory in C# In my Silverlight application I have created a generic list object with a custom class. I have approximately 3lacs (300,000) records in it. I have to bind different data to the same list frequently, but sometimes I get a out of memory error. How do I free the memory of generic list of a custom class in C#.NET. A: Only store what you need to in the List. A: I think, that it's enough, that you remove the unused Items from the List. So the List isn't growing to 300,000 Records. If no reference is set to an object (ReferenceCounter == 0) the gc will collect it,... in the future... So i think your main Questions should be, what do you want to do with more than 300,000 entries and is it nessesary to hold them all? If yes: Maybe a Proxy or Flyweight pattern would solve your Problem with ease. Due to the LazyLoading of the heavy Objects you can hold the List of small Objekts, which only loads their heavy content by explicit call to do so. Now it comes better, with the Flyweight pattern you can also store some basic Information (e.g. MetaData), for example of an Image, the Size, without loading the full heavy image. So if you can't reduce your Listentry count, just reduce the MemoryFootprint of your Objects. p.s.: The Flyweights could also forgett their heavy Objects after a defined time to shrink after a defined sleeping time. A: Clear the list and run GC.Collect(); twice. If I remember correctly, the first time the GC passes an unreferenced item it marks it for garbage collection, the second time it passes it removes it from memory. (If I'm wrong, please let me know.) There is still no guarantee that the memory will be cleared but it's as close as you can get afaik.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: examples of web services I had made numerous web applications in java.. I read a lot about web services But don't know how to make working example in web services? Also, don't have any idea about ejb,jmx,etc. Is it necessary to put web application on some server in order to implement web services? A: Depending on how you define a "web service", it can be as simple or as complex as you like. Many REST-based web services are just normal web applications that return JSON as their response instead of HTML. At the other end of the spectrum, there are SOAP (and others) that are much more involved, but can basically be called just like any other method by the consuming application. A: you can use Apache Axis2[1] to create and consume web services. This article[2] shows the steps to how to write a simple web service. [1] http://axis.apache.org/axis2/java/core/ [2] http://wso2.org/library/95
{ "language": "en", "url": "https://stackoverflow.com/questions/7583679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with python 2.4 and 2.4.4 in struct.unpack and win/lin i'm coding on a Linux debian machine with python 2.4. My neighbour with Windows XP and python 2.4.4 He can run this code: w1, w2, w3 = unpack("LLL", pack("LLHH", localtime, ipddr, counter, aid)) But when i try this code i become this error: w1, w2, w3 = unpack("LLL", pack("LLHH", localtime, ipddr, counter, aid)) struct.error: unpack str size does not match format Can it be the Version of python or maybe the system? A: Use the I format code instead of L. On your Linux machine, L isn't twice as long as H, it's four times as long -- 8 bytes (64 bits) instead of 4 bytes (32 bits). I should be 4 bytes (32 bits) on both. Edit: Make sure to read eryksun's comment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a way to get the size of a file in .NET using a static method? I know the normal way of getting the size of a file would be to use a FileInfo instance: using System.IO; class SizeGetter { public static long GetFileSize(string filename) { FileInfo fi = new FileInfo(filename); return fi.Length; } } Is there a way to do the same thing without having to create an instance of FileInfo, using a static method? Maybe I'm trying to be overly stingy with creating a new instance every time I want a file size, but take for example trying to calculate the total size of a directory containing 5000+ files. As optimized as the GC may be, shouldn't there be a way to do this without having to tax it unnecessarily? A: If you really, really need a static method, use the native GetFileSize or GetFileSizeEx API. But keep in mind this will require a handle to the file from the CreateFile API. You can also view the source of the FileInfo class: http://referencesource.microsoft.com/#mscorlib/system/io/fileinfo.cs#4ee673c1a4ecad41 A: Don't worry about it. First, allocation in .NET is cheap. Second, that object will be in gen 0 so it should be collected without much overhead. A: Don't worry about it. * *I've found a blog post of someone who measured the overhead of object creation in .NET (C# Object Creation Time Trials), and, as it turns out, creating 10,000 objects took 0.03 seconds, i.e., 3 µs per object. The time required to read the file length from the file system will surely dominate those 3 microseconds significantly. *A lot of static methods in the .NET framework internally create objects and call instance methods on them (you can verify this by looking at the reference source or by using some reflection tool). You assume that a static method is faster. Do not make such assumptions. If you have two ways to do the same thing, measure which one is faster.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: How to get the Map view zoomlevel with solo abject in robotium for android implementing apk file only I am working on robotium to test an android apk file.this apk file implementing robotium testcases .in mapview one button is inbuild buttons zoom in and zoom out buttons I would like to get the map view zoom level of certain stage. I don't know how to get with that by using solo in robotium. A: use solo.clickOnButton(0) its working fine in this function repeat multiple times
{ "language": "en", "url": "https://stackoverflow.com/questions/7583689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with For Loop and Array The below method code is a FOR loop which builds 26 arrays (one for each letter of the alphabet) from an SQLite database. The problem is that the return array called MultipleArray is only returning 16 arrays, and not 25 as it should. Can anyone spot why it is not returning the full 25 arrays ? EDIT - The problem seems to be that since the letter Q has no data in the database (which is correct) array 17 (letterQ) has no content. The statement which builds the mulptipleArray then terminates adding arrays at this point. Anyone know how I can fix this ? Thank you. - (NSMutableArray *)placesInfo { NSString *tmpLike = [[NSString alloc] init]; multipleArray = [[NSMutableArray alloc] init]; for (int i = 0; i < 26; i++) { NSMutableArray *retval = [[[NSMutableArray alloc] init] autorelease]; tmpLike = @""; switch (i) { case 0: tmpLike = @"A"; break; case 1: tmpLike = @"B"; break; case 2: tmpLike = @"C"; break; case 3: tmpLike = @"D"; break; case 4: tmpLike = @"E"; break; case 5: tmpLike = @"F"; break; case 6: tmpLike = @"G"; break; case 7: tmpLike = @"H"; break; case 8: tmpLike = @"I"; break; case 9: tmpLike = @"J"; break; case 10: tmpLike = @"K"; break; case 11: tmpLike = @"L"; break; case 12: tmpLike = @"M"; break; case 13: tmpLike= @"N"; break; case 14: tmpLike = @"O"; break; case 15: tmpLike = @"P"; break; case 16: tmpLike = @"Q"; break; case 17: tmpLike = @"R"; break; case 18: tmpLike = @"S"; break; case 19: tmpLike = @"T"; break; case 20: tmpLike = @"U"; break; case 21: tmpLike = @"V"; break; case 22: tmpLike = @"W"; break; case 23: tmpLike = @"X"; break; case 24: tmpLike = @"Y"; break; case 25: tmpLike = @"Z"; break; default: break; } NSString *query = [[NSString alloc] initWithFormat: @"SELECT Name, Description, Postcode, AddressLine1, ImageURL, Free, Area, OpeningTimes, NearestTube, Cost,UniqueID, URL, Number, FirstLetter FROM MainDetails WHERE FirstLetter = '%@%'",tmpLike]; sqlite3_stmt *statement; if (sqlite3_prepare_v2(_database, [query UTF8String], -1, &statement, nil) == SQLITE_OK) { while (sqlite3_step(statement) == SQLITE_ROW) { char *nameChars = (char *) sqlite3_column_text(statement, 0); char *desChars = (char *) sqlite3_column_text(statement, 1); char *postChars = (char *) sqlite3_column_text(statement, 2); char *addyChars = (char *) sqlite3_column_text(statement, 3); char *imageChars = (char *) sqlite3_column_text(statement, 4); char *freeChars = (char *) sqlite3_column_text(statement, 5); char *areaChars = (char *) sqlite3_column_text(statement, 6); char *openChars = (char *) sqlite3_column_text(statement, 7); char *nearChars = (char *) sqlite3_column_text(statement, 8); char *costChars = (char *) sqlite3_column_text(statement, 9); int uniqueID = sqlite3_column_int(statement, 10); char *urlChars = (char *) sqlite3_column_text(statement, 11); char *numberChars = (char *) sqlite3_column_text(statement, 12); NSString *name = [[NSString alloc] initWithUTF8String:nameChars]; NSString *description = [[NSString alloc] initWithUTF8String:desChars]; NSString *postcode = [[NSString alloc] initWithUTF8String:postChars]; NSString *address = [[NSString alloc] initWithUTF8String:addyChars]; NSString *image = [[NSString alloc] initWithUTF8String:imageChars]; NSString *free = [[NSString alloc] initWithUTF8String:freeChars]; NSString *area = [[NSString alloc] initWithUTF8String:areaChars]; NSString *openT = [[NSString alloc] initWithUTF8String:openChars]; NSString *near = [[NSString alloc] initWithUTF8String:nearChars]; NSString *cost = [[NSString alloc] initWithUTF8String:costChars]; NSString *url = [[NSString alloc] initWithUTF8String:urlChars]; NSString *number = [[NSString alloc] initWithUTF8String:numberChars]; PlaceObject *info = [[PlaceObject alloc] initWithUniqueID: uniqueID name : name description:description postCode:postcode addressOne : address image:image free:free area:area openingTimes:openT nearestTube:near cost:cost url:url number:number]; [retval addObject:info]; int x= [retval count]; NSLog(@"%d",i); if (x ==0) { NSLog(@"No content"); } switch (i) { case 0: letterA = retval; break; case 1: letterB = retval; break; case 2: letterC = retval; break; case 3: letterD = retval; break; case 4: letterE = retval; break; case 5: letterF = retval; break; case 6: letterG = retval; break; case 7: letterH = retval; break; case 8: letterI = retval; break; case 9: letterJ = retval; break; case 10: letterK = retval; break; case 11: letterL = retval; break; case 12: letterM = retval; break; case 13: letterN = retval; break; case 14: letterO = retval; break; case 15: letterP = retval; break; case 16: letterQ = retval; break; case 17: letterR = retval; break; case 18: letterS = retval; break; case 19: letterT = retval; break; case 20: letterU = retval; break; case 21: letterV = retval; break; case 22: letterW = retval; break; case 23: letterX = retval; break; case 24: letterY = retval; break; case 25: letterZ = retval; break; default: break; } [name release]; query = @""; [query release]; [description release]; [url release]; [number release]; [postcode release]; [address release]; [image release]; [free release]; [area release]; [openT release]; [near release]; [cost release]; [info release]; } sqlite3_finalize(statement); } } tmpLike = @""; [tmpLike release]; multipleArray = [NSMutableArray arrayWithObjects: letterA, letterB, letterC, letterD, letterE, letterF, letterG, letterH, letterI, letterJ, letterK, letterL, letterM, letterN, letterO,letterP, letterQ, letterR, letterS, letterT, letterU, letterV, letterW, letterX, letterY, letterZ, nil]; int x= [multipleArray count]; NSLog(@"Mulptilpe Array Contents: %d", x); NSLog(@"%@",multipleArray); return multipleArray; } A: EDIT - The problem seems to be that since the letter Q has no data in the database (which is correct) array 17 (letterQ) has no content. The statement which builds the mulptipleArray then terminates adding arrays at this point. Anyone know how I can fix this ? If you need into insert a nil value into your array, you use [NSNull null]. There's nothing magical about this value. It's just an object that you can later test against. You cannot insert a real nil into an NSMutableArray. A: I would start by simplifying your code. The two big switch statements are unnecessary. You can get drop the first one by getting rid of the tmpLike variable and replacing the query string with: NSString *query = [[NSString alloc] initWithFormat: @"SELECT ...blah blah blah... WHERE FirstLetter = '%c%'", 'A' + i]; I assume the letterA...letterZ are NSMutableArrays declared somewhere else. You can get rid of the second switch statement and all the letter* arrays by simply adding retval to multipleArray. [multipleArray addObject:retval] That way you're incrementally building multipleArray rather than trying to build it all at once at the end. Also if the query fails for any one letter, only that letter will be missing. The following letters will still be added. A: I am going to give a little hint about basic characters that will save you a lot of code! you can perform arithmetics on them to change letters. unichar letter = L'A' + i; tempLike = [NSString stringWithCharacters:&letter length:1]; Now the actual problem is you need to check each object for nil and replace it with a custom object (usually [NSNull null]) because once you pass the nil sentinel to the method it thinks that it is the end. A: I would suggest you . to implement code that check string before enter into database. if string is null then replace with @""(blank). Thanks A: Try this before your second switch statement: if (!retval) { retval = [NSMutableArray arrayWithObject:[NSNull null]]; } else if (![retval count]) { [retval addObject:[NSNull null]]; NSLog(@"No content"); } ....
{ "language": "en", "url": "https://stackoverflow.com/questions/7583691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Div problems using html, css, Javascript In an HTML document, I have created a div. In it, I created another div, and in this inner div I put a cross sign. I want to build an event function that closes the parent div when the user clicks on the cross sign. An example: <!doctype html> <html> <head><title>Div problems</title></head> <body> <div id="content"> <div id="box1"> <img src="people.gif"/> </div> <div id="box2"> <img src="camera.gif" height=30px width=30px/> </div> <div id="box3"> <img src="square.gif" height=30px width=30px/> </div> <div id="box4"> <img src="rectangle-image3.gif" height=30px width=30px/> </div> <div id="box5"> <img src="triangle.gif" height=30px width=30px/> </div> <div id="box6"> <img src="correct.gif" height=30px width=30px/> </div> <div id="box7"> <img src="exit.gif" height=30px width=30px/> </div> </div> </body> </html> The cross would be the "exit" image. Please tell me how to do it. A: Have you tried anything so far? Given this description, I guess just using a click event on the inner element to change the CSS of the outer element will work fine. Here's a quick example with jQuery: $(document).ready(function() { $('#innerElement').click(function() { $('#outerElement').hide(); }); }); This will effectively set the parent's CSS display to "none." Hiding the parent element will, of course, hide any containing elements, including the one being clicked. A: How is this idea. HTML: <!doctype html> <html> <head><title>Div problems</title></head> <body> <div id="content" style="position:relative"> <div id="box1"> <img src="people.gif"/> </div> <div id="box2"> <img src="camera.gif" height=30px width=30px/> </div> <div id="box3"> <img src="square.gif" height=30px width=30px/> </div> <div id="box4"> <img src="rectangle-image3.gif" height=30px width=30px/> </div> <div id="box5"> <img src="triangle.gif" height=30px width=30px/> </div> <div id="box6"> <img src="correct.gif" height=30px width=30px/> </div> <div id="box7" style="position:absolute;top:0;right:0" onclick="hideContent()"> <img src="exit.gif" height=30px width=30px/> </div> </div> </body> </html> JS: function hideContent() { document.getElementById('content').style.display="none"; } A: Like this should do it, say this is your markup: <div id="parent"><div><span>CROSS SIGN</span></div></div> And JQuery: $('#parent span').click(function() { $('#parent').hide(); }); This should do it. A: This code shows a simplistic approach to the problem, in pure javascript. You should be able to adapt it to your particular problem. <!doctype html> <html> <head> <title>Div problems</title> <script type="text/javascript"> window.onload = function() { var childLink = document.getElementById('sonlink'); childLink.onclick = function() { var parent = document.getElementById('parent'); parent.style.display = 'none'; return false; } } </script> </head> <body> <div id="parent">Outer div <div id="son">Inner div <a href="#" id="sonlink">+</a></div> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7583694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-8" }
Q: Is it possible to mock android services under unit tests? I'm trying to write unit tests for my android application and I want to mock my service class. I want to test some error behaviors in the service, such as connection errors or file not found. To simplify my question, I started a new Android Project and created an Activity and a Service class: MyAndroidProjectActivity.java package br.org.venturus.android; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View; import android.widget.TextView; import br.org.venturus.android.service.MyService; public class MyAndroidProjectActivity extends Activity { private MyService service; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder binder) { service = ((MyService.MyBinder) binder).getService(); } public void onServiceDisconnected(ComponentName className) { service = null; } }; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); { Intent service = new Intent(this, MyService.class); startService(service); bindService(service, mConnection, Context.BIND_AUTO_CREATE); } } @Override protected void onDestroy() { super.onDestroy(); // stop MyService { Intent svc = new Intent(this, MyService.class); stopService(svc); } } public void doChange(View view) { TextView tv = (TextView) findViewById(R.id.tvHello); tv.setText(service.getNewString()); } } MyService.java package br.org.venturus.android.service; import br.org.venturus.android.R; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; public class MyService extends Service { private IBinder binder; public MyService() { this.binder = new MyBinder(); } @Override public IBinder onBind(Intent intent) { return binder; } @Override public void onCreate() { super.onCreate(); } @Override public void onDestroy() { super.onDestroy(); } public class MyBinder extends Binder { public MyService getService() { return MyService.this; } } public String getNewString() { return getString(R.string.change); } } And I created a new Android Test Project with this unit class: MyAndroidProjectActivityTest.java package br.org.venturus.android.test; import android.test.ActivityInstrumentationTestCase2; import android.test.UiThreadTest; import android.widget.Button; import android.widget.TextView; import br.org.venturus.android.MyAndroidProjectActivity; import br.org.venturus.android.R; public class MyAndroidProjectActivityTest extends ActivityInstrumentationTestCase2<MyAndroidProjectActivity> { private MyAndroidProjectActivity mActivity; private TextView tvHello; private Button btChange; public MyAndroidProjectActivityTest() { super("br.org.venturus.android", MyAndroidProjectActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); // Get the activity and components { mActivity = this.getActivity(); tvHello = (TextView) mActivity .findViewById(br.org.venturus.android.R.id.tvHello); btChange = (Button) mActivity .findViewById(br.org.venturus.android.R.id.btChange); } } public void testPreconditions() { assertNotNull(tvHello); assertNotNull(btChange); } @UiThreadTest public void testChangeButton() { assertEquals(tvHello.getText(), getActivity().getString(R.string.hello)); btChange.performClick(); assertEquals(tvHello.getText(), getActivity() .getString(R.string.change)); } } When I run the unit tests, the pre conditions and the change button tests are fine. What I want to do, for instance, is to create a MyServiceMock and override the MyService.getNewString to return other value, and mock this object in the test. Something like this: MyServiceMock.java package br.org.venturus.android.test.service; import br.org.venturus.android.service.MyService; public class MyServiceMock extends MyService { @Override public String getNewString() { return "This is the new value!"; } } Is that possible? A: Yes, it's possible and I think the example of the MyServiceMock.java above is also an alternative. There are a few mocking frameworks out there that you can use for this. I have some experience with Mockito. You can just mock the MyService class and specify that when the getNewString method is called, return a string "This is the new value!". MyService myServiceMock = Mockito.mock(MyService.class); Mockito.doReturn("This is the new value!").when(myServiceMock).getNewString(); You can also use the Mockito.doThrow() method to throw an exception when a mock method is called: Mockito.doThrow(new RuntimeException()).when(mockedList).clear(); //following throws RuntimeException: mockedList.clear();
{ "language": "en", "url": "https://stackoverflow.com/questions/7583697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Winforms application shows differently on different computers when using Infragistics components and resizing routines I am developing a GUI using Winforms. Everything looks fine on the majority of testing computers (as in, the UI is displayed in the same way and accordingly to the pc on which the GUI was developed). On a single laptop, though, it happens that several elements are not displayed correctly (wrong sizes, or problems in redrawing). I am running out of tests to figure out what could possibly we wrong; all the computers run Windows 7 on various screen resolutions. I am using Infragistics components to build the UI. Any thoughts? edit: some examples. On the "broken" laptop, some tabs (part of an UltraWinTab) are invalidated and not redrawn after a minimize/restore command, you get only the background of the tab but no components. Some other controls are inexplicably drawn at a much smaller size (instead of filling the area, I get big empty bottom and right bands). A: We've had issues with this as well. A Windows.Forms application with Infragistics controls looked good on Windows XP, but on W7 all kinds of resizing issues started to occur. It took me ages to find out what happened. Of course, first I assumed it had to do with Infragistics, but I just didn't find a clue anywhere on any forum. At last I stumbled upon this link, where it was explained that beyond a certain nesting hierarchy of controls, resizing events are no longer fired. We have a UI framework and for us it was sufficient to make a derivative of System.Windows.Forms.SplitContainer with this override: // HACK: under Windows7, controls do not always redraw to their whole rectangle after restoring their size. protected override void OnSizeChanged(EventArgs e) { if (Handle != null) // Can be null because the event is invoked before the handle is created. BeginInvoke((MethodInvoker)(() => base.OnSizeChanged(e))); } Because we have Infragistics controls (grid, dock manager) on SplitContainers. Maybe Infragistics controls have a deep nesting level, making this happen sooner than with other controls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583699", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# Excel Interop: How to format cells to store values as text I'm writing numbers to an Excel spreadsheet from a DataTable and all of these numbers are 5 digits long with preceding 0s if the number itself is less than 5 digits long (so 395 would be stored as 00395, for example). When entering these numbers into Excel (using C#), it's storing them as numbers and eliminating the preceding 0s. Is there any way I can format the cells from C# in order to get the values to be stored as text rather than numbers? A: You can SomeRange.NumberFormat = "@"; or if you prefix the value with a ' and write it to the cell excel will treat it as a number-stored-as-text and provide a visual cue. A: This answer just solved a major problem with a solution from one of our company's software, I had to retrieve the value as displayed, but once I set it to the new sheet, it was being inserted as a number. Simple solution. I cant vote up as yet, but down follows how it ended up. for (int h = 1; h <= 1; h++) { int col = lastColl(sheets); for (int r = 1; r <= src.Count; r++) { sheets.Cells[r, col + 1] = "'"+src.Cells[r, h].Text.ToString().Trim(); } } A: //where [1] is column number which you want to make text ExcelWorksheet.Columns[1].NumberFormat = "@"; //If you want to format a particular column in all sheets in a workbook - use below code. Remove loop for single sheet along with slight changes. //path were excel file is kept string ResultsFilePath = @"C:\Users\krakhil\Desktop\TGUW EXCEL\TEST"; Excel.Application ExcelApp = new Excel.Application(); Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultsFilePath); ExcelApp.Visible = true; //Looping through all available sheets foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets) { //Selecting the worksheet where we want to perform action ExcelWorksheet.Select(Type.Missing); ExcelWorksheet.Columns[1].NumberFormat = "@"; } //saving excel file using Interop ExcelWorkbook.Save(); //closing file and releasing resources ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(ExcelWorkbook); ExcelApp.Quit(); Marshal.FinalReleaseComObject(ExcelApp);
{ "language": "en", "url": "https://stackoverflow.com/questions/7583704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: I need to change a tables unique ID column Not sure the best way to do this or if there is even a single best answer but here is the problem: I have a SQL Server 2000 database that consists of at least 13 tables. Some of the tables have a unique id (SysName) so that there can only be one unique SysName value (alpha001, alpha002, alpha003, etc). With me so far? Now, the client is wanting to be able to insert multiple sysnames values in the database (alpha001, alpha001, alpha001, alpha002, alpha002, alpha003, alpha003, alpha003, alpha003, alpha003, etc). On top of that, if you change the value for a sysname (alpha001 to beta001) in one table, the value in some of the other tables are also updated (I'm having a brain fart about what this is called at the moment). I'd also like to add a new column (SysNameID) and set it to autoincrement. What is the best way to do this so that it will go through the database and just add the SysNameID values (1,2,3,4,5,6...) so that I do not have to rebuild the table? I'm thinking I need to add a SysNameID column to all the affected tables and set the (brain fart term) between the tables to retain the correlation (for data integrity purposes). If this is request is unclear, please leave a comment and I'll do the best I can to answer it. Some of you guys are very smart so you may have to dumb it down for me. :) A: I don't totally understand what your question/challenge is with the current sysname column .... but for the second part: yes, you can easily add an autoincrement column to your table(s), and no, you won't have to do anything (like "rebuild the table" - whatever that was supposed to be.....) - SQL Server will fill the existing rows with autoincrement values for you.$ ALTER TABLE dbo.YourTableNameHere ADD SysNameID INT IDENTITY(1,1) NOT NULL I usually recommend making that IDENTITY column either your primary (and clustered) key for the table, or if that's not possible, at least put a UNIQUE CONSTRAINT on the column to prevent duplicate values from being inserted: ALTER TABLE dbo.YourTableNameHere ADD CONSTRAINT UC_SysNameID UNIQUE(SysNameID) A: Basic process: Make sure you have a current backup and do not attempt to do this on prod without a through test on develpment first. This is so extensive a change, you might want to restore prod to a new dev instance because it will be time-consuming and tricky and other development will be interfered with while you do this. You add the identity column to the parent table called SysNameID (see @marc_s' answer for details) You add an int column to each child table also called SysNameId. It is not an autoincrementing column and must allow nulls. You Update this column by using the current sysname columns to find the id assciated with that sysname. Once all the columns are populated you set the column to not allow nulls and create the foreign key to the parent table. The surrogate keys should not change, so you don;t really need to cascade update. Finally you drop the sysname column from the child tables and adjust all the code that uses it to join to the parent table and look it up. Alternatively, you rename each child table and create a view that joins the child table to the parent and gets the sysname column from there. That should ensure existing code doesn't break. There is no simple way to meet your requirement. You are changing the very fundamentals of how your database works. It has the potential to affect virtually every query against the child tables. It may affect reports (which are likely sorted by sysname which is now no longer unique). This is a major change and to do it properly could take months. Suggested reading: http://www.amazon.com/Refactoring-Databases-Evolutionary-Database-Design/dp/0321293533/ref=sr_1_1?ie=UTF8&s=books&qid=1268158669&sr=8-1
{ "language": "en", "url": "https://stackoverflow.com/questions/7583708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Including .cpp at end of template header file I was reading an older data-structures book and it said that when you're doing template class programming you should include the .cpp at the end of the .h file. As far as I know you have to do full function implementations in your .h file for any template class member functions - it's due to the way the template compiler works. The only functions I was taught could be put in a implementation file for a template class were template specialization functions i.e.: template<> Class<Type>::function_name(). Why would this book to suggest to include the .cpp at the end of the .h? is this just a way of separating the implementations into different files while getting them to compile with the header? and if so, where would you put real specializations - I'm guessing they couldn't go in the .cpp included by the header. A: This is probably old parlance, and I think your analysis of separation of implementation and declaration is correct. Back when this particular book was written, the author probably thought of a cpp file as the file where definitions resided, and h files as the files where declarations resided. Putting real explicit specializations into the former file would, naturally, be lethal (or at least useless) to the linker because of repeated definitions. Nowadays, I'd avoid naming the definitions file .cpp. A: First, there's no rule that you have to have the implementations of the templates in your .h (or .hpp, or .hh) file; in fact, for anything but the simplest templates, I would recommend against doing so. You do have to include the implementation, regardless of the file. What the author probably had in mind was to put the implementation in a .cpp file, and include that. I'd recommend finding a different name, however, since most people (and some IDE's) will suppose that you should compile all .cpp files. A common convention where .cc and .hh are the usual extensions for sources and headers is .tcc for template implementations; in a Windows world (where .cpp is almost universal), I'd recommend something like .tpp. Note that the earliest implementations of templates required the implementation to be in a .cpp. These implementations didn't require (or allow) it to be included, however; the compiler searched for the .cpp (or .cc) corresponding to the .hpp (or .hh) file in which the template class definition or function declaration appeared, and generated a dummy source file which included it (and anything else which was necessary). A: Most likely the author prefers having declaration and definition in different files, I can guess this is because it makes it easier to jump between declarations and definitions. But having "cpp" file extension is a bit confusing. Usually those files are called "ipp" for "Inline C++". A: As far as I know you have to do full function implementations in your .h file for any template class member functions - it's due to the way the template compiler works. May be the book assumed you have the full function implementations in your .cpp file. If full specializations are in cpp file, they should not be included in header file. Most likely it wont compile if you did so. Because compiler will see multiple definitions of the same function as header file will generally be included in multiple source files. A: If you want to use a template, the entire template definition has to be visible in the TU that instantiates the template. So you could simply put full definitions in the header file. It's only if you really want to keep the class definition and class member function bodies separate, then you might be tempted to put those function definitions into a separate file. However, the above rule still applies, so you'll have to include the separate file together with the header in order for anyone to be able to use the template. It's a matter of taste. If the member function bodies are short, you might as well define them inline. Also bear in mind that functions that are defined inside the class definition are implicitly declared inline, while you'd have to specify that explicitly if you write the bodies separately. A partially specialised templated is still a template, so the same rules apply. A fully specialized class template is just an ordinary class, so you treat is as such: // FooInt.hpp template <typename> class Foo; template <> class Foo<int> { // your class here }; One thing you may have had in mind is "explicit template instantiation", a la template class Foo<int>;. That's something else; leave a comment if you're interested in using that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583710", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: gwt-unit cache does not exist I am facing this error when i try to commit my SVN . svn: 'C:\Users\wageeha junaid\workspace\Copy of HOLS\gwt-unitCache\gwt-unitCache- 00000132A65F0D8B' does not exist A: you should not commit the unitCache to the versioning system. use svn:ignore for that purpose. A: Easy fix if you are using Eclipse: Right click on the gwt-unitCache folder and press Refresh. The problem is that you need to update the folder from the package explorer before you commit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to pass parameters / arguments using jQuery? <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> function chooseLocationType(location, title, demand){ alert(demand); } <body> <input name="tempstaff_location" class="ques_radio" id='tempstaff_location' value='location_' type="radio" onclick="chooseLocationType('a','b','c')" /> </body> I have the folowing code, on click of the radio box , There is one conditional code based on this to show hide some dive. And there is one more jQuery script which run on Click and used function. jQuery(this) input[name=tempstaff_location]").click(function(){ if(jQuery(this).attr("checked")){ }); How can I combine both script in one. A: Having your: <script type="text/javascript"> function chooseLocationType(location, title, demand){ alert(demand); } </script> I would, as you don't specify where the values 'a', 'b', and 'c' come, add them as data attributes to your input <input name="tempstaff_location" class="ques_radio" id='tempstaff_location' value='location_' data-location="a" data-title="b" data-demand="c" type="radio"/> And finally access them in the event callback $("input[name=tempstaff_location]").click(function(){ if(jQuery(this).attr("checked")){ chooseLocationType($(this).data('location'), $(this).data('title'), $(this).data('demand') ); } }); A: If the parameters vary with each element store them in a data tag within the element. Then extract them in the click handler. That way you can apply a single handler and do both. It will be easier if you change chooseLocationType to accept an array of location types. <input name="tempstaff_location" class="ques_radio" id='tempstaff_location' value='location_' type="radio" data-location="a,b,c" /> $('input[name=tempstaff_location]").click(function(){ if(jQuery(this).attr("checked")){ chooseLocationType( $(this).data('location').split(/,/) ); } }); If the values are fixed then it's much easier, you just move the call into your handler. <input name="tempstaff_location" class="ques_radio" id='tempstaff_location' value='location_' type="radio"/> $('input[name=tempstaff_location]").click(function(){ if(jQuery(this).attr("checked")){ chooseLocationType( 'a','b','c' ); } }); A: When you assign an inline onclick attribute, it is just a function, basically equivalent to this code: element.onclick = function () { chooseLocationType( 'a','b','c' ); }; In your JavaScript file, you can just write document.getElementById("tempstaff_location").onclick = function () { if(this.checked) { chooseLocationType( 'a','b','c' ); } } Getting an element by its id is generally better than selecting it by a tagname and attriute. A: You can directly call click event on page load instead of calling in radio button html. If following is the html: <input name="tempstaff_location" class="ques_radio" id='tempstaff_location' value='location_' data-location="a" data-title="b" data-demand="c" type="radio"/> Then you can call following script : jQuery('input[name=tempstaff_location]').click(function(){ if(jQuery(this).attr('checked')) { chooseLocationType(jQuery(this).attr('data-location'),jQuery(this).attr('data-title'),jQuery(this).attr('data-demand')); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7583717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: pass a variable into chrome.tabs.onUpdated.addListener() - Chrome extension I need to access the tab.Id of a window that my Chrome extension has created. Here's the code I'm using to create a window: chrome.windows.create({ url: fullUrl, width: w, height: h, type: 'normal' }, function() { chrome.windows.getCurrent(function(window) { chrome.tabs.getSelected(window.id, function (response){ var ourWindow = response.id alert('created a window with a tab id of: ' + ourWindow); }); }); }); And the code where I'd like to be able to access that 'ourWindow' variable we previously set: chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { if(changeInfo.status == "loading") { if(tabId == ourWindow) { alert('Holy smokes, this is the window we created!'); } } }); I can't seem to access the variable, since it was created outside of the onUpdated.addListener. Any ideas? A: Just move this var into global variable space: var ourWindow = null; ... chrome.tabs.getSelected(window.id, function (response){ ourWindow = response.id; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7583720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Modal FormPanel & DatePicker & MessageBox, how to manage masks I'm having some problems with the following scenario : * *I have a nested list which has a detailCard. *When I click the detailCard I pop a FormPanel, now the detailCard is masked. *FormPanel has a DatePicker, so after selecting a value with the picker I return to the FormPanel but the mask is gone. *Also when I show a Messabox from the FormPanel I can still click the FormPanel without dismissing the MessageBox. So I the basic question is, when you show a FormPanel as modal and you have another component which hides the mask on hide, is there a way to manage the mask so it only hides when you close the form? Thanks for any ideas. A: I've a similar problem. It seems that as per the picker shows as modal, when the element is picked, the picker hides any mask. I've been looking for picker events to handle that, but no luckily yet, so, if you have the answer, please update this thread. Update: [Solution found] Just add a listener to the hide "method" of the picker and do what you need to restore the mask. xtype: 'datepickerfield', name: 'date', label: 'Date', picker: { listeners: { hide: function() { // Prevent mask hide default behavior of picker hide event. HandleLoadingMask(); }, }, }, HTH, Milton.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NetBeans: How to create a web service client that consumes a SSL protected Metro service? I am trying to add a web service reference to my application in NetBeans 7.0.1. The Metro webservice is protected with SSL and is hosted on the same computer that I want to run the client on. I am using the 'New Web Service Client' wizard, but when I submit an SSL protected WSDL, I get the following error message: Problem with downloading wsdl or schema file. Check the URL, proxy settings, or whether the server is running. URL: https://192.168.0.200:8181/MyApp/myService?wsdl Metro User Guide - To Secure the Example Web Service Client Application (SSL) states: In the step where you are directed to cut and paste the URL of the web service that you want the client to consume into the WSDL URL field, type https :// fully-qualified-hostname:8181 /CalculatorApplication/CalculatorWSService?wsdl (changes indicated in bold) to indicate that this client should reference the web service using the secure port. The first time you access this service, accept the certificate (s1as) when you are prompted. This is the server certificate popping up to confirm its identity to the client. In some cases, you might get an error dialog telling you that the URL https:// fully-qualified-hostname :8181/CalculatorApplication/CalculatorWSService?wsdl couldn't be downloaded. However, this the correct URL, and it does load when you run the service. So, when this error occurs, repeat the steps that create the Web Service Client using the secure WSDL. The second time, the web service reference is created and you can continue creating the client. No matter how many times I try I still get the same error message (there are no proxies set and the server is running with the services deployed). The WSDL gets displayed in browser after accepting the certificate. If I enter the basic WSDL URL (the one without HTTPS), the wizard accepts it and generates the client. What do I need to do to get this work? UPDATE The same applies if I run client and service on different machines. I am using the default development certificate. Retriever output: Error: An I/O error occured. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target` Do I have to set keytore and truststore in VMargs? What if I want to have this service reference in the same web application that contains the web services? A: Answer found here: You have to run NetBeans with the following options: <NETBEANS_HOME>/bin/netbeans.exe -J-Djavax.net.ssl.trustStore=<AS_HOME>/domains/domain1/config/cacerts.jks -J-Djavax.net.ssl.keyStore=<AS_HOME>/domains/domain1/config/keystore.jks -J-Djavax.net.ssl.trustStorePassword=changeit -J-Djavax.net.ssl.keyStorePassword=changeit I actually set those in <NETBEANS_HOME>/etc/netbeans.conf, in netbeans_default_options. I still got an error though, this just resulted that I am able to generate client code for SSL protected services. Running a simple WS call results in this: EDIT IMPORTANT The following only happens if you are using the older JAX-WS libraries! Exception in thread "main" javax.xml.ws.WebServiceException: Cannot find 'https://localhost:8181/myApp/myService?wsdl' wsdl. Place the resource correctly in the classpath. This can be solved by setting the clients DATASTOREWS_WSDL_LOCATION property with a method like this: private static URL getURL() { try { return new URL("https://localhost:8181/myApp/myService?wsdl"); } catch (MalformedURLException ex) { Logger.getLogger(DataStoreWS_Service.class.getName()).log(Level.SEVERE, null, ex); return null; } } This is needed only if you generate it for a simple Java Application, because the generated client code differs for Java Web Application. Also, I just couldn't get it working with a fully qualified hostname, like my local IP. The only thing that worked was localhost. One important thing: Don't forget to bundle the same Metro libraries as on the service side! NB bug report.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: recognize swipe gesture on UITableviews inside a UIScrollView with paging enabled Edit: I've begun implementing since I had first asked the question, so I'll rephrase the question with updated. I've set up a UIScrollView with a UIPageControl and a series of UITableviews as subviews. It works except for one problem: the subviews are each tableviews with horizontal swipe gestures on the table (the purpose of this swipe is to slide a cell and reveal a menu underneath the cell). They don't work unless I disable scrolling on the UIScrollView. But I still need a user to be able to swipe the scroll view outside when swiping outside the table. Any guidance on how I can achieve this effect (swipe inside the table picked up by the table, swipe outside the table picked up by the scroll view). Original: I'd like to set up a series of UITableviews horizontally in a UIScrollView with paging enabled. The tableviews will use a horizontal swipe gesture recognizer (to slide the cell to the side and reveal a submenu). And ideally horizontal swiping on the scroll view outside of a table (e.g. on the top of the scroll view) will cause UIScrollView to page to the next table. Will the two swipe gestures work the way I hope? Or will the UIScrollView interfere? If so how would you correct it? Any guidance would be great. A: Here's what I'm going with so far: * *ScrollView scrolling remains disabled. *When handling swipe gesture on tableView, added this test: if locating the cell that the swipe was over returns nil, then invoke a scroll of the UIScrollView to the next page, and update currentPage of the PageControl object. This works well enough, thought this way I'm missing the very real-time scrolling of having the UIScrollView sense swipe touches (in another words, if I swipe just a little bit and stop, the view still pages). Still would love to hear a better solution from the SO community. Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/7583748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: soapUI vs rest-assured for REST API testing What's better for testing a REST API in built in Spring 3.1, soapUI or rest-assured? oAuth 2.0 is used for authentication. A: It depends on who is going to create and maintain the tests. If it is going to be the QA then soapUI is the right tool. If it is going to be the developers then rest-assured. A: You can also use other tools for REST API Testing like RestCase, Runscope or vRest. There are also many rest clients available like Postman and etc..
{ "language": "en", "url": "https://stackoverflow.com/questions/7583749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: In Chrome td border-bottom overlap In chrome and safari td border overlap over other. I'm using css .basketTable tr td { background-color: #FFFFFF; border-top: 1px dotted #666666; color: #333333; padding: 18px 9px 5px 0; text-align: left; vertical-align: top; } Totally clueless. I'm sure someone must have faced the same issue, please suggest. CSS: .basketTable{ border-collapse:collapse;} .basketTable th { padding:5px 10px 5px 0; border-top:4px solid #666; } .basketTable tr td { background-color: #fff; border-top: 1px dotted #666; padding:18px 9px 5px 0; text-align:left; color:#333; vertical-align:top; } HTML: <table width="500px" border="0" class="basketTable" summary="table"> <thead> <tr> <th class="productCol">Produkt</th> <th class="articleCol">Art.nr.</th> <th class="quantityCol">Antal</th> <th class="unitPrice">Pris per styck</th> <th class="totalPrice">Totalt</th> </tr> </thead> <tbody> <tr> <td><a href="/alarms/baby_monitors/Pr362455"><img title="product" src="/medias/sys_master/8796144205854/36-2455_t.jpg" alt=""></a><p>Babytalker 1010 PMR Baby Monitor-Small</p></td> <td class="productCode">36-2455</td> <td><span class="quantity">1</span></td> <td><span class="price">5,84<span>(6,49)</span></span></td> <td colspan="4" class="last-child">5,84</td> </tr> <tr> <td><a href="/alarms/baby_monitors/Pr362455"><img title="product" src="/medias/sys_master/8796144205854/36-2455_t.jpg" alt=""></a><p>Babytalker 1010 PMR Baby Monitor-Small</p></td> <td class="productCode">36-2455</td> <td><span class="quantity">1</span></td> <td><span class="price">5,84<span>(6,49)</span></span></td> <td colspan="4" class="last-child">5,84</td> </tr> </tbody> </table> A: Try table{border-collapse:separate;}. A: Try td{overflow:hidden;}, it removes the overlapped parts from outside the border.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a formal definition of session integrity regarding servlets? This question is related to another existing SO question. HttpServletRequest's getSession(boolean) method mentions session integrity, but it does not define the concept. I could not find an offical definition. Is there any? Does anyone know what rules formally define when a session is in or out of integrity? Thanks. A: It refers to the concept of linking the server session with the client (web browser) session with a cookie. I'm not sure how familiar you are with java web apps, but the Servlet containers can track sessions by adding a parameter to the url (usually called jsessionid) or by sending a cookie to the client. I think it gets confusing because session tracking is a synonym of session integrity. A: I don't think there is a special meaning for term "session integrity". Session is just a data store maintained between user requests for application specific data. While client provides same and valid session id with her requests, application is guaranteed to have consistent session data i.e what application has put into session, it will also get back. So, I would treat "integrity" as using common understanding of that word: Integrity is a concept of consistency of actions, values, methods, measures, principles, expectations, and outcomes. A: Session integrity is dealt by the servlet container. Session integrity means the consistency of sessions: i.e. session tracking. The servlet container can either use (as far as I know) 2 types of session tracking: * *Cookie, by storing JSESSIONID in a cookie. *URL Rewriting, by appending the JSESSIONID as a fragment (not as a parameter, and there's reasons why) in the URL. The servlet container must make sure that it tracks its sessions with consistency. Resources: * *Java Servlet (Wikipedia)
{ "language": "en", "url": "https://stackoverflow.com/questions/7583752", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google map using intent I have 2 tabs in my application and one of that is for location Map. So i have set that tab to start an activity to show the map. code: Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?saddr=20.344,34.34&daddr=20.5666,45.345")); startActivity(intent); I dont want to use googleAPi key and get the map, and i want to do it by intent. But the problem here is, the map will be displayed over the complete screen and the tabs are not visible. Is there a way i can display some button/ tab along with the map when the map is displayed using an intent ( not Mapactivity and setting APIkey ) A: Your code (the Intent) starts Google Maps as a separate application. This is what Intents are supposed to do. If you want Maps as a part of your application (visible within Tabs) you will need to use MapActivity or `MapView' (and provide the Maps key, of course). There is no way around it. For more details see http://code.google.com/android/add-ons/google-apis/maps-overview.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7583755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Switch elements position with CSS3? With CSS3, is it possible to switch 2 elements position? I think I remember someone showing me this with items in a list but I can't seem to find the style by googeling it. The reason I need this is im mobile optimising a site with media queries. On mobile devices my site has a 1 column layout, and currently blog images appear before the blog titles. I want these the other way around and I can't currently change the source order in the html. Thanks A: Of course. Using your media query to trigger this, you'd just set the position of the elements where you want them using any positioning property that works, including floats. But without the markup, I can't guess at what you have.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting foreground window size wrong all the time I am writing a program on c# that implements mouse and keyboard hooks and once a specified key clicked it will go and grab foreground window and save it's x,y, height and width into xml file. I am not sure what is wrong, but I keep getting wrong sizes and wrong parameters. I would appreciate a help on this one as I been struggling for two days with it now. Bellow is relevant code. Standard declarations: //rectangle for the windows size [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left; public int Top; public int Right; public int Bottom; } //win API [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] public static extern IntPtr GetForegroundWindow(); [return: MarshalAs(UnmanagedType.Bool)] [DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)] public static extern bool SetForegroundWindow(IntPtr hwnd); [DllImport("user32.dll", SetLastError = true)] static extern bool GetWindowRect(IntPtr hWnd, ref RECT Rect); And the relevant code itself void mouseHook_MouseDown(object sender, MouseEventArgs e) { this.handle = GetForegroundWindow(); } #region keyboard pressed void keyboardHook_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F9) //if slot selected { RECT Rect = new RECT(); SetForegroundWindow(this.handle); //this.handle = GetForegroundWindow(); GetWindowRect(this.handle, ref Rect); Grid newSlot = new Grid(); newSlot.topX = Rect.Top; newSlot.topY = Rect.Left; newSlot.width = Rect.Right - Rect.Left; newSlot.height = Rect.Bottom - Rect.Top; layoutGrid.Add(newSlot); lbl_slots.Text = layoutGrid.Count().ToString(); } else if (e.KeyCode == Keys.F10) //if main stack slot selected { RECT Rect = new RECT(); SetForegroundWindow(handle); GetWindowRect(GetForegroundWindow(), ref Rect); for (int i = 0; i < layoutGrid.Count(); i++) //selecting slot for main stack { layoutGrid[i].slot_number = i + 1; //setting slots numbers if (layoutGrid[i].topX != Rect.Top && layoutGrid[i].topY != Rect.Left) layoutGrid[i].is_stack = false; else { layoutGrid[i].is_stack = true; lbl_stackSlot.Text = (i + 1).ToString(); } } } } EDIT: I have tried to use both public struct RECT and Rectangle, the values with RECT I receive seems to be random, I mean left and top and height and width, sometimes it will find the proper points , but sometimes it seems completely random ones. The values I receive with Rectangle seems to have proper left and top but return wrong height and width. A: I finally found a solution. Figured out will post it here if anyone ever runs into same problem. I ended up using GetWindowInfo instead of GetWindowRect and it is worked like charm. Took the code example from and article I found online http://kenneththorman.blogspot.com/2010/08/c-net-active-windows-size-helper.html Thanks to everyone who tried to help. A: Using System.Drawing.Rectangle is incorrect. The fields do not match. Your definition of RECT is correct. I'm guessing a little, but your problem could be related to the comment at the bottom of the GetWindowRect MSDN topic. Apps under Vista that are not linked with WINVER=6 will receive a misleading set of values here, that do not account for the extra padding of "glass" pixels Vista Aero applies to the window. This appears to happen even in Aero Basic (without Glass) to retain sizing consistency. The workaround (if you don't want to set WINVER=6) seems to be to dynamically bind to dwmapi.dll and use GetProcAddress() to obtain the DwmGetWindowAttribute() function, and call it with the DWMWA_EXTENDED_FRAME_BOUNDS argument to request the genuine window frame dimensions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583762", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL : How can I use sub query in a query with group by section? How can I use sub query in a query with group by section? I use SQL Server 2008 R2 AND Delphi 2010 I receive this error: Cannot perform an aggregate function on an expression containing an aggregate or a sub query. Like this query : select t1.sen, sum(t1.d1)as d1, sum(t1.d2)as d2, sum(t1.d1+t1.d2) as d_sum, Round((sum((1000*(t1.d1+t1.d2))/(9500-( select sum(t2.t_shab+t2.t_rooz) from tbl1 t2 where FCode=81 AND DCode=1 AND t2.sen<=t1.sen )))),1) as SSS from tbl1 t1 where FCode = 81 AND DCode = 1 group by t1.sen A: Without any warranty, you can try, if it doesn't work let me know, I'll delete my answer create function getSumBSen(@pfcode number, @pdcode number, @pSen number) returns number as begin declare @r number; select @r =sum(t2.t_shab + t2.t_rooz) from tbl1 t2 where t2.FCode = @pfcode and t2.DCode = @pdcode and t2.sen <= @pSen group by t2.FCode, t2.DCode; return (@r); end; select t1.sen, sum(t1.d1) as d1, sum(t1.d2) as d2, sum(t1.d1 + t1.d2) as d_sum, Round((sum((1000*(t1.d1+t1.d2))/(9500-getSumBSen(t1.FCode, t1.dcode, t1.sen)))),1) as SSS from tbl1 t1 where t1.FCode = 81 and t1.DCode = 1 group by t1.sen; memento: * *Function creation added, it won't let me actually fix the code because my edit is too short. So I had to write some more miscellaneous junk so that the code fix will be accepted. A: Try this: DECLARE @tbl1 AS TABLE ( FCode INT ,DCode INT ,sen INT ,d1 INT ,d2 INT ,t_shab INT ,t_rooz INT ) ; SELECT * FROM ( SELECT t1.sen ,SUM(t1.d1) AS d1 ,SUM(t1.d2) AS d2 ,SUM(t1.d1 + t1.d2) AS d_sum ,ROUND((SUM((1000 * (t1.d1 + t1.d2)) / (9500 - factor.factor))), 1) AS SSS FROM @tbl1 AS t1 INNER JOIN ( SELECT t1.sen ,SUM(t2.t_shab + t2.t_rooz) AS factor FROM @tbl1 AS t2 INNER JOIN @tbl1 AS t1 ON t1.FCode = 81 AND t1.DCode = 1 AND t2.FCode = 81 AND t2.DCode = 1 AND t2.sen <= t1.sen GROUP BY t1.sen ) AS factor ON factor.sen = t1.sen WHERE FCode = 81 AND DCode = 1 GROUP BY t1.sen ) AS X ; A: You should be able to put your sub-query under FROM clause, following this general pattern: SELECT TABLE1.ID, SUM(TABLE1.A), ROUND(SUM(T2.B1), 2) FROM TABLE1, (SELECT SUM(B) B1 FROM TABLE2 WHERE ...) T2 GROUP BY TABLE1.ID Trying to "translate" your query, you'll probably get something similar to this: select t1.sen, sum(t1.d1)as d1, sum(t1.d2)as d2, sum(t1.d1+t1.d2) as d_sum, Round((sum((1000*(t1.d1+t1.d2))/(9500-( t2a.s )))),1) as SSS from tbl1 t1, ( select sum(t2.t_shab+t2.t_rooz) s from tbl1 t2 where FCode=81 AND DCode=1 AND t2.sen<=t1.sen ) t2a where FCode = 81 AND DCode = 1 group by t1.sen A: Its the true way create function getSumBSen2(@pfcode INT, @pdcode INT, @pSen INT) returns int as begin declare @r int; select @r= sum(t2.t_shab + t2.t_rooz) from tbl1 t2 where t2.FCode = @pfcode and t2.DCode = @pdcode and t2.sen <= @pSen; return (@r); end; GO select t1.sen, sum(t1.d1) as d1, sum(t1.d2) as d2, sum(t1.d1 + t1.d2) as d_sum, Round((sum((1000*(t1.d1+t1.d2)+0.01)/(9500-(dbo.getSumBSen2(t1.FCode, t1.DCode, t1.sen))))),1) as SSS from tbl1 t1 where t1.FCode = 81 and t1.DCode = 1 group by t1.sen;
{ "language": "en", "url": "https://stackoverflow.com/questions/7583767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Refactoring spec code related at the end I am using Ruby on Rails 3.1.0 and the rspec-rails 2 gem. I would like to refactor the following sample code in a my spec file: describe "Making things" do it "should make a thing" do # Make the thing ... # This is the same statement as that present in the "should make another # thing" example (read below for more information) response.body.should include("Hello World") end it "should make another thing" do # Make another thing ... # The same statement as that present in the "should make a thing" example response.body.should include("Hello World") end end How can I refactor the above response.body.should include("Hello World") code so to write less code? That is, how can I test the response.body content by using one statement valid for both spec examples? A: Use shared_examples_for. Like this: describe "Making things" do before do @user.new end shared_examples_for "normal case" do it "shows hello world" do response.body.should include("Hello World") end # more tests could be here end context "making a thing" do before(:each) do # make thing end it_should_behave_like_a "normal case" end context "making another thing" do before(:each) do # make another thing end it_should_behave_like_a "normal case" end end See documentation here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to update the EntitySet - because it has a DefiningQuery and no element exist I am using Entity Framework 1 with .net 3.5. I am doing something simple like this: var roomDetails = context.Rooms.ToList(); foreach (var room in roomDetails) { room.LastUpdated = DateTime.Now; } I am getting this error when I try to do: context.SaveChanges(); I get the error: Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exists in the <ModificationFunctionMapping> element to support the current operation. I am doing lots of updates on the context and not having any issues, it's only when I try to update this particular entity. All my searching shows up the same thing, that there is no primary key declared on the entity that I'm trying to update. But alas, I do have a Primary key declared... A: The error may have occurred if your table doesn't have a primary key, in this case the table is "read only", and the db.SaveChanges () command will always error. A: This is the case for me. Simply removing resulted in another error. I followed the steps of this post except the last one. For your convenience, I copied the 4 steps from the post that I followed to solve the problem as following: * *Right click on the edmx file, select Open with, XML editor *Locate the entity in the edmx:StorageModels element *Remove the DefiningQuery entirely *Rename the store:Schema="dbo" to Schema="dbo" (otherwise, the code will generate an error saying the name is invalid) A: I was getting the same error message, but in my scenario I was trying to update entities derived from a many-to-many relationship using a PJT (Pure Join Table). From reading the other posts, I thought I could fix it by adding an additional PK field to the join table... However, if you add a PK column to a join table, it is no longer a PJT and you lose all of the entity framework advantages like the automatic relationship mapping between the entities. So the solution in my case was to alter the join table on the DB to make a PK that includes BOTH of the foreign ID columns. A: Set Primary Key then save Table and Refresh then go to Model.edmx delete Table and get again . A: Just note that maybe your Entity have primary key but your table in database doesn't have primary key. A: so its true, just add a primary key Note: be sure that when you're updating your EF diagram from the database that you're pointing to the right database, in my case the connection string was pointing to a local DB instead of the up-to-date Dev DB, schoolboy error i know, but I wanted to post this because it can be very frustrating if you're convinced you've added the primary key and you're still getting the same error A: In my case, forgot to define Primary Key to Table. So assign like shown in Picture and Refresh your table from "Update model from Database" from .edmx file. Hope it will help !!! A: UPDATE: I've gotten a few upvotes on this lately, so I figured I'd let people know the advice I give below isn't the best. Since I originally started mucking about with doing Entity Framework on old keyless databases, I've come to realize that the best thing you can do BY FAR is do it by reverse code-first. There are a few good articles out there on how to do this. Just follow them, and then when you want to add a key to it, use data annotations to "fake" the key. For instance, let's say I know my table Orders, while it doesn't have a primary key, is assured to only ever have one order number per customer. Since those are the first two columns on the table, I'd set up the code first classes to look like this: [Key, Column(Order = 0)] public Int32? OrderNumber { get; set; } [Key, Column(Order = 1)] public String Customer { get; set; } By doing this, you're basically faked EF into believing that there's a clustered key composed of OrderNumber and Customer. This will allow you to do inserts, updates, etc on your keyless table. If you're not too familiar with doing reverse Code First, go and find a good tutorial on Entity Framework Code First. Then go find one on Reverse Code First (which is doing Code First with an existing database). Then just come back here and look at my key advice again. :) Original Answer: First: as others have said, the best option is to add a primary key to the table. Full stop. If you can do this, read no further. But if you can't, or just hate yourself, there's a way to do it without the primary key. In my case, I was working with a legacy system (originally flat files on a AS400 ported to Access and then ported to T-SQL). So I had to find a way. This is my solution. The following worked for me using Entity Framework 6.0 (the latest on NuGet as of this writing). * *Right-click on your .edmx file in the Solution Explorer. Choose "Open With..." and then select "XML (Text) Editor". We're going to be hand-editing the auto-generated code here. *Look for a line like this: <EntitySet Name="table_name" EntityType="MyModel.Store.table_name" store:Type="Tables" store:Schema="dbo" store:Name="table_nane"> *Remove store:Name="table_name" from the end. *Change store:Schema="whatever" to Schema="whatever" *Look below that line and find the <DefiningQuery> tag. It will have a big ol' select statement in it. Remove the tag and it's contents. *Now your line should look something like this: <EntitySet Name="table_name" EntityType="MyModel.Store.table_name" store:Type="Tables" Schema="dbo" /> *We have something else to change. Go through your file and find this: <EntityType Name="table_name"> *Nearby you'll probably see some commented text warning you that it didn't have a primary key identified, so the key has been inferred and the definition is a read-only table/view. You can leave it or delete it. I deleted it. *Below is the <Key> tag. This is what Entity Framework is going to use to do insert/update/deletes. SO MAKE SURE YOU DO THIS RIGHT. The property (or properties) in that tag need to indicate a uniquely identifiable row. For instance, let's say I know my table orders, while it doesn't have a primary key, is assured to only ever have one order number per customer. So mine looks like: <EntityType Name="table_name"> <Key> <PropertyRef Name="order_numbers" /> <PropertyRef Name="customer_name" /> </Key> Seriously, don't do this wrong. Let's say that even though there should never be duplicates, somehow two rows get into my system with the same order number and customer name. Whooops! That's what I get for not using a key! So I use Entity Framework to delete one. Because I know the duplicate is the only order put in today, I do this: var duplicateOrder = myModel.orders.First(x => x.order_date == DateTime.Today); myModel.orders.Remove(duplicateOrder); Guess what? I just deleted both the duplicate AND the original! That's because I told Entity Framework that order_number/cutomer_name was my primary key. So when I told it to remove duplicateOrder, what it did in the background was something like: DELETE FROM orders WHERE order_number = (duplicateOrder's order number) AND customer_name = (duplicateOrder's customer name) And with that warning... you should now be good to go! A: I had the same issue. As this thread said, My table didn't have a PK, so I set the PK and ran the code. But unfortunately error came again. What I did next was, deleted the DB connection (delete .edmx file in Model folder of Solution Explorer) and recreated it. Error gone after that. Thanks everyone for sharing your experiences. It save lots of time. A: This is not a new answer but will help somebody who's not sure how to set primary key for their table. Use this in a new query and run. This will set UniqueID column as primary key. USE [YourDatabaseName] GO Alter table [dbo].[YourTableNname] Add Constraint PK_YourTableName_UniqueID Primary Key Clustered (UniqueID); GO A: This can also happen if data model is out of date. Hopefully this will save someone else frustration :) A: It usually happens because one of the following reasons: * *Entity Set is mapped from Database view *A custom Database query *Database table doesn't have a primary key After doing so, you may still need to update in the Entity Framework designer (or alternatively delete the entity and then add it) before you stop getting the error. A: Just Add a primary key to the table. That's it. Problem solved. ALTER TABLE <TABLE_NAME> ADD CONSTRAINT <CONSTRAINT_NAME> PRIMARY KEY(<COLUMN_NAME>) A: I was getting this issue because i was generating my EDMX from an existing database (designed by somebody else, and i use the term 'designed' loosely here). Turns out the table had no keys whatsoever. EF was generating the model with many multiple keys. I had to go add a primary key to the db table in SQL and then updated my model in VS. That fixed it for me. A: Adding the primary key worked for me too ! Once that is done, here's how to update the data model without deleting it - Right click on the edmx Entity designer page and 'Update Model from Database'. A: I had the exact same problem, unfortunately, adding the primary key doesn't solve the issue. So here's how I solve mine: * *Make sure you have a primary key on the table so I alter my table and add a primary key. *Delete the ADO.NET Entity Data Model (edmx file) where I use to map and connect with my database. *Add again a new file of ADO.NET Entity Data Model to connect with my database and for mapping my model properties. *Clean and rebuild the solution. Problem solved. A: just add a primary key to your table and then recreate your EF A: I just had to remove the table from the model and update the model again bringing the table back. I guess the primary key was created after the table was pulled into the model. A: I had this issue come up and believe it was caused because I had deleted the Index on my tables primary key and replaced it with an index on some of the other fields in the table. After I deleted the primary key index and refreshed the edmx, inserts stopped working. I refreshed the table to the older version, refreshed the edmx and everything works again. I should note that when I opened the EDMX to troubleshoot this issue, checking to see if there was a primary key defined, there was. So none of the above suggestions were helping me. But refreshing the index on the primary key seemed to work. A: Open Your .edmx file in XML editor and then remove tag from Tag and also change store:Schema="dbo" to Schema="dbo" and rebuild the solution now error will resolve and you will be able to save the data. A: I found the original answer of updating the .edmx file work best in my situation. I just wasn't too happy about altering the model every time it was updated from the database. That's why I wrote an additional Text Template file, that is automaticaly invoked when after the model has changed - just like the entities are newly generated. I post it here in this comment. To make it work, make sure you name it like {model name}.something.tt, and store it in the same folder as your .edmx folder. I named it {model name}.NonPkTables.tt. It does not generate a file on its own due to the invalid file extension definition in the second line. Feel free to use. <#@ template language="C#" debug="false" hostspecific="true"#> <#@ output extension="/" #> <#@ assembly name="System.Core" #> <#@ assembly name="System.Data" #> <#@ assembly name="System.Windows.Forms" #> <#@ assembly name="System.Xml" #> <#@ assembly name="System.Xml.Linq"#> <#@ assembly name="%VS120COMNTOOLS%..\IDE\EntityFramework.dll" #> <#@ assembly name="%VS120COMNTOOLS%..\IDE\Microsoft.Data.Entity.Design.dll" #> <#@ import namespace="System" #> <#@ import namespace="System.Windows.Forms" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.IO" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Xml" #> <#@ import namespace="System.Xml.Linq" #> <#@ import namespace="System.Globalization" #> <#@ import namespace="System.Reflection" #> <#@ import namespace="System.Data.Entity.Core.Metadata.Edm" #> <#@ import namespace="System.Data.Entity.Core.Mapping" #> <#@ import namespace="System.CodeDom" #> <#@ import namespace="System.CodeDom.Compiler" #> <#@ import namespace="Microsoft.CSharp"#> <#@ import namespace="System.Text"#> <#@ import namespace="System.Diagnostics" #> <# string modelFileName= this.Host.TemplateFile.Split('.')[0] + ".edmx"; string edmxPath = this.Host.ResolvePath( modelFileName ); // MessageBox.Show( this.Host.TemplateFile + " applied." ); var modelDoc = XDocument.Load(edmxPath); var root = modelDoc.Root; XNamespace nsEdmx = @"http://schemas.microsoft.com/ado/2009/11/edmx"; XNamespace ns = @"http://schemas.microsoft.com/ado/2009/11/edm/ssdl"; var runtime = root.Elements(nsEdmx + "Runtime").First(); var storageModels = runtime.Elements(nsEdmx + "StorageModels").First(); XNamespace nsStore = @"http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator"; var schema = storageModels.Elements(ns + "Schema").First(); XNamespace nsCustomAnnotation = @"http://schemas.microsoft.com/ado/2013/11/edm/customannotation"; var entityTypes = schema.Nodes().OfType<XComment>().Where(c => c.Value.Contains("warning 6002: The table/view")); bool changed = false; foreach (var node in entityTypes) { var element = node.ElementsAfterSelf().First(); string entityName = element.Attribute("Name").Value; // Find EntitySet in EntityContainer. var entityContainer = schema.Elements(ns + "EntityContainer").First(); var entitySet = entityContainer.Elements(ns + "EntitySet").First(s => s.Attribute("Name").Value == entityName); // Change "store:Schema" attribute to "Schema" attribute. var attribute = entitySet.Attribute(nsStore + "Schema"); if (attribute != null) { string schemaName = entitySet.Attribute(nsStore + "Schema").Value; entitySet.Attribute(nsStore + "Schema").Remove(); entitySet.Add(new XAttribute("Schema", schemaName)); changed |= true; } // Remove the DefiningQuery element. var definingQuery = entitySet.Element(ns + "DefiningQuery"); if (definingQuery != null) { definingQuery.Remove(); changed |= true; Debug.WriteLine(string.Format("Removed defining query of EntitySet {0}.", entityName)); } } if (changed) modelDoc.Save(edmxPath); #> A: I fixed it by just deleting and rebuilding the EF project and all its classes. See details below: I went round and round on this one for an hour, then deleted the EF project containing the error, saving out all my custom code, then rebuilding the whole thing. Since it was just a matter of generating a new EF diagram and its inner code, this process of fixing the problem took about 10 minutes. The problem, I suspect, is that the database-first method for generating EF classes and properties gets a little weird after two or three "updates". Basically, I found a problem in the code behavior, went and fixed the database table properties, and then updated the EF diagram one time too many. Then I tried fiddling with the code, which didn't work. Starting over worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583770", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "590" }
Q: How can I prevent HTML encoding on a FormView? I am trying to display a property (land) size in the ItemTemplate of a FormView control, and the size value is a string that is sometimes square metres and sometimes hectares, so I can't hardcode a <sup> tag suffix, but I need to display the unit as m<sup>2</sup> when appropriate. How do I prevent the tags being encoded? A: You could use javascript to add/remove the formatting tags when the form-submit event fires.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running a process asynchronously with feedback from ASP.NET via WCF (C#) (Environment .NET 4.0 C# WCF and ASP.NET) So this is the flow I'd like to have happen: * *User visits page. *User uploads file via a control. *User clicks "Commit". *Page tells WCF service to begin "processing" this file (where a lot of behind the scenes work such as decompressing, hashing, moving, and database work happens) *As the file gets processed, the user sees feedback regarding the status of the processing via AJAX, an update panel, and a timer checking the status every N seconds. I added a table in the database called 'UploadProcessing' which persists the status (among other things) of the upload and I wrote the logic to process the upload on the back end which gets called by the WCF service. As the upload is processed, it uploads the 'UploadProcessing' record with the current status of the work until it is finally completed. I first started with just calling the WCFClient.ProcessUpload(args...); from the Commit_Click() event, but that just processed the upload and waited until it was complete before enabling the AJAX update status timer which always showed that it had already completed (because it had). Then I tried calling the same method asynchronously but it appeared to function in the same way because the page wouldn't fully post back to the client (with the enabled timer) until the async complete handler got its response, effectively resulting in the same 'completed' response to the user. So what I'm politely and respectfully asking the community is how would you 'fire and forget' this ProcessUpload() method via WCF so it can do its thing in the background while the page is free to async postback and monitor its status? Perhaps some sort of ThreadPool solution on the WCF side? Or maybe a slave service that monitors the 'UploadProcessing' table for pending uploads and then handles them that way? Thank you in advance for any advice! A: Suggest making your WCF method a OneWay operation, e.g. [OperationContract(IsOneWay = true)] public void ProcessUpload(...) { //etc } A: It sounds like you're going about it the right way, perhaps your Async setup of the WCF Service just wasn't quite right? The answer to this question has some helpful links, and here's an MSDN page on Calling WCF Service Operations Asynchronously. Update: It looks like this blog post covers your problem almost exactly, looks like a good resource for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Websocket server for Python3 outside HTTP server I am searching for a websocket server implementation for Python3. There are some projects on the web, but they all run in HTTP-context. I need a server that is started on command line, not by an HTTP-server (No HTTP-Handler object available) Ideally, the code should not require any bigger third party-project (like twisted, tornado ...) Any ideas? Concrete description of my use case: My network contains several python servers (not web servers). Every of these Python servers logs runtime information to a logger. Now, I want be able to listen to those logs from within a browser... and websocket seems the most interesting solution to me... A: My websockify project support python3. The websocket.py module that websockify is built on implements a generic python WebSocket server. It currently requires the numpy module if you want to use the new versions (HyBi-07+) of the protocol (I will probably implement a slower generic fallback in the next couple of days). You also might be able to use 2to3 with pywebsocket to get it running in python 3. pywebsocket is really the reference implementation of WebSockets that both Chrome and Mozilla test against.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: easy way to save the state of Silverlight Is there an easy way to save the state of a Silverlight application and retrieve it at the next reboot? I know Silverlight can save and read data locally on the client, but what I seek is a method which behave similarly to what the Eclipse IDE do respect the perspectives and views selected by the user. I'd like if Silverlight can remember in the next reboot the last page seen by user and the state of the widgets. A: There is no built-in way to do that. You have to manually code all the state and save it on a client yourself. A: As you mention "the last page seen by [the] user" you really need to look at using a navigation framework instead of "remebering" the last used page. That way your app becomes deep-linkable via standard bookmarks. Note: If you were writing a WP7 app I would say the opposite, but you seem to be asing about an SL web app. A: If you store your current details about the application in one object like a singleton you could serialize this and save it in a database. Next time the application is launch you download it and de- serialize the object it will give you the way the application was. However this means that you need to be using this singleton though out the application or a process of going through the object to set the application up again. So i guess it isnt easy really.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what does ?body=1 do in rails 3.1 asset pipeline? In development, all my javascript assets are being appended with the body=1 get variable. What is this actually doing? http://localhost:3000/assets/application.js?body=1 A: Trawling through the Sprocket source code we find: # Returns a 200 OK response tuple def ok_response(asset, env) if body_only?(env) [ 200, headers(env, asset, Rack::Utils.bytesize(asset.body)), [asset.body] ] else [ 200, headers(env, asset, asset.length), asset ] end end body_only? is set when ?body=1 or true For a static asset, Asset.body is defined as: def body # File is read everytime to avoid memory bloat of large binary files pathname.open('rb') { |f| f.read } end Whereas passing the asset back its self is a "Rack-capable body object" # Add enumerator to allow `Asset` instances to be used as Rack # compatible body objects. def each yield to_s end When we look at the bundled_asset, the Asset.body is redefined as retrieving the body of the asset only and not including any dependencies. Asset.to_a is defined as retrieving the asset its self as well as all of its dependencies as an array passed on to Rack. In this way, assets aren't combined together but taken as individual objects, so individual CSS files are still individual.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: How can I move my broken Plone content to a new contenttype? The "old" content type is: collective.fhdirectory The "new" content type is: collective.teamdirectory All the "old" content on my website is now broken… A: There is a products that specifically do this job: Products.contentmigration. Here a good howto on how to Migrate Custom AT Types with Products.contentmigration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: View Autocad Drawings inside Delphi application Is there a way ( ole or component ) to view Atocad 2004-2011 drawings inside Delphi application ? A: I don't know for sure, but if you have AutoCad installed on your PC, try importing the ActiveX. It's in the Delphi IDE under Component | Import Component... | Import ActiveX Control. That'll show the list of available ActiveX gizmos. See if there's anything there that looks like AutoCad. If so, you should be able to make it work ON YOUR PC. To make it work on ANY PC, you'd need a free or licensed viewer that can handle AutoCad. A: CadSoftTools offer CAD Image DLL or CAD Import VCL A: The Open Design Alliance supports (or used to support, I'm not sure about that one) Delphi in their TeighaX library. In the past you have been able to use DWG Trueview as an ActiveX control but that may have been disabled.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use DataTrigger from code in Silverlight? I have found a few examples that relate to WPF, but none for Silverlight. So, what is a working example of setting up a Microsoft.Expression.Interactivity.Core.DataTrigger in code? Here is the code I currently have, though it doesn't work (no exceptions, but nothing happens at runtime): // Set up a storyboard var duration = new Duration(TimeSpan.FromMilliseconds(400)); var animation = new ColorAnimation { To = Colors.White, RepeatBehavior = RepeatBehavior.Forever, AutoReverse = true, Duration = duration }; var sb = new Storyboard { RepeatBehavior = RepeatBehavior.Forever, AutoReverse = true, Duration = duration }; sb.Children.Add(animation); Storyboard.SetTarget(animation, fillBrush); Storyboard.SetTargetProperty(animation, new PropertyPath("(SolidColorBrush.Color)")); // Configure the data trigger var focusTrigger = new DataTrigger { Binding = new Binding("IsFocussed") { Source = asset, Mode = BindingMode.OneWay }, Value = true }; focusTrigger.Actions.Add(new ControlStoryboardAction { Storyboard = sb, ControlStoryboardOption = ControlStoryboardOption.Play, IsEnabled = true }); asset.IsFocussed changes and raises change notifications via INotifyPropertyChanged. A: Try using the namespace: System.Windows.Interactivity and add the following after your "Configure the data trigger" comment // Configure the data trigger // Configure the TriggerCollection TriggerCollection triggers = Interaction.GetTriggers(fillBrush); var focussedTrigger = new EventTrigger("GotFocus"); focussedTrigger.Actions.Add( new ControlStoryboardAction{Storyboard = sbFocussed}); var unfocussedTrigger = new EventTrigger("LostFocus"); unfocussedTrigger.Actions.Add( new ControlStoryboardAction { Storyboard = sbUnfocussed }); triggers.Add(focussedTrigger); triggers.Add(unfocussedTrigger); note: using EventTrigger = System.Windows.Interactivity.EventTrigger; using TriggerCollection = System.Windows.Interactivity.TriggerCollection; A: In the end I was missing two bits: * *Add the trigger to the brush: var triggers = Interaction.GetTriggers(fillBrush); triggers.Add(focusTrigger); *Set the binding on the trigger using BindingOperators.SetBinding, not the Binding property setter: var binding = new Binding("IsFocussed") { Source = asset, Mode = BindingMode.OneWay }; BindingOperations.SetBinding(focusTrigger, PropertyChangedTrigger.BindingProperty, binding); I can't quite see why the second point was necessary, but it seemed to be. Hope that helps someone else out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to programately record HDMI video? I am looking for a device that can be used, via an API, to record HDMI video. I found several devices on the web but I am looking for one that does have an API that I could call and schedule recordings, that could be analysed lately. Please specify if you were successful doing thing. A: If you want to capture in software, you need HDMI capture card with SDK and/or a driver to one of the well-known capture APIs, such as DirectShow in MS Windows. Something like this: Blackmagic Design Intensity or XtremeRGB-Ex4+ (PCIe).
{ "language": "en", "url": "https://stackoverflow.com/questions/7583790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# WinForms Drawing without viewing A friend of nine gave me an idea for buffering: to view the drawing after the drawing process is completed. He told me to draw on a graphic (a panel in this case) which is invisible for the user. But when the drawing process is complete, the drawing gets applied on the panel. With other words it's like drawing a picture without showing it to anyone until it's finished. I tried it. But I'm doin' it wrong. First I draw on a Panel that is only declared (there are no lines in the code that change it's properties). After that I'm trying to apply the new drawing on a visible panel using "gfx = RealPanel.CreateGraphics();" But this only makes a new graphics on the panel... Yep, I'm doin' it wrong. I have no idea how to do it right. In my case there is a panel that in one moment gets filled with lines and squares. The panel is also belong to another panel. The firs panel cannot de resized along with the whole window, but the second panel can. When panel number 2 is being resized and it's smaller than panel number 1, the flickering begins. The second panel's auto scroll property is set to "true", and when I'm scrolling there is flickering too. Please don't try telling me to use double buffering. I tried with "unlocking" the double buffering property of the panel. And I tried all the methods explained here: Winforms Double Buffering ... Doesn't make things any different for me. And I want to try this idea. So, how can I do it right? Thanks! A: You should never have to use CreateGraphics. A double-buffered panel should fix this. Don't use it on your "hidden" panel. You should probably get rid of the hidden panel and just use your new panel control. If you still have flickering issues, then you should edit your question and post the code that causes the filckering. public class PanelEx : Panel { public PanelEx() { this.DoubleBuffered = true; } } If you still want to do your own "hidden" double-buffering, then you do it straight on your own bitmap: Bitmap bm = new Bitmap(width, height); Then do your drawing like this: using (Graphics g = Graphics.FromImage(bm)) { //Draw stuff } In your Panels paint event, all you do is: private void panel1_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawImage(bm, 0, 0); } Whenver you need to update the screen, just invalidate the panel: panel1.Invalidate(); which will tell your program to call the paint event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Quartz.NET trigger a misfire if the Windows service was stopped? I'm using the Quartz.NET dll with AdoJobStore inside a Windows service. I noticed that the tutorial isn't very clear about misfires. The question: Is a misfire supposed to be triggered if the Windows service was stopped when the job should have been executed? The Quartz.NET tutorial says: "A misfire occurs if a persistent trigger "misses" its firing time because of the scheduler being shutdown, or because there are no available threads in Quartz's thread pool for executing the job". So does that mean that if the service itself is stopped no misfire is triggered (because that's what happens to me)? A: That's correct. The misfire will happen whenever the scheduler is started up again. In essence the misfire happens when the scheduler checks when a job should run and it determines that the fire time for the job is in the past.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: send_mass_emails with EmailMultiAlternatives I try to build a newsletter application and want to send 50 emails with one connection. send_mass_mail() looks perfect but I can't figure out how I call this in combination with EmailMultiAlternatives. This is my code that sends only one email with one connection: html_content = render_to_string('newsletter.html', {'newsletter': n,}) text_content = "..." msg = EmailMultiAlternatives("subject", text_content, "from@bla", ["to@bla"]) msg.attach_alternative(html_content, "text/html") msg.send() a working example with the code above and send_mass_mail would be great, thanks! A: That is send_mass_mail() rewritten to use EmailMultiAlternatives: from django.core.mail import get_connection, EmailMultiAlternatives def send_mass_html_mail(datatuple, fail_silently=False, user=None, password=None, connection=None): """ Given a datatuple of (subject, text_content, html_content, from_email, recipient_list), sends each message to each recipient list. Returns the number of emails sent. If from_email is None, the DEFAULT_FROM_EMAIL setting is used. If auth_user and auth_password are set, they're used to log in. If auth_user is None, the EMAIL_HOST_USER setting is used. If auth_password is None, the EMAIL_HOST_PASSWORD setting is used. """ connection = connection or get_connection( username=user, password=password, fail_silently=fail_silently) messages = [] for subject, text, html, from_email, recipient in datatuple: message = EmailMultiAlternatives(subject, text, from_email, recipient) message.attach_alternative(html, 'text/html') messages.append(message) return connection.send_messages(messages) A: It's not possible to directly use send_mass_mail() with EmailMultiAlternatives. However, according to the Django documentation, send_mass_mail() is simply a wrapper that makes use of the EmailMessage class. EmailMultiAlternatives is a subclass of EmailMessage. EmailMessage has a 'connection' parameter allowing you to specify a single connection to use when sending the message to all recipients - i.e. the same functionality as provided by send_mass_mail(). You can use the get_connection() function to obtain an SMTP connection as defined by the SMTP settings in settings.py. I believe that the following (untested) code should work: from django.core.mail import get_connection, EmailMultiAlternatives connection = get_connection() # uses SMTP server specified in settings.py connection.open() # If you don't open the connection manually, Django will automatically open, then tear down the connection in msg.send() html_content = render_to_string('newsletter.html', {'newsletter': n,}) text_content = "..." msg = EmailMultiAlternatives("subject", text_content, "from@bla", ["to@bla", "to2@bla", "to3@bla"], connection=connection) msg.attach_alternative(html_content, "text/html") msg.send() connection.close() # Cleanup A: I followed a mixed approach, sending to users both plain text and html messages and personalizing messages for every user. I started from the section Sending multiple emails od Django documentation. from django.conf import settings from django.contrib.auth.models import User from django.core import mail from django.core.mail.message import EmailMultiAlternatives from django.template.loader import get_template from django.template import Context ... connection = mail.get_connection() connection.open() messages = list() for u in users: c = Context({ 'first_name': u.first_name, 'reseller': self,}) subject, from_email, to = 'new reseller', settings.SERVER_EMAIL, u.email text_content = plaintext.render(c) html_content = htmly.render(c) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") messages.append(msg) connection.send_messages(messages) connection.close() A: This is how I do the task (tested code): from html2text import html2text from django.utils.translation import ugettext as _ from django.core.mail import EmailMultiAlternatives, get_connection def create_message(subject, message_plain, message_html, email_from, email_to, custom_headers=None, attachments=None): """Build a multipart message containing a multipart alternative for text (plain, HTML) plus all the attached files. """ if not message_plain and not message_html: raise ValueError(_('Either message_plain or message_html should be not None')) if not message_plain: message_plain = html2text(message_html) return {'subject': subject, 'body': message_plain, 'from_email': email_from, 'to': email_to, 'attachments': attachments or (), 'headers': custom_headers or {}} def send_mass_html_mail(datatuple): """send mass EmailMultiAlternatives emails see: http://stackoverflow.com/questions/7583801/send-mass-emails-with-emailmultialternatives datatuple = ((subject, msg_plain, msg_html, email_from, email_to, custom_headers, attachments),) """ connection = get_connection() messages = [] for subject, message_plain, message_html, email_from, email_to, custom_headers, attachments in datatuple: msg = EmailMultiAlternatives( **create_message(subject, message_plain, message_html, email_from, email_to, custom_headers, attachments)) if message_html: msg.attach_alternative(message_html, 'text/html') messages.append(msg) return connection.send_messages(messages) A: Here's a succinct version: from django.core.mail import get_connection, EmailMultiAlternatives def send_mass_html_mail(subject, message, html_message, from_email, recipient_list): emails = [] for recipient in recipient_list: email = EmailMultiAlternatives(subject, message, from_email, [recipient]) email.attach_alternative(html_message, 'text/html') emails.append(email) return get_connection().send_messages(emails) A: When you are sending multiple/mass/bulk emails, establishing and closing SMPT/any connection is an expensive process, you have to reuse the connection instead of creating and destroying the connection for every recipient. You have to create a single connection and send all the emails at once. from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from django.core import mail def send_bulk_email(emails_list, subject, context, template, from_email): html_content = render_to_string(template, context) text_content = strip_tags(html_content) emails = [] for recipient in emails_list: email = EmailMultiAlternatives(subject, text_content, from_email, [recipient]) email.attach_alternative(html_content, "text/html") emails.append(email) connection = mail.get_connection() return connection.send_messages(emails)
{ "language": "en", "url": "https://stackoverflow.com/questions/7583801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Using a stored procedure inside of a stored procedure I have a stored procedure that queries some results. I have another stored procedure that needs to return the results of the first stored procedure and the results of a query to a table. Currently, the body of this stored procedure looks something like this: EXEC myFirstStoredProc @param1 SELECT * FROM MyTable When I execute mySecondStoredProc, the results of MyTable appear. However, the results of the EXEC statement do not appear. How do I get the results of the nested sproc call to appear? Thank you! A: Assuming this is SQL Server what you've described should work. Here's a sample that you can use to see it in action CREATE PROC testProc AS BEGIN exec sp_helpdb SELECT * FROM sys.tables END
{ "language": "en", "url": "https://stackoverflow.com/questions/7583806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: User input of program feature request in TFS2010 Is there any way that users can enter feature requests, so that they will appear in TFS2010? We would like to keep an overview of all incoming requests and only create our own User Stories after verifying these requests. A: At first, if I read this correctly, you 'd like to generate a new Work Item type named "Feature" or similar. A very nice post on that can be found here. Then you would like customers to remotely access your TFS, so they can generate/view your "Features". See Work Item Only Group for that. Another presentation on how to set this up, is to be found here, where in the comments OP writes: The great thing we find at my work, is that you can create a linked worked item from a client submitted bug, and they cannot see the work item and the internal chatter inside the work item. This works out great This is a very nice bonus. A: Work Item Read Only view is the perfect tool for you. It is just TFS Web Access, but the users are placed in the Work Item Only security group: http://msdn.microsoft.com/en-us/library/cc668124.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7583809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: InkCanvas slows down when we have multiple strokes I am using InkCanvas for creating paint like application. When i use to draw multiple strokes on canvas it works very slow. I have machine with very good configuration as : Intel(R) Core(TM) 2 Quad CPU Q6600 @ 2.40GHz (4CPUs),~2.4GHz and 2GB RAM. When i have more that 10000 thousands strokes memory usage goes up to 500 MB and while drawing and erasing CPU uses cross 30 . Normal samples also gives the same result.Re-sizing of window is also very slow. I chose InkCanvas because i need to create vector based drawing application and WPF have provided it. What is the reason behind this ? Should i go with InkCanvas for paint like application? If yes then how should I tackle this problem? A: You have to create your own canvas for the job, not inkcanvas. It is designed for light usage.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jsf2 Richfaces render Question I am using richfaces4 and i have a question about rerendering components. When i rerender my "link_panel" every row of the datatable will rerender its "link_panel". How can i change this behavior? I would like to rerender just tze current output panel and not for the complete datatable. greetings, m <rich:column rendered="#{userBean.renderLinkLinks}"> <f:facet name="header"> Verlinkt </f:facet> <center> <a4j:outputPanel id="link_panel"> <a4j:outputPanel rendered="#{!linkBean.isLinkedWithLerneinheit(lerneinheit)}"> <h:outputLink > <h:outputText value="Link"/> <a4j:ajax event="click" listener="#{linkBean.linkSelectionWithLerneinheit(lerneinheit)}" render="link_panel"/> </h:outputLink> </a4j:outputPanel> <a4j:outputPanel id="unlink_panel" rendered="#{link <rich:column rendered="#{userBean.renderLinkLinks}"> <f:facet name="header"> Verlinkt </f:facet> <center> <a4j:outputPanel id="link_panel"> <a4j:outputPanel rendered="#{!linkBean.isLinkedWithLerneinheit(lerneinheit)}"> <h:outputLink > <h:outputText value="Link"/> <a4j:ajax event="click" listener="#{linkBean.linkSelectionWithLerneinheit(lerneinheit)}" render="link_panel"/> </h:outputLink> </a4j:outputPanel> <a4j:outputPanel id="unlink_panel" rendered="#{linkBean.isLinkedWithLerneinheit(lerneinheit)}" > <h:outputLink > <h:outputText value="Unlink"/> <a4j:ajax event="click" listener="#{linkBean.unlinkSelectionFromLerneinheit(lerneinheit)}" render="link_panel"/> </h:outputLink> </a4j:outputPanel> </a4j:outputPanel> </center> </rich:column> A: If you only want to render one link_panel, then you have to have unique id's for the elements.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to increase packet size for reading webresponse I am reading response from a web url (in our own network), using httpWebResponse. While reading the response using StreamReader ReadToEnd(), It fetching data in packets and each packet having size of approx 500 bytes. How can I increase this packet size to approx 512 KB? A: The packet size isn't (primarily) up to the fetching code - it's up to the server what size of packet it sends out, and those packets may be further split up by the rest of the network. You simply can't have a TCP/IP packet of 512K... and you shouldn't care. This is just how TCP/IP works; it's not like it's making several HTTP requests for the data, it's just using the normal TCP/IP channel. Have a look at fetching the same data from a browser - you'll see it split into packets in the same way. EDIT: I see from your comments that it's taking 4 seconds to get the data. Yes, that's quite a long time - but that may well just be how long it takes to fetch/create and transport the data. You haven't really given much context here (what's a "webuser"?) but I think you're trying to optimize in the wrong place.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Installing wxPython from source under linux I am trying to install wxPython from source under linux. The steps I followed were: * *Download wxPython from http://downloads.sourceforge.net/wxpython/wxPython-src-2.8.12.1.tar.bz2 *Run ./configure --prefix=$HOME/Local At the end of the configure process the output was: Configured wxWidgets 2.8.12 for `x86_64-unknown-linux-gnu' Which GUI toolkit should wxWidgets use? GTK+ 2 Should wxWidgets be compiled into single library? no Should wxWidgets be compiled in debug mode? no Should wxWidgets be linked as a shared library? yes Should wxWidgets be compiled in Unicode mode? no What level of wxWidgets compatibility should be enabled? wxWidgets 2.4 no wxWidgets 2.6 yes Which libraries should wxWidgets use? jpeg sys png sys regex sys tiff builtin zlib sys odbc no expat builtin libmspack no sdl no *make wxPython, which appears to run without errors. *make install But when I now try to do import wx in the python console (v2.7), python does not find the module. So my questions are: * *Am I missing some dependencies although wxPython seems to build and install without any errors? *Did I miss anything during the installation process? *How do I make python aware of the new package? Any hint, link, article is appreciated. A: For wxPython 2.8.x, there are complete build from source instructions here: http://wxpython.org/BUILD-2.8.html If you'd rather go for 2.9, then you can use the following instructions instead: http://wxpython.org/builddoc.php If you run into issues, join the wxPython-users mailing list / Google Group here: http://wxpython.org/maillist.php Tell them which versions of wxPython and Python you're using along with which Linux and you'll almost certainly get help. There are a lot of Linux guys on there. A: I am installing WxPython 3.0 on centos machine with python 2.7. even with disable-mediactrl the install searches for GSTreamer and gives the error "configure: error: GStreamer not available" despite the fact that GSTreamer is available on the machine. Here are the details for two such builds: My idea was to turn OFF mediactrl, so I am using following option python build-wxpython.py --extra_setup=disable-mediactrl --build_dir=../bld or python build-wxpython.py --extra_setup="--disable-mediactrl --build_dir=../bld However, it still searches for GSTreamer and outputs the error message listed below. I reinstalled GSTreamer 0.10 and into \usr\lib\GSTreamer 0.10, however, I receive the same error message error message : checking what is the type of the third argument of getsockname... socklen_t checking what is the type of the fifth argument of getsockopt... socklen_t checking for linux/joystick.h... yes checking for python... /home/aptRoot/tools/python/64/Python-2.7/bin/python checking for WEBKIT... configure: WARNING: webkitgtk not found. configure: WARNING: WebKit not available, disabling wxWebView checking for CAIRO... yes checking for cairo_push_group... yes checking for GST... configure: WARNING: GStreamer 0.10 not available, falling back to 0.8 checking for GST... configure: WARNING: GStreamer 0.8/0.10 not available. configure: error: GStreamer not available Error running configure ERROR: failed building wxWidgets Traceback (most recent call last): File "build-wxpython.py", line 378, in <module> wxbuild.main(wxscript, build_options) File "/home/hemadris/iAPT/install/wxPython-src-3.0.0.0/build/tools/build-wxwidgets.py", line 364, in main "Error running configure") File "/home/hemadris/iAPT/install/wxPython-src-3.0.0.0/build/tools/build-wxwidgets.py", line 80, in exitIfError raise builder.BuildError(msg) BuildError
{ "language": "en", "url": "https://stackoverflow.com/questions/7583813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Check last Database backup date in C# - SQL Server 2008 I have a C# windows Forms application and when the start-up Form loads, i want to check the last time a backup was performed on the database the application connects to. A: you could create a store procedure that does the work for you. then you can execute it within the form's OnLoad event or where ever it fits for your need. Have a look at the below for getting the T-SQL that does the trick http://www.mssqltips.com/sqlservertip/1601/script-to-retrieve-sql-server-database-backup-history-and-no-backups/ A: These are taken from my automation of backups: First get a list of all databases, including their database GUID: select db.name, db.database_id, rec.database_guid from sys.databases db inner join sys.database_recovery_status rec on db.database_id = rec.database_id where db.source_database_id is null and db.name <> 'tempdb' The condition on source_database_id excludes snapshots. Then using the GUID from the above, get the date of the last full backup type='D' that isn't COPY_ONLY: SELECT MAX(backup_finish_date) as backup_finish_date from msdb..backupset where type='D' and database_guid = @DbGuid and is_copy_only=0
{ "language": "en", "url": "https://stackoverflow.com/questions/7583817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simplify a piece of php code, too many repetitions Cant really figure out how to simplify this. What i want is to get contents of these few pages and display them on my site. Is the right way just to repeat the file_get_contents for every page i want or can i do this in another way (maybe all the web sites in one file_get_contents function ?). Also, the rest of the code just repeats its self. I this the whole code just slows down my web site a lot. If somebody is willing to lend a hand :) in this, thank you so much. <?php //Obtain Quote Info - This collects the Microsoft Stock Info $quote10 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=NYSE:GLD'); $quote9 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXEURO:PX1'); $quote8 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXDJSTOXX:SX5E'); $quote7 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXFTSE:UKX'); $quote4 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXNIKKEI:NI225'); $quote5 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=SHA:000001'); $quote4 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXDJX:.DJI'); $quote3 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXNASDAQ:.IXIC'); $quote2 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=INDEXSP:.INX'); $quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG'); $quote1 = file_get_contents('http://finance.google.com/finance/info?client=ig&q=NASDAQ:YHOO'); //Remove CR's from ouput - make it one line $json = str_replace("\n", "", $quote); $json1 = str_replace("\n", "", $quote1); $json2 = str_replace("\n", "", $quote2); $json3 = str_replace("\n", "", $quote3); $json4 = str_replace("\n", "", $quote4); $json5 = str_replace("\n", "", $quote5); $json6 = str_replace("\n", "", $quote6); $json7 = str_replace("\n", "", $quote7); $json8 = str_replace("\n", "", $quote8); $json9 = str_replace("\n", "", $quote9); $json10 = str_replace("\n", "", $quote10); //echo $json['45']; //Remove //, [ and ] to build qualified string $data = substr($json, 4, strlen($json) -5); $data1 = substr($json1, 4, strlen($json1) -5); $data2 = substr($json2, 4, strlen($json2) -5); $data3 = substr($json3, 4, strlen($json3) -5); $data4 = substr($json4, 4, strlen($json4) -5); $data5 = substr($json5, 4, strlen($json5) -5); $data6 = substr($json6, 4, strlen($json6) -5); $data7 = substr($json7, 4, strlen($json7) -5); $data8 = substr($json8, 4, strlen($json8) -5); $data9 = substr($json9, 4, strlen($json9) -5); $data10 = substr($json10, 4, strlen($json10) -5); //decode JSON data $json_output = json_decode($data, true); $json_output1 = json_decode($data1, true); $json_output2 = json_decode($data2, true); $json_output3 = json_decode($data3, true); $json_output4 = json_decode($data4, true); $json_output5 = json_decode($data5, true); $json_output6 = json_decode($data6, true); $json_output7 = json_decode($data7, true); $json_output8 = json_decode($data8, true); $json_output9 = json_decode($data9, true); $json_output10 = json_decode($data10, true); //Un-remark print_r to see all array keys //print_r($json_output); //Output Stock price array key. echo "\n".$json_output['t'],"\n".$json_output['l'],"\n".$json_output['cp'];echo "<br />"; echo "\n".$json_output1['t'],"\n".$json_output1['l'],"\n".$json_output1['cp'];echo "<br />"; echo "\n".$json_output2['t'],"\n".$json_output2['l'],"\n".$json_output2['cp'];echo "<br />"; echo "\n".$json_output3['t'],"\n".$json_output3['l'],"\n".$json_output3['cp'];echo "<br />"; echo "\n".$json_output4['t'],"\n".$json_output4['l'],"\n".$json_output4['cp'];echo "<br />"; echo "\n".$json_output5['t'],"\n".$json_output5['l'],"\n".$json_output5['cp'];echo "<br />"; echo "\n".$json_output6['t'],"\n".$json_output6['l'],"\n".$json_output6['cp'];echo "<br />"; echo "\n".$json_output7['t'],"\n".$json_output7['l'],"\n".$json_output7['cp'];echo "<br />"; echo "\n".$json_output8['t'],"\n".$json_output8['l'],"\n".$json_output8['cp'];echo "<br />"; echo "\n".$json_output9['t'],"\n".$json_output9['l'],"\n".$json_output9['cp'];echo "<br />"; echo "\n".$json_output10['t'],"\n".$json_output10['l'],"\n".$json_output10['cp']; A: Just use an array and a for each loop. $stock_array = array('NYSE:GLD', 'INDEXEURO:PX1', 'INDEXDJSTOXX:SX5E', etc..); foreach ($stock_array as $stock) { $quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q='.$stock); $json = str_replace("\n", "", $quote); $data = substr($json, 4, strlen($json) -5); $json_output = json_decode($data, true); echo "\n".$json_output['t'],"\n".$json_output['l'],"\n".$json_output['cp'];echo "<br />"; } Hope this helps, Phil A: A few thoughts: 1) IF the main problem is it slowing down your site, cache the value using Memcached or similar, so you don't have to fire 5000 requests/sec for information that doesn't change. 2) Could you have each user's browser load this asynchronously with javascript so each block loads as it becomes available and therefore allows the navigation, etc. to load immediately? 3) If you really need to do some data massaging of this data coming back from google's api, you could have a separate php page that's like a handle_google_data.php file that your users' browser hits asynchronously with javascript. 4) You might throw some microtime(true) statements throughout your code to see what's taking the longest (I'm fairly positive it will be the api calls). Good luck! -Z. A: Try this one and modify the $json_var to get the output that you need. $file_arr is containing the file paths that you need to call. $output_var = ''; function my_function($file_path) { $quote = file_get_contents($file_path); $json = str_replace("\n", "", $quote); $data = substr($json, 4, strlen($json) -5); $json_output = json_decode($data, true); $json_var = "\n".$json_output['t'].",\n".$json_output['l'].",\n".$json_output['cp'].'<br />'; return $json_var; } $file_arr = array('0'=>'http://finance.google.com/finance/info?client=ig&q=NYSE:GLD','1'=>'http://finance.google.com/finance/info?client=ig&q=INDEXEURO:PX1'); foreach($file_arr as $k=>$v): $output_var .= my_function($v); endforeach; echo $output_var; A: You can put your links in an array like this then run a foreach through them. $quotelinks = array( 'http://finance.google.com/finance/info?client=ig&q=NASDAQ:GOOG', 'http://finance.google.com/finance/info?client=ig&q=NASDAQ:YHOO', 'http://finance.google.com/finance/info?client=ig&q=INDEXSP:.INX', 'http://finance.google.com/finance/info?client=ig&q=INDEXNASDAQ:.IXIC', 'http://finance.google.com/finance/info?client=ig&q=INDEXDJX:.DJI', 'http://finance.google.com/finance/info?client=ig&q=SHA:000001', 'http://finance.google.com/finance/info?client=ig&q=INDEXNIKKEI:NI225', 'http://finance.google.com/finance/info?client=ig&q=INDEXFTSE:UKX', 'http://finance.google.com/finance/info?client=ig&q=INDEXDJSTOXX:SX5E', 'http://finance.google.com/finance/info?client=ig&q=INDEXEURO:PX1', 'http://finance.google.com/finance/info?client=ig&q=NYSE:GLD'); foreach ($quotelinks as $quotelink) { $quote = file_get_contents($quotelink); $json = str_replace("\n", "", $quote); $data = substr($json, 4, strlen($json) -5); $json_output = json_decode($data, true); echo "\n".$json_output['t'],"\n".$json_output['l'],"\n".$json_output['cp'];echo "<br />"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7583819", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to convert a .eps file to a high quality 1024x1024 .jpg? I have a .eps file that I can look at in Photoshop, and it has a very high resolution, sharp edges, etc. at even larger than 1024x1024. With ImageMagick I want to convert this .eps to a 1024x1024 .jpg with very high resolution. However, with the following command, the image is very blurry: convert -resize "1024x1024" -colorspace RGB -flatten test.eps test.jpg What ImageMagick parameters do I have to use so that the resulting .jpg is 1024x1024 and a high quality, sharp image? here's some XMP data we found, perhaps what is causing it to not be resized with -size: A: For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other. Try something like convert -density 300 image.eps -resize 1024x1024 image.jpg Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command. The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at. This is not super obvious in the manpage for convert, but is hinted at: SYNOPSIS convert [input-option] input-file [output-option] output-file A: Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583821", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: Using POST requests to Solr from SolrNet Is it possible to send data to Solr using POST instead of GET? I use SolrNet and a Windsor container. A: Yes, it's possible. You have to write a decorator around ISolrConnection that POSTs instead of GETs. Installing the decorator is very easy in Windsor: var container = new WindsorContainer(); container.Register(Component.For<ISolrConnection>() .ImplementedBy<PostSolrConnection>() .Parameters(Parameter.ForKey("serverUrl").Eq(serverURL))); container.AddFacility("solr", new SolrNetFacility(serverURL)); I blogged exactly about this some time ago (decorator code included) UPDATE: PostSolrConnection is now part of the SolrNet library as SolrNet.Impl.PostSolrConnection
{ "language": "en", "url": "https://stackoverflow.com/questions/7583824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: videoinput with C# I have a video capture (usb-webcam) application that currently uses very old VFW with p-Invoke hookup to C#. I'm trying to replace it and I stumbled on the VideoInput library, and later found VideoInputSharp. I managed to get VideoInputSharp into my application and it gives me the frame rate and camera control I need. The problem is that on some PCs the call to VideoInput.IsFrameNew() never returns true even though the device is set up (VideoInput.IsDeviceSetup() does return true). I've successfully run this on a W7x64 system and a XPx32 system, but does not work on W7x32. Any thoughts on why this is happening? UPDATE1: Since originally posting this question, I've found that on the systems that don't work, I am still able to call VI.ShowSettingsWindow() to generate a dialog box; however, it is a different dialog box than I see on the systems that work (even though it is the same camera/driver). Is this a clue? Also note that I'm running the same version of DirectX on the machine it works with and the machine it doesn't work with. UPDATE2: The systems that this is failing on are W7x32 and W7x64 both using a Microsoft LifeCam. I found yesterday that if I remove the Microsoft LifeCam software from the machine it then works! I sure could use an explanation for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VS Windows Form App, Controlling Hover State (not Blue) some of my button states in my Windows Form Application are defaulting to a blue Hover state. I am pretty new to VS and I am mainly using the GUI to modify the design, but I don't see anywhere where I can control just the color of the hover state of the buttons. Can anybody tell me where I control this, whether it be programatically or in the GUI? A: The windows operating system handles that. To modify it, you would have to change the FlatStyle appearance to Flat and then modify the FlatAppearance attributes, which includes the MouseOverBackColor property. Unfortunately, you lose the visual styles then.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing parameter from one class to another Problem: I have a function that gets passed data and a size. But I want another function dedicated to "getting the size" so i can call it and find out what it is. Is there any way to point to what is passed into my function (the one passed data and size) and bring the size to my GetSize function so it can return size?? CommonClass::Do something(void* data, unsigned long size) // Is what I have I want to use the same unsigned long size used when do something was called for my GetSize function CommonClass::GetSize( Thanks all! A: Make a class variable that contains size, something like: In class.cc int getSize() { return size_; } void func(int data, int size) { size_ = size; } In header.h int size_;
{ "language": "en", "url": "https://stackoverflow.com/questions/7583832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JmDNS 3.4.1, does it support IPv6? Does JmDNS 3.4.1 support IPv6? when I register a service with an IPv4 I can see it on other machines, but if I use an interface with an IPv6 address, I don't :( Also, I get No support for IPv6 in jSLP yet (see https://bugs.eclipse.org/328074), skipping interface... does JmDNS use SLP?
{ "language": "en", "url": "https://stackoverflow.com/questions/7583838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error Reading string into array I'm in the process of creating a tile based game. This game requires a method to load a text file and write the numbers between the delimiter "-", to a multidimensional array. However, an error message "object not set to an instance occurs. 'Load map Public Sub LoadMap(ByVal URI As String) Using reader As New System.IO.StreamReader(URI) For x As Integer = 0 To 13 Dim line = reader.ReadLine() Dim tokens() As String = line.Split("-") 'adds values to multidimensional array For y As Integer = 0 To 16 Me.map(x, y) = Integer.Parse(tokens(y)) Next y Next x End Using End Sub Example map - numbers represent image id's 2-2-2-0-0-0-0-0-0-0-0-3-3-5-5-5-5 2-2-2-0-0-0-0-0-0-0-0-3-3-5-5-5-5 2-2-2-0-0-0-0-0-0-0-0-3-3-2-2-2-5 2-2-2-0-0-0-0-0-0-0-0-3-3-2-2-2-5 2-2-2-0-0-0-0-0-0-0-0-3-3-2-2-2-5 0-0-0-0-0-0-0-0-0-0-0-3-3-2-2-2-5 3-3-3-3-3-3-3-3-3-3-3-3-3-3-3-3-3 4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2 4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2 4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2 4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2 4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2 4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2 4-4-4-4-4-3-4-4-4-4-4-4-4-2-2-2-2 I can't seem to establish the problem. Thanks in advance... A: osRead.ReadLine() returns Nothing if the end of the input stream is reached. You call Peek to see if you're at the end of the input, but then, you proceed to read 12 lines without checking if you're at the end of the input in-between. If you have less than 12 more lines, you'll get the error you mentionned on temp.Split("-"), because temp will have a value of Nothing, so you can't call methods on it. Also, just noticed something... your Map is 11x8, but you're reading 12 lines, and going through 9 values, you probably want to do: For x As Integer = 0 To 10 or For x As Integer = 1 To 11 Same thing for your other loop. A: * *Always use Option Strict On! (Your code shouldn’t even compile, you need to parse the input integers, or your map stores strings, which is equally as bad since you logically store numbers.) *Name your variables properly. *Omit vacuous comments. Only comment things that aren’t obvious from the code. *Don’t hard-code magic numbers (what’s 11? 8?) *Don’t declare variables before initialising. Declare on first use. *The outer loop in your code makes no sense. *Don’t close streams manually, always use a Using block to ensure the program still works in the face of exceptions. *Initialise map. Which leaves us with: Public Sub LoadMap(ByVal URI As String) Const MapHeight As Integer = 12 Const MapWidth As Integer = 9 Me.map = New Integer(MapHeight, MapWidth) { } Using reader As New System.IO.StreamReader(URI) For x As Integer = 0 To MapHeight - 1 Dim line = reader.ReadLine() Dim tokens() As String = line.Split("-") For y As Integer = 0 To MapWidth - 1 Me.map(x, y) = Integer.Parse(tokens(y)) Next y Next x End Using End Sub Bonus: Check for errors: what if the map doesn’t have the predefined width/height? Why hard-code this at all? A: If temp is null (Nothing) in VB.Net, then you can't call methods on it. Do a check for Nothing before attempting to do anything with the value. So Just to be sure you have updated your code to look something like this: If temp IsNot Nothing 'tempLine stores the split read line Dim tempLine() As String 'splits readline into - ERROR Not set to an instance tempLine = temp.Split("-") 'adds values to multidimensional array For y As Integer = 0 To 8 Me.map(x, y) = tempLine(y) Next y End If And you are STILL getting the null reference exeption? A: also make sure that your StreamReader is properly initialized... if the initialization fails (perhaps because of a bad URI) then attempting to call osRead.peek() will throw the "object not set to an instance" error.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: reorder columns of a csv file containing float, integer and text data? I would like to do a similar process to a csv file as detailed in this question, but I get an error message saying: TypeError: list indices must be integers The csv file that I want to rearrange has a combination of float, text, and integer data types. I'm assuming this is the problem, but can't figure out a way to modify the code below to insert the data. It writes the header information in the new CSV file though. I'm using the same code as suggested by John Machin, but my write names variable uses: writenames = "ID,average,max,min,median,mode,stddev,skewness,kurtosis".split(",") reader = csv.reader(open("/home/usrs/chris/Summary.csv", "rb")) writer = csv.writer(open("/home/usrs/chris/SummaryNEW.csv", "wb")) readnames = reader.next() names2indicies = dict((name,index) for index, name in enumerate(readnames)) writeindices = [names2string[name] for name in writenames] reorderfunct = operator.itemgetter(writeindices) writer.writerow(writenames) for row in reader: writer.writerow(reorderfunct(row)) A: operator.itemgetter() is all you need: inp=csv.reader(open(...)) outp=csv.writer(open(...)) map(outp.writerow,map(operator.itemgetter(x,y,z),inp)) Where x,y,z are the columns you want to re-order. However, since the first row in Summary.csv is headers, then you might consider using DictReader and DictWriter: writenames = "ID,average,max,min,median,mode,stddev,skewness,kurtosis".split(",") reader = csv.DictReader(open("/home/usrs/chris/Summary.csv", "rb")) writer = csv.DictWriter(open("/home/usrs/chris/SummaryNEW.csv", "wb"), \ fieldnames=writenames) reorderfunct = lambda r: dict([(col, r[col]) for col in writenames]) writer.writeheader() for row in reader: writer.writerow(reorderfunct(row))
{ "language": "en", "url": "https://stackoverflow.com/questions/7583850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: True and False for && logic and || Logic table Table true/false for C Language I have heard of a table true false for C Language for and && or || is kind of the mathematics one for which they say if true+true=true and false+true=false I'm just kind of confuse on this and I tried to do the research but couldn't find any of the table I just wish to have this table for my notes since I will do more in C language if someone could bring me to the site or resources where they explain about this more I've edited my original question to make it a note for my own study. Thanks @thiton for the great references and the rest for an awesome answer/resources. Logical AND (&&) false && false: false false && true: false true && false: false true && true: true Logical OR (||) false || false: false false || true: true true || false: true true || true: true Logical NOT (!) !false: true !true: false A: You're thinking of Boolean algebra. A: Truth values can be described using a Boolean algebra. The article also contains tables for and and or. This should help you to get started or to get even more confused. A: I think You ask for Boolean algebra which describes the output of various operations performed on boolean variables. Just look at the article on Wikipedia. A: I`d like to add to the already good answers: The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,∨ and AND,∧ and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!". Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int! int main () { std::cout << "true - true = " << true - true << std::endl; // This can be used as signum function: // "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers. std::cout << "true - false = " << true - false << std::endl; std::cout << "false - true = " << false - true << std::endl; std::cout << "false - false = " << false - false << std::endl << std::endl; std::cout << "true + true = " << true + true << std::endl; std::cout << "true + false = " << true + false << std::endl; std::cout << "false + true = " << false + true << std::endl; std::cout << "false + false = " << false + false << std::endl << std::endl; std::cout << "true * true = " << true * true << std::endl; std::cout << "true * false = " << true * false << std::endl; std::cout << "false * true = " << false * true << std::endl; std::cout << "false * false = " << false * false << std::endl << std::endl; std::cout << "true / true = " << true / true << std::endl; // std::cout << true / false << std::endl; ///-Wdiv-by-zero std::cout << "false / true = " << false / true << std::endl << std::endl; // std::cout << false / false << std::endl << std::endl; ///-Wdiv-by-zero std::cout << "(true || true) = " << (true || true) << std::endl; std::cout << "(true || false) = " << (true || false) << std::endl; std::cout << "(false || true) = " << (false || true) << std::endl; std::cout << "(false || false) = " << (false || false) << std::endl << std::endl; std::cout << "(true && true) = " << (true && true) << std::endl; std::cout << "(true && false) = " << (true && false) << std::endl; std::cout << "(false && true) = " << (false && true) << std::endl; std::cout << "(false && false) = " << (false && false) << std::endl << std::endl; } yields : true - true = 0 true - false = 1 false - true = -1 false - false = 0 true + true = 2 true + false = 1 false + true = 1 false + false = 0 true * true = 1 true * false = 0 false * true = 0 false * false = 0 true / true = 1 false / true = 0 (true || true) = 1 (true || false) = 1 (false || true) = 1 (false || false) = 0 (true && true) = 1 (true && false) = 0 (false && true) = 0 (false && false) = 0 A: You probably mean a truth table for the boolean operators, which displays the result of the usual boolean operations (&&, ||). This table is not language-specific, but can be found e.g. here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "67" }
Q: Problem with Jquery UI Buttons - first one not loading? I am trying to use the Jquery UI to use radio inputs as buttons. This is the code I've got so far: <div id="time-buttons" <input type="radio" id="radio1" name="radio" /><label for="radio1">Choice 1</label> <input type="radio" id="radio2" name="radio" checked="checked" /><label for="radio2">Choice 2</label> <input type="radio" id="radio3" name="radio" /><label for="radio3">Choice 3</label> <input type="radio" id="radio4" name="radio" /><label for="radio4">Choice 4</label> <input type="radio" id="radio5" name="radio" /><label for="radio5">Choice 5</label> </div> and the javascript: $( "#time-buttons" ).buttonset(); The problem that I have is that radio1 is not being changed into a button, but all of the others are. When I've looked inside Firebug, it looks as though the tag isn't present for Choice 1. Does anyone know why this is happening? Thanks for any help Edit: Sorry, just realised a very stupid mistake...basically I missed off the closing div >. Stupid me! A: As the highlighter probably helped you figure out, your first <div> tag isn't complete. Errors like this are easier to see in an editor that does syntax highlighting, and are often reported in Chrome's console (in the developer tools).
{ "language": "en", "url": "https://stackoverflow.com/questions/7583855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: T4 template for an MVC Controller with Entity Framework - member properties of the host (MvcTextTemplateHost)? Does anyone have a full reference of the members of the Host object I can use in the T4 template ControllerWithContext.tt that comes with MVC 3? I've tried every google search I could think of, but the only relevant result is this page: http://blogs.msdn.com/b/webdevtools/archive/2009/01/29/t4-templates-a-quick-start-guide-for-asp-net-mvc-developers.aspx But it only shows 4 properties(ItemName, NameSpace, ExtraActionMethods, ControllerRootName) and not the full list. In the template there are things like RelatedProperties, EntitySetName, ModelType and ContextType. I'm trying to find the full list of properties, their types and descriptions. Any help would be greatly appreciated. A: I have put together an unofficial list of ASP.NET MVC 3 properties available to T4 templates when you use the Add View or Add Controller dialogs in Visual Studio 2010. It does not cover the properties that are available when using MvcScaffolding in the NuGet Package Manager Console. The property information was determined using a T4 template to reflect over the public properties on the MvcTextTemplateHost. Add Controller: +--------------------+---------------+----------------------------------------------------------------------------------------+ | Property Name | Type | Description | +--------------------+---------------+----------------------------------------------------------------------------------------+ | AddActionMethods | Boolean | Adds action methods to the generated controller class. | | AreaName | System.String | The name of the Area that the controller is created for. | | ContextType | System.Type | The type of the data context. | | ControllerName | String | The name of the controller class that will be generated. | | ControllerRootName | String | The name of the controller class excluding the Controller part at the end of the name. | | EntitySetName | String | Name of the property on the data context class containing the set of entities. | | ModelType | System.Type | The type of the model class specified in the Add Controller dialog. | | Namespace | String | Namespace that will be used for the generated controller class. | | PrimaryKeys | PrimaryKey[] | Primary keys for the model. See table at end for PrimaryKey properties. | | RelatedProperties | Dictionary | Related properties on the model. See table at end for RelatedModel properties. | +--------------------+---------------+----------------------------------------------------------------------------------------+ Add View: +-----------------------------+---------------+------------------------------------------------------------------------------------------+ | Property Name | Type | Description | +-----------------------------+---------------+------------------------------------------------------------------------------------------+ | AreaName | System.String | The name of the Area that the view is being created for. | | ContentPlaceHolderIDs | List<string> | List of content place holder IDs in the master page. | | IsContentPage | Boolean | True if the generated view will be created with a master page or a Razor layout page. | | IsPartialView | Boolean | True if the generated view is a partial view (e.g. an ASP.NET user control). | | MasterPageFile | String | Master page file or Razor layout to be used with view (e.g. ~/Views/Shared/Site.Master). | | Namespace | String | Namespace that will be used for the generated view. | | PrimaryContentPlaceHolderID | String | Primary content place holder ID to be used when creating a view using a master page. | | ReferenceScriptLibraries | Boolean | True if checked in the Add View dialog. | | ViewDataType | System.Type | The view model's type. | | ViewDataTypeName | String | Fully qualified name for the view model's type. | | ViewName | String | Name of the view. | +-----------------------------+---------------+------------------------------------------------------------------------------------------+ Common Properties: +---------------------+-------------------------+-----------------------------------------------------------------------------------------------+ | Property Name | Type | Description | +---------------------+-------------------------+-----------------------------------------------------------------------------------------------+ | AssemblyPath | List<string> | List of assemblies referenced by the project and the project's output assembly. Internal use. | | Errors | CompilerErrorCollection | Used to stored errors that occur whilst processing the T4 template. Internal use. | | FileEncoding | System.Text.Encoding | The encoding of the file that will be generated. | | FileExtension | String | Not set. | | FrameworkVersion | System.Version | The .NET framework version. | | OutputFileExtension | System.String | The extension of the file that will be generated. | | TemplateFile | System.String | The full path to the T4 template file being used. | +---------------------+-------------------------+-----------------------------------------------------------------------------------------------+
{ "language": "en", "url": "https://stackoverflow.com/questions/7583858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Resharper 6 create auto property by default When I write code and need new property, i simply write propery name as it would exist already and choose action from menu: Problem is, that it generates code like this: protected int SomeNewProperty { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } So I need to go there and manually adjust that (actually I prefer to choose Create field from menu and change it to auto property). Anyway, I thought, may be there is a way to change default behavior of "Create property", that it would create auto property instantly? Update In Resharper 8 auto properties are available and may be set by default! A: There is an option to change default body style. However, the close you can get is protected int SomeProperty { get { return 0; } set { } } A: You cannot do this in R# (at least in v6). That is, create a pseudo property and have resharper generate the Auto Property stub. You can still use the superior method that Visual Studio uses. Type out your new property which will show as a syntax error and then CTRL + . shows VS mini menu. Then just hit enter and straight away, the job is done. It does not take you to the class file which can be distracting too. To use the shortcut above, you don't even need to have you cursor on the broken property name. So this is better than the method described by Rickard as it is faster and less distracting you away from the code you are writing. A: Just when you click Create property it will halt on the type. Hit tab and you will get a context menu with the option to use Auto property. A: There is a default snippet that comes with Visual Studio called 'prop' Just type that, hit , give a type name and give it a name. Done and done. I know that doesn't answer your question in terms of Resharper, but it is functionality already provided by the Visual Studio IDE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: Monkey patching 'datetime' produces strange results I'm trying to make one of my libraries compatible with Python 2.6. It uses the method datetime.timedelta.total_seconds which was added in 2.7, so to make it work with 2.6, I wanted to monkey patch it into timedelta like this: import datetime if not hasattr(datetime.timedelta, 'total_seconds'): class timedelta(datetime.timedelta): def total_seconds(self): return self.days * 86400.0 + self.seconds + self.microseconds * 1e-6 datetime.timedelta = timedelta This does actually work in some cases, e.g. if I create a timedelta variable, it does have this method. But if a new timedelta object is produced by subtracting two datetime.datetime values, the method is missing from the resulting object. What's going wrong and how do I fix this? A: The datetime module is written entirely in C. This includes the function that subtracts one datetime.datetime object from another. That function -- called new_delta() -- directly instantiates PyDateTime_DeltaType, which is the original datetime.timedelta class (written in C). It won't notice that you've rebound datetime.timedelta to your own class in Python-land. I don't see any easy workarounds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Difference to how declare instance variables If I have this class: class G { Texture a, b, c; } and class F { Texture a; Texture b; Texture c; } is there a difference in what access modifier is assigned or both are equivalent and thus how write them is only a style-preference? A: There is no functional difference; a, b and c will all be declared as private Texture fields. (private is the default access modifier for members of a class.) Whether you choose to use one access modifier and type declaration for each one, or for all three, is purely stylistic. A: There is no difference in C# - just stylistics (I prefer the second one). In languages such as C and C++, it would make a difference with pointers: int* p1, p2, p3; // p1 is a pointer to int, but p2 and p3 aren't In C# we don't have this problem: int* p1, p2, p3; // Ok, all three are pointers int *p1, *p2, *p3; // Invalid in C# Also, in C++ sometimes T a, b; is not equivalent to T a; T b; even when T is not a pointer - that's the case when a coincides with T; T T, X; //T and X are of type T T T; T X; //error T is not a type Sorry, I posted more about C++ than about C#, but this is to demonstrate that C# has taken care of potential differences between the two forms which C++ hasn't :) A: The result is the same. It's equivalent. A: No differences! There is just a style choice. A: this is purely stylistic and if you want to know more about access modifiers you can get it here
{ "language": "en", "url": "https://stackoverflow.com/questions/7583868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Injecting a named String using CDI I want to have a configuration parameter injected this way: public class MyManagedBean { @Inject public MyManagedBean(@Named("user") String user){ .... } } So I tried to implement a producer method this way: @ApplicationScoped public class MyConfiguration { private Properties loadProperties() { Properties properties = new Properties(); try { properties.load(getClass().getResourceAsStream( "user.properties")); } catch (IOException e) { throw new RuntimeException(); } return properties; } @Produces @Named("user") String getUser() { return loadProperties().getProperty("user"); } } I have other bean defined this way: public class OtherManagedBean { @Inject public OtherManagedBean(MyManagedBean myManagedBean){ .... } } However, I'm having this exception when I try to deploy it: INFO: WEB0671: Loading application [example-ear#example-war.war] at [example] SEVERE: Exception while loading the app SEVERE: Exception while loading the app : WELD-001410 The injection point [parameter 1] of [constructor] @Inject public com.example.OtherManagedBean(MyManagedBean) has non-proxyable dependencies org.jboss.weld.exceptions.UnproxyableResolutionException: WELD-001410 The injection point [parameter 1] of [constructor] @Inject public com.example.OtherManagedBean(MyManagedBean) has non-proxyable dependencies at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:317) at org.jboss.weld.bootstrap.Validator.validateBean(Validator.java:139) at org.jboss.weld.bootstrap.Validator.validateRIBean(Validator.java:162) at org.jboss.weld.bootstrap.Validator.validateBeans(Validator.java:385) at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:371) at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:390) at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:190) at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:128) at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:298) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:370) at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1067) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1247) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:465) at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:222) at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168) at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:234) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) at java.lang.Thread.run(Thread.java:662) Any idea? Thanks. A: It looks like you need a default (no-arg) constructor for your MyManagedBean to make it proxyable. I am not really sure about why it is needed, since MyManagedBean is a @Dependent bean and so is not proxied AFAIK; I do not know even why a proxyable bean needs a default constructor, to be honest This seems to be an implementation detail or a little point from CDI specification that was ignored. Anyway, I bet it can make a good new question :) EDIT: I discovered why a proxyable bean needs a default construction. It is no mistery, actually: since the proxy of a bean is a subclass of the same bean, the proxy needs to call a super() constructor in its own construction. If it has no non-private default constructor, it does not know which constructor to call. One can even imagine a scenario where the injected constructor is called to create the proxy, but I do not know which kind of complexity it can add to a CDI implementation; it may not be so easy to do...
{ "language": "en", "url": "https://stackoverflow.com/questions/7583871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to generate a random number for each page? I'm using node.js and express, and I'd like to generate a random five-figure number in app.js and return it to the client. I'd like to do this on the server rather than the client, because I want to be certain that the number is different for every user who is currently connected. Here's my current (broken) code from app.js: // My first attempt - a function to generate a random number. // But this returns the same number to every client. function genRandNum() { return Math.floor(Math.random() * 90000) + 10000; } // Routes app.get('/', function(req, res){ res.render('index', { title: 'Hello world', random_id: genRandNum() // No good - not different for each user. }); }); There are actually two problems: * *How can I generate a number for each client? *How can I be certain the number is different for every client? Do I need to create a Redis store of currently open sessions and their numbers? Thanks for helping out a beginner :) A: Your code works for me, with index.jade: h1 #{random_id} However, as written it generates a random # for each page, not just each client. Some sort of backing data store would be needed to permanently guarantee each client has a unique #, but since you're only using 5-digits (90K possible IDs), you're clearly not concerned with this being unguessable. And if you only care about this in the context of a single node process, why not just use an auto incrementing value? var clientId = 1; app.get('/', function(req, res){ res.render('index', { title: 'Hello world', random_id: clientId++ }); }); A: For unique random numbers, you can also take the help from your user .. he can enter some random key strokes and then you can modify them/add/subtract something and send at server
{ "language": "en", "url": "https://stackoverflow.com/questions/7583874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Function name in stack trace of SpiderMonkey I'm using the SpiderMonkey engine 1.8 and I'm unhappy with the way it creates the stack trace. We occasionally receive auto-generated function names in JavaScript-files from the server, which aren't really readable. On the client side I have access to other functionalities that allow me to make them more readable to humans. Does anyone know how SpiderMonkey builds one line of a stack trace? Is there a way I can influence this? * *The name-property of a function is readonly *WebKit's displayName doesn't seem to work in SpiderMonkey (yet) EDIT: I took a look at the source of SpiderMonkey and, whow, I don't know if it's just me, but that C++ code is close to unreadable. Well, I don't have that much experience with C++, but it's damn hard to find a way through all those files. I found no way... So, please, it's up to you :). A: If you want to take the stacktrace and manipulate it, you could use stackinfo to get parsed stacktrace information, then rebuild the stacktrace how you want to build it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: XAML vs. controls created at runtime In Windows Phone, what is better from performance point of view, to define controls in XAML or creating them dynamically at runtime? What are cons/pros for XAML and runtime controls? A: I remember reading that Xaml loading is more efficient than the equivalent creation in code, however: Factors that effect the speed included the number of named elements (as they get connected to code-behind members by lookups in the designer file) and the number of similar/total elements. From a business perspective keeping it in Xaml is a far easier way to maintain a project. The whole purpose of Xaml was to allow designers to work on the look independent of the coders. A: I think i'm right in saying that perf wise it does not matter. From a Dev perspective, having the controls defined in the XAML allows a clear separation, and if you are using MVVM, you get all the benefits that pattern brings (unit testing, clear separation, better manageability etc) also, if you have your controls defined in XAML, your app will lend itself better to Blend development and allow you to control the look and feel of your app visually. I prefer to keep all UI controls in XAML, and do the nuts and bolts in code..but the framework is designed to suit all dev tastes A: I think if you try to define animations/VisualStates using pure code, you'll realize how great Blend can be. The Binding syntax also, doesn't feel very readable in code, but then, that's maybe a matter of taste. A: The performance difference is negligible and shouldn't even be a factor because the maintenance and code quality difference is so large. Code-generated controls are a nightmare to maintain, are difficult to design and style, and make it harder for developers to follow the application flow. You basically are asking about the difference between using XAML which can provide design-time views, separate presentation logic from business logic, and allows tools like Blend to take over, versus a programmatic approach that negates all of the above. What if you decided down the road to port your application to Windows 8 and use the WinRT engine? With the XAML approach and a pattern like MVVM you could likely reuse the bulk of your code and simply update some of the views, whereas with a programmatic approach all of that code would have to be trashed in favor of the new runtime. So even if there was a slight performance difference between one over the other, I'd suggest it doesn't matter because the other factors are far more important to consider.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: insert string into middle of antoher string at an specific, but unknown point - objective c i have been struggling with this one for a couple of days i have a block of string which is html , which i am loading into a web view as html text. what i would like to do is insert an image aprox halfway into the string, but do it at the start or end of a paragraph , so i keep the overall format of the string for example, if i have <p> some text <p> would like to insert image here <p> more text is there any way i can do this A: you can load webview using below string NSString* mTheBackgroundPath = [[NSBundle mainBundle] pathForResource:@"logo_s28" ofType:@"png"]; mTheBackgroundPath = [ mTheBackgroundPath stringByReplacingOccurrencesOfString:@"/" withString:@"//"]; mTheBackgroundPath = [ mTheBackgroundPath stringByReplacingOccurrencesOfString:@" " withString:@"%20"]; mTheBackgroundPath = [@"file://" stringByAppendingString:mTheBackgroundPath]; NSString *htmlString = [NSString stringWithFormat:@"<p> some text <p> %@ <p> more text",mTheBackgroundPath];
{ "language": "en", "url": "https://stackoverflow.com/questions/7583885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Google plus-one button on a page that is refreshed with AJAX Is anyone aware of some code for Google's plus-one button that will work on a page that is refreshed with AJAX? It was very simple with Facebook, but I can't find any documentaion about this for Google. Thanks. A: I was searching for this too and found this <!-- Place this tag in your head or just before your close body tag --> <script type="text/javascript" src="https://apis.google.com/js/plusone.js"> {parsetags: 'explicit'} </script> <!-- Place this tag where you want the +1 button to render --> <g:plusone></g:plusone> <!-- Place this render call where appropriate --> <script type="text/javascript">gapi.plusone.go();</script> gapi.plusone.go(); place this code and the button will appear A: If you're trying to render a person badge with ajax rather than a plusone you need a different api call: api.person.go(); https://developers.google.com/+/web/badge/#gapi.*.go
{ "language": "en", "url": "https://stackoverflow.com/questions/7583892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Why is this an invalid column in SQL stored proc? I have the following SQL stored procedure that when I try to save it, it complains about "Invalid column name 'Goal'" in the last select statement. Can someone tell me why this is an invalid comlumn name? I am doing basically the same thing for NetSales and it doesn't complain about that column. if object_id('tempdb..#tmpHours') is not null DROP TABLE #tmpHours if object_id('tempdb..#tmpPay') is not null DROP TABLE #tmpPay SET @MondayOfCurrentWeek = (SELECT DATEADD(wk, DATEDIFF(wk,0,@WeekOf), 0) ) SELECT p.PerceptionistID AS PerceptionistID, p.BaseCommission AS BaseCommission, p.BonusCommission AS BonusCommission, h.WeekOf AS WeekOf, h.WorkHours AS WorkHours, h.PTOHours AS PTOHours, h.HolidayHours AS HolidayHours, ROUND(h.WorkHours, 0) AS HoursRounded, ( SELECT COUNT(c.PerceptionistID) FROM T_Call c WHERE c.PerceptionistID = p.PerceptionistID AND c.OutcomeID = @OutcomeSale AND EnteredOn BETWEEN @MondayOfCurrentWeek AND DATEADD(dd, 7, @MondayOfCurrentWeek) ) AS GrossSales, ( SELECT COUNT (c.PerceptionistID) FROM T_CallCredit cc INNER JOIN T_Call c ON cc.CallID = c.CallID WHERE c.PerceptionistID = p.PerceptionistID AND cc.CallCreditStatusID NOT IN (17, 18) -- 17 - 'Error in Customer Account', 18 - 'Courtesy Credit' AND cc.EnteredOn BETWEEN @MondayOfCurrentWeek AND DATEADD(dd, 7, @MondayOfCurrentWeek) ) AS Credits INTO #tmpHours FROM T_Perceptionist p RIGHT JOIN T_PerceptionistHours h ON p.PerceptionistID = h.PerceptionistID WHERE h.WeekOf = @MondayOfCurrentWeek SELECT PerceptionistID, CAST((HoursRounded*2) AS int) AS Goal, GrossSales, Credits, (GrossSales - Credits) AS NetSales, HoursRounded, WorkHours, PTOHours, HolidayHours, BaseCommission, BonusCommission, [dbo].fnCalculateCommission(BaseCommission, BonusCommission, (GrossSales - Credits), CAST((HoursRounded*2) AS int)) AS CommissionPay INTO #tmpPay FROM #tmpHours --- Complains about column name 'Goal' in the following statement SELECT PerceptionistID, Goal, GrossSales, Credits, NetSales, HoursRounded, WorkHours, PTOHours, HolidayHours, BaseCommission, BonusCommission, CommissionPay FROM #tmpPay A: Try running it in a new connection or dropping the temp tables in a separate batch first. Possibly the #temp tables are still hanging about from a previous batch when you did not have the Goal column and the parser validates the column names against the existing table, encounters a binding error and refuses to run the batch. If the temp tables don't exist at all compilation of the statement will be deferred.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: grouping controller in subdirectories for nested resources I would like to organize my controllers in subdirectories. Here is an example: routes.rb: resources :locations do resources :users end I would like to put my controller in the appropriate subdirectory: app/controllers/locations/users_controller.rb and the url would be (standard): /locations/1/users /locations/1/users/new /locations/1/users/10/edit ... If i had a namespace in my routes I could change my users_controller.rb to class Locations::UsersController < LocationsController end but it does not work with nested resources, instead I get the following error: Routing Error uninitialized constant UsersController Update It works if I add: resources :locations do resources :users end match 'locations/:location_id/users' => "locations/users#index" but I would have to add a route for every action and nested resource... A: Like Kwon says, it's the order that matters. But you can still use a namespace. .../config/routes.rb namespace :locations do resources :users end resources :locations .../app/controllers/locations_controller.rb: class LocationController < ApplicationController .../app/controllers/locations/users_controller.rb: class Locations::UsersController < LocationsController A: If you want to use just that one route: match 'locations/:location_id/users' => "locations/users#index" That should come before any other resources/matches that might conflict with that match. By default Rails routes are top-bottom. # should be before locations resource resources :locations do resources :users end Alternatively, if you want to punt all your nested users resource over to locations/users you can assign a controller to the resource. resources :locations do resources :users, :controller => "locations/users" end A: One can use modules to have nested routes with nested controllers: resources :locations do scope module: :locations do resources :users end end $ rake routes ... location_users GET /locations/:location_id/users locations/users#index ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7583898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Upgrade page layout with sharepoint feature I use sharepoint 2010. I have a feature which contains some pages layout. When the feature is activated, page layout are applied. But when I deploy a new version of this feature with a new version of pages layout, page layout aren't take into considerations because they have the same name. How can i do this ? A: Your page layouts won't update because they're unghosted, i.e. customized in the Master Page Gallery. It has nothing to do with the files having the same name unless you've explicitly set IgnoreIfAlreadyExists to FALSE in your elements.xml in the feature. If your solution doesn't contain any important pages yet (development server or otherwise), the simplest solution is the following: * *Delete the page layouts, (making sure no pages reference the page layouts in question, else you won't be able to delete them.) *In Central admin, uncheck "Allow Site Collection Administrators to Customize Master Pages and Layout Pages" ( see http://blogs.msdn.com/b/steve_fox/archive/2010/03/08/ghosting-unghosting-in-sharepoint-2010.aspx for details). *Redeploy your solution See also http://blogs.technet.com/b/wbaer/archive/2007/08/10/ghosts-in-the-machine.aspx for a thorough explanation of ghosting and unghosting in SharePoint Hope this answers your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Environment info in Tornado I've been trying to use Tornado for some part of my application. For that, I want to find out the environment information of the user, that is, the browser and OS of the user. In pylons, I can do that but I am not getting how to do that in Tornado/ A: All that information is stored in the request field of the the RequestHandler instance. It can be accessed via self.request from within RequestHandler methods. It's an instance of tornado.httpserver.HTTPRequest. Information about browser, OS etc. will be found in the headers field. Example: import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write(self.request.headers) if __name__ == "__main__": application = tornado.web.Application([ (r"/", MainHandler), ]) application.listen(8888) tornado.ioloop.IOLoop.instance().start()
{ "language": "en", "url": "https://stackoverflow.com/questions/7583900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: issue in openfeint when i call setHighScore function I am integrating openfient SDK in my app. When I want to submit user's score and called a function as below it is giving error 'OFDelegate' was not declared in this scope [OFHighScoreService setHighScore:scores forLeaderboard:@"112033" onSuccess:OFDelegate() onFailure:OFDelegate()]; Please help me to shortout this issue. A: This problem may occur when upgrading from an old version of open feint or reading an old post about Open Feint, as this method is no longer available, yet still compiles and runs. The following lines will probably be enough to solve this problem: [OFHighScoreService setHighScore:scores forLeaderboard:@"112033" onSuccessInvocation:[OFInvocation invocationForTarget:nil selector:nil] onFailureInvocation:[OFInvocation invocationForTarget:nil selector:nil]]; Just don't forget to import: #import "OFHighScoreService.h" A: Make sure you have integrated OpenFeint SDK with your app. You may find this video useful: http://vimeo.com/5633994
{ "language": "en", "url": "https://stackoverflow.com/questions/7583906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: T-SQL: Disable default FLOAT rounding when using Table with its View Good day! Here is the problem of float rounding when I want insert data into Table using its View. Data NEED to store as varchar in Table. Table: CREATE TABLE [dbo].[TestTableFloat_E] ( [id] [int] IDENTITY(1,1) NOT NULL, [FloatField] [varchar](100) NOT NULL ) View: ALTER VIEW [dbo].[TestTableFloat] AS SELECT id ,Convert(float, FloatField) as FloatField FROM dbo.TestTableFloat_E The data, what I select from Table using its View - have to have float type (field FloatField). I can't insert data into Table, if i need, I need do it with its View. So, I can't (this is task rule) insert data directly into Table, just with View. I create trigger to insert data: CREATE TRIGGER [dbo].[tr_TestTableFloatInsert] ON [dbo].[TestTableFloat] INSTEAD OF INSERT AS BEGIN SET NOCOUNT ON; insert into TestTableFloat_E (FloatField) select FloatField FROM INSERTED Actions: I try insert data into TestTableFloat_E (table) with help of its View (TestTableFloat), rises trigger and insert data into table. Problem: When I insert float number, I have rounding, that I don't need: insert TestTableFloat (FloatField) select 123.123456 I have 123,123 in the Table TesttableFloat. I need it doesn't round, I have to have 123.123456 What can it be? A: You can have it store more digits, but it's going to switch to scientific notation: CREATE TRIGGER [dbo].[tr_TestTableFloatInsert] ON [dbo].[TestTableFloat] INSTEAD OF INSERT AS BEGIN SET NOCOUNT ON; insert into TestTableFloat_E (FloatField) select CONVERT(varchar(100),FloatField,2) FROM INSERTED END Which ends up storing 1.231234560000000e+002 into the table. From CAST and CONVERT: When expression is float or real, style can be one of the values shown in the following table. Other values are processed as 0. 0 (default) A maximum of 6 digits. Use in scientific notation, when appropriate. 1 Always 8 digits. Always use in scientific notation. 2 Always 16 digits. Always use in scientific notation. Insert usual caveats about futility of expecting float and a decimal representation of the same to always be exactly convertible, and of using inappropriate data types to store particular types of data It would appear the best data type to use for this data would be decimal with appropriate scale and precision, which is neither of the types you're working with. But you claim that those are the "required" types. E.g. if the view uses a decimal instead of a float, the stored varchar(100) value is exactly as expected.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get photos from camera roll? I tried to use ALAssetLibrary to get albums and photos. This is my code: void (^assetEnumerator)(struct ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) { if(result != NULL) { NSLog(@"See Asset: %@", result); } }; void (^assetGroupEnumerator)(struct ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) { if(group != nil) { [group enumerateAssetsUsingBlock:assetEnumerator]; } }; ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init]; [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:assetGroupEnumerator failureBlock: ^(NSError *error) { NSLog(@"Failure"); }]; I'm getting exc_bad_access on : [group enumarateAssetsUsingBlock:assetEnumerator] and the group is not nil. The strange thing is that this code is working if I create a new project, but in my old project it's not working. SDK version is iOS 4.3 Tested on iPhoneSimulator 4.3 Can anyone could give me an ideea of what's happening? Thanks. A: As you crash on the one project but not on the other, are you sure the settings and configurations are appropriate? In particular: * *Check that the TARGET_DEPLOYMENT_OS is set to the minimum version the ALAsset framework is available. *Check that you have included all the requested frameworks (even if the linker should warn about this if you forgot to include it) Moreover, the details of the crash (crashlog, exception details, ...) would be helpful if any. Also are you sure the ALAssetLibrary isn't released before the enumeration (which is probably done asynchnously) ends? There is no release in your code in your question but maybe there is one in your real code? AFAIK, enumerateGroupsWithTypes: executes its block on a secondary thread in an asynchrnous way (see this other question on SO), so that's probably your problem (you are trying to use a group that has been released from memory since you start your enumeration, you have to be sure the ALAssetLibrary is still in memory until the enumeration is done)
{ "language": "en", "url": "https://stackoverflow.com/questions/7583909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP Post form and return xml result I have a form which submits to a external url and the url returns a xml result whether the action did go well or not. I want the form to be posted and the xml result to returned so the user can see the xml result instead of the external url being opened in blank window without any formatting. I'm not sure how to make this. A: Instead of posting the form directly to the external script, you will need to wrap it in your own PHP code to be able to deliver the XML back to your user to view. To do this, you can: * *Make the form post to itself instead of directly to the external resource *Capture the $_POST *Transfer it to a cURL request that posts to the external form *Retrieve the output from the cURL request and display it for your user, wrapped in <pre></pre> to preserve XML formatting. Note however, that some web browsers will correctly display the returned XML as it already is, provided it is correctly identified as XML by the server sending it. You don't have control over that on either the external server or your end user clients though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583913", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Different Size arrays when reading from a stream When writing characters to an array from a stream, is there a way to make the length of the array the exact number of characters if the size of the stream is unknown at compile? For example when reading text input into an array and the size of text can be any length. A: Find the size of the file fseek(fp, 0, SEEK_END); size = ftell(fp); /* Rewind. */ fseek(fp, 0, SEEK_SET); Allocate the memory char *buf = malloc(size); A: It has been a while since I've written C, but I believe you can use the malloc() function to dynamically allocate a block of memory. char* str = malloc( sizeof( char ) * lengthOfStream ) ; A: Are u asking about to increase the lenght of the each array element size or wants to increase the lenght or size of the array(no.of elements) if u wants to increase the no.of elements then use this syntax char array[]; if you are talking about the individual element its not possible to increase because the datatype by whixh we decleared an array was constant. Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/7583916", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XML empty tag being converted to open and closing tag pair I have a large XML master configuration file that contains details for a a number of inter connected applications. Much of the configuration is common to all applications but some pieces differ, such as IP addresses, database connection strings etc. I've enclosed the elements specific to a particular application within a conditional element and an attribute is used to define which application the nested elements are used for. This allows me to transform the master configuration file to generate the required application specific config file. The problem I'm having is the output XML has empty tag elements of the form <add key="Setting3" value="1.2.3.4" /> changed to <add key="Setting3" value="1.2.3.4"> </add> While I understand this should not matter, it makes it harder to diff the resulting XML file with the current app specific files which were all created by hand. Is there something I can do to my xslt that will keep the empty tags unchanged in the results? My xslt is as follows <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:param name="app" select="''"></xsl:param> <xsl:output method="xml" indent="yes" version="1.0" encoding="utf-8"/> <xsl:template match="node()|@*"> <xsl:copy> <xsl:apply-templates select="node()|@*|comment()|processing-instruction()"/> </xsl:copy> </xsl:template> <xsl:template match="conditional"> <xsl:if test="starts-with(@app,$app))"> <xsl:copy-of select="*|@*|comment()|processing-instruction()"/> </xsl:if> </xsl:template> </xsl:stylesheet> A sample master config file is as follows <?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- Common Settings for all applications --> <add key="Setting1" value="1000" /> <add key="Setting2" value="600" /> <conditional app="App1"> <!-- App1 Settings --> <add key="Setting3" value="1.2.3.4" /> </conditional> <conditional app="App2"> <!-- App2 Settings --> <add key="Setting3" value="1.3.10.10" /> </conditional> </configuration> Thanks Edit: Changing the xml:output as Martin suggested improves the output as the closing tag is now appended to the opening tag on the same line, but I'd still like to get it to keep the empty tag formatting of the source XML file. So <add key="Setting3" value="1.2.3.4" /> becomes <add key="Setting3" value="1.2.3.4"></add> I am using Microsoft's msxml.exe version 3.0 as follows msxml.exe master.config config.xslt app=App1 > App1.config msxml.exe master.config config.xslt app=App2 > App2.config If there is a better processor I suspect it would be fine for me to switch to any other freely available processor that runs on Windows. A: I think the problem is not with the XSLT you have shown (although you could try whether using <xsl:output method="xml" indent="no" version="1.0" encoding="utf-8"/> improves things) but rather with the way you run the transformation with your XSLT processor. So consider to tell us which XSLT processor you use and if you have code running the transformation to show us the code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android, getting an exception that is crashing my app I am a noob learning android by making a simple game: There are a few buttons that the user can press I show some questions on the screen and he has to press one of the buttons as the answer when he presses the button I play a sound. 3 wrong answers and the game is over. Simple right? Everything works and I have learned a lot except for one "#%#"%"# exception that keeps crashing my app :( It's really strange, on 3 wrong answers the game is over so I run this code: soundPool.release(); this.finish(); which sends the user back to the last activity and they can start the game again. The problem arises every 3-5 times that they restart the game... I get a force close and this in logcat: http://imageshack.us/photo/my-images/90/91939698.png/ The error seems to be here: public void playSound(int sound) { AudioManager mgr = (AudioManager)GameScreen.this.getSystemService(Context.AUDIO_SERVICE); float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC); float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume = streamVolumeCurrent / streamVolumeMax; /** The below line is line 117 that is crashing the program */ soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f); } Please advise on how I can crush this annoying "bug". Thanks! Ryan ================================================================================ EDIT: in onCreate I am doing this: new LoadMusicInBackground().execute(); and LoadMusicInBackground is this: /** Helper class to load all the music in the background. */ class LoadMusicInBackground extends AsyncTask<Void, String, Void> { @Override protected Void doInBackground(Void... unused) { soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 100); soundPoolMap = new HashMap<Integer, Integer>(); soundPoolMap.put(A1, soundPool.load(GameScreen.this, R.raw.a, 1)); soundPoolMap.put(A3, soundPool.load(GameScreen.this, R.raw.b, 1)); soundPoolMap.put(A5, soundPool.load(GameScreen.this, R.raw.c_s, 1)); soundPoolMap.put(A6, soundPool.load(GameScreen.this, R.raw.d, 1)); soundPoolMap.put(A8, soundPool.load(GameScreen.this, R.raw.e, 1)); soundPoolMap.put(A10, soundPool.load(GameScreen.this, R.raw.f_s, 1)); soundPoolMap.put(A12, soundPool.load(GameScreen.this, R.raw.g_s, 1)); soundPoolMap.put(wrong, soundPool.load(GameScreen.this, R.raw.wrong2, 1)); publishProgress(""); Log.v("SOUNDPOOL",""+soundPoolMap); return(null); } @Override protected void onProgressUpdate(String... item) { //text1.setText(item[0]); } @Override protected void onPostExecute(Void unused) { //Toast .makeText(GameScreen.this, "Done!", Toast.LENGTH_SHORT).show(); } } A: ... EDIT: public final void release() Release the SoundPool resources. Release all memory and native resources used by the SoundPool object. The SoundPool can no longer be used and the reference should be set to null. You cannot reuse soundPool object once you call release, so you need to create a new instance. So do this to make sure it is not resued: soundPool.release(); soundPool = null; A: I'd try logging soundPool and soundPoolMap as it looks like one of these are null. Perhaps as part of restarting the game these values are cleared? A: For a noob you're doing quite well :-D I think this is causing your problem: soundPool.release(); You're probably releasing it and try to reuse it next time. See release() documentation....
{ "language": "en", "url": "https://stackoverflow.com/questions/7583932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fade out on the parent not its children I have a page with a back ground image and a slider. Both of them are fadout and fadding in at the same time. The problem is that when i apply fadeout to the div containing the background image its children div also fadeout. Is there a way to avoid that. <div id="background"> ..... // all the page content goes here. <div id="slider"> </div> </div> <script> function fade(){ $('#background').dealy(5000).fadeout(1000,function(){//change the image}).fadein(1000, fade() ); //same for slider } </script>` A: If I understand the OP's question, he wants to fade out the background image of #background but none of its children or content. If I understand correctly, you should create two classes for the #background div as follows: div#background.nobg { background-image: none; background-color: transparent; } div#background.hasbg { background-image: url('url/to/bg.png'); } And then using jQuery you can animate the class attribute as follows: $('#backround').animate({ 'class': 'hasbg' }, 'slow', 'easein'); A: I believe a much simpler solution would be to put the background in a separate div with a low z-index and position fixed. <head> <style> #background{position:fixed; top: 0; left:0; height:100%;width:100%; z-index: 0; background-color:#00f;} #content{ z-index:1; background-color:white; height:50%;width:50%; position:absolute;} </style> </head> <body> <div id="content">Content goes here</div> <div id="background"></div> <script type="text/javascript"> $('#background').delay(5000).fadeOut(1000,function(){ $('#background').fadeIn(1000).css('background-color','#f00');}); </script> </body> Now you can do whatever you want with the background without affecting the content.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583936", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: problem in retrieving string I have array which has string like.. "Turn left onto <b>Sri Krishna Nagar Rd</b><div class=\"google_note\">Pass by <b landmarkid=\"0x39ed58475c24020f:0x170a2130a5880d5a\" class=\"dir-landmark\">California Academy of Visual Effects</b> <div class=\"dirseg-sub\">(on the left)</div>\n</div>" The above value I got from JSON.Now,how can I get string in the following format. Turn left onto Sri Krishna Nagar Rd Pass by California Academy of Visual Effects (on the left) Thanx in advance. A: USE this NSString *str =@"Turn left onto <b>Sri Krishna Nagar Rd</b><div class=\"google_note\">Pass by <b landmarkid=\"0x39ed58475c24020f:0x170a2130a5880d5a\" class=\"dir-landmark\">California Academy of Visual Effects</b> <div class=\"dirseg-sub\">(on the left)</div>\n</div>"; str = [str stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@""]; NSRange r; while ((r = [str rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound) str = [str stringByReplacingCharactersInRange:r withString:@""]; NSLog(@"%@",str); A: Why you want that string in that format? do you want to load that return string from JSON inside UIWebView ? if yes then you can simply call loadHtmlString method by appending "<"html>.."<"/html>"
{ "language": "en", "url": "https://stackoverflow.com/questions/7583937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When not to use a gridview I Remember reading an article by Marcus Egger a while back about when to and when not to use a gridview style control. I can't find it now... I have a member on my team who has just found some jquery grids and is determined to use them for everything... I mean everything from lists of data (which I have no problem with) to using it as a primary means for CRUD on single items (which I find lazy and overkill). Does anyone have an opinion on this? Any good articles? Am I being too picky? A: Why don't you use a repeater control, then you have full control of your markup. Or do something like that: <table> foreach(var i in data) { <tr> <td>....etc </td> </tr> } </table> A: I have used jqGrid control for some projects, and find it to be very powerfull and customizable. And there is a great support for all possible questions here on stackoverflow by Oleg. However, it is impossible to give reccomendation for any scenario, as there is no silver bullet, and not even jqGrid is optimal for all scenarios. When you need to have ajax loading and paging, (multiple column) sorting, filtering, inplace editing, enumerated column values, jQuery UI theming - jqGrid is one of the best tools. It supports all that, and different types of data formats, including json and xml. However, sometimes you only need simple web app for administrator to perform CRUD operations on some codebooks, without requirements for specific looks, ajax and all the bells and whistles, and jqGrid is overkill in these cases, especially if autogenerated mvc scaffolding or asp.net dynamic data application does the job well. Or maybe there is no requirement for grid, if there is only a list of something needed, and it can be done in 15 minutes, then you should NOT use any grid control. There are also cases when displayed data can be more user-friendly, i.e. contact information - you will find someone a lot faster if you display large name and/or picture and smaller address, phone etc aside in a unordered list than you will do the same in a grid-styled display of same information (and you cannot put picture as it will make your row height too big). Regarding "lazy" part of your question, I would not agree as there is often more work to make jqGrid working than use some out-of-the-box component. With jqGrid you can implement inplace editing (inside jqGrid), but you can also make completely customized form (not different from one someone expects at edit page) which is loaded into edit dialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Find Last 10 authors for a certain file in Git What is the best (from performance point of view) way to find in Git the last 10 users who changed a certain file ? For example I want to know the last 10 committers (not the last 10 commits) of file foo.txt A: I'd try something like this in *nix systems (w/ bash) git log --format=%an foo.txt |awk ' !x[$0]++' |head -10
{ "language": "en", "url": "https://stackoverflow.com/questions/7583950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Bash: --help feature Is it posseble to have a --help argument with getopts? I'm currently using this to code the help feature: #!/bin/bash PROGNAME=${0##*/} PROGVERSION=1.0 usage() { cat << EO Prog description goes here. Usage: $PROGNAME Options: EO cat <<EO | column -s\& -t -h|--help & show this output -v|--version & show version information EO } SHORTOPTS="hv" LONGOPTS="help,version" ARGS=$(getopt -s bash --options $SHORTOPTS \ --longoptions $LONGOPTS --name $PROGNAME -- "$@" ) eval set -- "$ARGS" while true; do case $1 in -h|--help) usage exit 0 ;; -v|--version) echo "$PROGVERSION" exit 0 ;; --) shift break ;; *) shift break ;; esac shift done A: The bash getopts builtin does not support long option names with the double-dash prefix. It only supports single-character options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to show loading image in telerik grid using asp.net mvc razor Can you please show me a sample code of loading image during data binding using telerik grid asp.net mvc Razor. Thanks in advance. A: Check out the client events for OnDataBinding and OnDataBound. I would show a loading spinner when the OnDataBinding starts, then hide it again when the next method is called. <%= Html.Telerik().Grid(Model) .Name("Grid") .ClientEvents(events => events.OnDataBinding("Grid_onDataBinding") .OnDataBound("Grid_onDataBound")) %> And then, the javascript would be: function Grid_onDataBinding(e) { $("#spinner").show(); } function Grid_onDataBound(e) { $("#spinner").hide(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7583959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add a web view to the split view based application How to add a web view to the root view controller in the split view based application. The following is the code which i am using, [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"rightview"ofType:@"html"]isDirectory:NO]]]; but in the output its not producing any output. A: As it looks like an local html, you can also try doing it with loadHTMLString method like [webView loadHTMLString:htmlString baseURL:nil]; load htmlString with the html content of your bundle html file. A: You may also create a request using: NSURL *url = [NSURL URLWithString:@"link"]; NSURLRequest *req = [NSURLRequest requestWithURL:url]; [[viewController webView] loadRequest:req]; Or something along those lines. You're going to have to tweak things a bit to have everything communicate properly. Just make sure you declare your webView in the App Delegate...
{ "language": "en", "url": "https://stackoverflow.com/questions/7583961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to taken push view object into next view in flex My problem is that when I try to pass an object from the navigator.pushView(view, dataobject), I can't figure out how to access the dataobject from actionscript. I can access {dataobject.property} from MXML easily, but I want to set a variable in the new view to the passed dataobjects property. A: You have the passed object available in 'data' property. You can easily set your new local variable in activateHandler as: var myVar:String = data.myPassedVar;
{ "language": "en", "url": "https://stackoverflow.com/questions/7583969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a trigger on aspnet_membership makes login fail I'm doing some maintance on an older web application where we have 2 DB's. One for the WWW frontend (DotNetNuke) and another for the admin backend. Both of the applications use aspnet_membership for users, and we want to sync logins between the app's. I thought we'd do this with a trigger, but logins starts failing when I add the trigger. USE dnnTicket GO CREATE TRIGGER update_membership ON dbo.aspnet_Membership AFTER UPDATE AS SET NOCOUNT ON IF (trigger_nestlevel() > 1) RETURN --Make sure a similar trigger on the other db don't cause infinite loops. UPDATE ticket4you.dbo.aspnet_Membership SET [Password] = INSERTED.[Password], PasswordFormat = INSERTED.PasswordFormat, PasswordSalt = INSERTED.PasswordSalt, MobilePIN = INSERTED.MobilePIN, Email = INSERTED.Email, LoweredEmail = INSERTED.LoweredEmail, PasswordQuestion = INSERTED.PasswordQuestion, PasswordAnswer = INSERTED.PasswordAnswer , IsApproved = INSERTED.IsApproved , IsLockedOut = INSERTED.IsLockedOut , CreateDate = INSERTED.CreateDate , LastLoginDate = INSERTED.LastLoginDate , LastPasswordChangedDate = INSERTED.LastPasswordChangedDate, LastLockoutDate = INSERTED.LastLockoutDate , FailedPasswordAttemptCount = INSERTED.FailedPasswordAttemptCount , FailedPasswordAttemptWindowStart = INSERTED.FailedPasswordAttemptWindowStart , FailedPasswordAnswerAttemptCount = INSERTED.FailedPasswordAnswerAttemptCount , FailedPasswordAnswerAttemptWindowStart = INSERTED.FailedPasswordAnswerAttemptWindowStart FROM INSERTED WHERE ticket4you.[dbo].aspnet_Membership.UserId = INSERTED.userID SET NOCOUNT OFF GO With this trigger in the DB logins using the dnnTicket db fails. I traced the SQL server activity as best I could and found a very strange difference in the trace from when the query is run in the web server to when I manualy run the same query from SMMS. A: At a glance the trigger looks ok. I would start by checking that both applications have the same configuration for the membership provider, and the same machine keys. Then I would look for any error message that may be getting recorded. The DNN event viewer, (and log4net log file in 6.0) are good sources. If there is nothing I would use sql profiler to look for any messages related to trigger/login process. Also can you describe the failure in more detail? Does the trigger prevent logging in to both systems, or can you log into system A, but then not system B, or you can only ever access one system?
{ "language": "en", "url": "https://stackoverflow.com/questions/7583974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating REST API for existing MVC based website I have a website developed using ASP.NET MVC3. I now want to expose a REST API for others to use which will expose the same features as the website. In the website, once a user has logged in and credentials validated against a DB, the session manages the logged-in state of the user. How would I do the equivalent with the REST API, where many of the methods exposed require the user to be logged in (or at least have valid username and password)? In addition to this, would the best approach for the website be to use the REST API also (presuming the API covers all the functionality required by the site)? How well is ASP.NET MVC3 suited for this - of course taking into account that the site already exists using this framework? A: I wrote up a blog post on how to [Build a RESTful API architecture within an ASP.NET MVC 3 application] years ago and ended up having to let the site go. :( It might be a good start if you want to take on building the REST API into your MVC application. See answer by @tugberk on using WebAPI for a good solution. A: ASP.NET MVC is very well suited for this. Although you can use other approaches (like WCF) I would stick with MVC since you already have a working site that needs to be exposed for other consumers. See also my other answer: Which is better for building an API for my website: MVC or Ado.net data services? A: Note: WCF Web API is now ASP.NET Web API and has changed a lot. The beta version is now available. For more information: Getting Started With ASP.NET Web API - Tutorials, Videos, Samples I would go with WCF Web Api to do that. ASP.NET MVC is also nice and capable of exposing your data but WCF Web Api is more capable if you consider exposing your data to your users. It is easy to use and integrate REST Web APIs to your system. For the authentication, API Key is always the best way for this type of scenario. Here is a good example on how you can implement API Auth with WCF Web API : http://weblogs.asp.net/cibrax/archive/2011/04/15/http-message-channels-in-wcf-web-apis-preview-4.aspx Note: They just released the preview version 5 couple of weeks ago and Message Channels has been changed to Message Handlers as far as I know. But the above article should give you an idea. For security implementations, the below might help as well : wcf Authentication Token Implementation - How to do A: ASP .NET MVC is a great choice for this. I have created several ASP MVC that act as RESTful services as well as websites. To summarize the design paradigm I use, each controller has an action that emits a JSON representation of the requested data. Said data is loaded in a view model on the server, and the built in JSON serializer takes care of the server side, while a jQuery view nicely loads the data back in for my actual webpages to consume. The site itself has index actions on each controller that emit that necessary markup, but not the data. jQuery document.ready methods on the pages load in the data from what is essentially my rest api, but build right into the site. Checkout Nerd Dinner for great sample code. http://nerddinner.com/ Concerning security, I think my experience will differ from yours. ASP MVC integrates very nicely with active directory if your users are all in the same domain and have AD credentials. This is the only method I have used, and with ease, success, and satisfaction. I have had coworkers interact with other APIs that hand out a token upon calling an authorize method. The received token would then be the clients responsibility to store and hand back on each request, but I cannot talk you through implementation details, as I have not person experience on that front. A: I would go with a WCF web service based implementation as follows. * *Wrap all your business logic into a separate dll project named as yourproject.businessservices for example *Create a authentication webservice which will generate a non-repeatable token per user login *This login stores the essential details of the user along with the token in a Cache like MemCache which should have a sliding expiration *If the user has not accessed the cache for let's say an hour, the cache expires and the user is logged out *If the user is using it the cache keeps getting extended. On the wcf services side, *Create APIs to return the token on authentication *All the wcf methods will have this session id which needs to be validated The advantage is that the wcf methods can be exposed to return xml or json format and can also be used as normal web services. [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/MyModule/XML/GetData/{customerSessionId}")] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "/MyModule/JSON/GetData/{customerSessionId}")]
{ "language": "en", "url": "https://stackoverflow.com/questions/7583975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: sprintf with C++ string class I really liked the answer given in sprintf in c++? but it still isn't quite what I'm looking for. I want to create a constant string with placeholders, like const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout"; and then build the string with replaceable parameters like: sprintf(url, LOGIN_URL, protocol, server); //coding sprintf from long ago memory, please ignore but I really want to stay away from C strings if I can help it. The stringbuilder() approach requires me to chunk up my constant strings and assemble them when I want to use them. It's a good approach, but what I want to do is neater. A: Boost format library sounds like what you are looking for, e.g.: #include <iostream> #include <boost/format.hpp> int main() { int x = 5; boost::format formatter("%+5d"); std::cout << formatter % x << std::endl; } Or for your specific example: #include <iostream> #include <string> #include <boost/format.hpp> int main() { const std::string LOGIN_URL = "%s://%s/chronicle/spring/api/logout"; const std::string protocol = "http"; const std::string server = "localhost"; boost::format formatter(LOGIN_URL); std::string url = str(formatter % protocol % server); std::cout << url << std::endl; } A: Take a look at: Boost Format
{ "language": "en", "url": "https://stackoverflow.com/questions/7583976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: BibTex grammar for ANTLR I'm looking for a bibtex grammar in ANTLR to use in a hobby project. I don't want to spend my time for writing ANTLR grammar (this may take some time for me because it will involve a learning curve). So I'd appreciate for any pointers. Note: I've found bibtex grammars for bison and yacc but couldn't find any for antlr. Edit: As Bart pointed the I don't need to parse the preambles and tex in the quoted strings. A: Here's a (very) rudimentary BibTex grammar that emits an AST (contrary to a simple parse tree): grammar BibTex; options { output=AST; ASTLabelType=CommonTree; } tokens { BIBTEXFILE; TYPE; STRING; PREAMBLE; COMMENT; TAG; CONCAT; } //////////////////////////////// Parser rules //////////////////////////////// parse : (entry (Comma? entry)* Comma?)? EOF -> ^(BIBTEXFILE entry*) ; entry : Type Name Comma tags CloseBrace -> ^(TYPE Name tags) | StringType Name Assign QuotedContent CloseBrace -> ^(STRING Name QuotedContent) | PreambleType content CloseBrace -> ^(PREAMBLE content) | CommentType -> ^(COMMENT CommentType) ; tags : (tag (Comma tag)* Comma?)? -> tag* ; tag : Name Assign content -> ^(TAG Name content) ; content : concatable (Concat concatable)* -> ^(CONCAT concatable+) | Number | BracedContent ; concatable : QuotedContent | Name ; //////////////////////////////// Lexer rules //////////////////////////////// Assign : '=' ; Concat : '#' ; Comma : ',' ; CloseBrace : '}' ; QuotedContent : '"' (~('\\' | '{' | '}' | '"') | '\\' . | BracedContent)* '"' ; BracedContent : '{' (~('\\' | '{' | '}') | '\\' . | BracedContent)* '}' ; StringType : '@' ('s'|'S') ('t'|'T') ('r'|'R') ('i'|'I') ('n'|'N') ('g'|'G') SP? '{' ; PreambleType : '@' ('p'|'P') ('r'|'R') ('e'|'E') ('a'|'A') ('m'|'M') ('b'|'B') ('l'|'L') ('e'|'E') SP? '{' ; CommentType : '@' ('c'|'C') ('o'|'O') ('m'|'M') ('m'|'M') ('e'|'E') ('n'|'N') ('t'|'T') SP? BracedContent | '%' ~('\r' | '\n')* ; Type : '@' Letter+ SP? '{' ; Number : Digit+ ; Name : Letter (Letter | Digit | ':' | '-')* ; Spaces : SP {skip();} ; //////////////////////////////// Lexer fragments //////////////////////////////// fragment Letter : 'a'..'z' | 'A'..'Z' ; fragment Digit : '0'..'9' ; fragment SP : (' ' | '\t' | '\r' | '\n' | '\f')+ ; (if you don't want the AST, remove all -> and everything to the right of it and remove both the options{...} and tokens{...} blocks) which can be tested with the following class: import org.antlr.runtime.*; import org.antlr.runtime.tree.*; import org.antlr.stringtemplate.*; public class Main { public static void main(String[] args) throws Exception { // parse the file 'test.bib' BibTexLexer lexer = new BibTexLexer(new ANTLRFileStream("test.bib")); BibTexParser parser = new BibTexParser(new CommonTokenStream(lexer)); // you can use the following tree in your code // see: http://www.antlr.org/api/Java/classorg_1_1antlr_1_1runtime_1_1tree_1_1_common_tree.html CommonTree tree = (CommonTree)parser.parse().getTree(); // print a DOT tree of our AST DOTTreeGenerator gen = new DOTTreeGenerator(); StringTemplate st = gen.toDOT(tree); System.out.println(st); } } and the following example Bib-input (file: test.bib): @PREAMBLE{ "\newcommand{\noopsort}[1]{} " # "\newcommand{\singleletter}[1]{#1} " } @string { me = "Bart Kiers" } @ComMENt{some comments here} % or some comments here @article{mrx05, auTHor = me # "Mr. X", Title = {Something Great}, publisher = "nob" # "ody", YEAR = 2005, x = {{Bib}\TeX}, y = "{Bib}\TeX", z = "{Bib}" # "\TeX", }, @misc{ patashnik-bibtexing, author = "Oren Patashnik", title = "BIBTEXing", year = "1988" } % no comma here @techreport{presstudy2002, author = "Dr. Diessen, van R. J. and Drs. Steenbergen, J. F.", title = "Long {T}erm {P}reservation {S}tudy of the {DNEP} {P}roject", institution = "IBM, National Library of the Netherlands", year = "2002", month = "December", } Run the demo If you now generate a parser & lexer from the grammar: java -cp antlr-3.3.jar org.antlr.Tool BibTex.g and compile all .java source files: javac -cp antlr-3.3.jar *.java and finally run the Main class: *nix/MacOS java -cp .:antlr-3.3.jar Main Windows java -cp .;antlr-3.3.jar Main You'll see some output on your console which corresponds to the following AST: (click the image to enlarge it, generated with graphviz-dev.appspot.com) To emphasize: I did not properly test the grammar! I wrote it a while back and never really used it in any project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7583982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What are things/points to keep in mind while developing a reusable custom control? Windows Form (in C#) - I need to create a custom listbox control for the following requirement: There is a listbox with a long list of items. I want the user to be able to click in the list, and then start typing and have it automatically take them to the matching item (I call this "type ahead"). It needs to be able to do this for as many characters as they type that have a match. This control should be really reusable without much changes. What are things/points I should keep in mind while developing a reusable custom control? (if you provide a good pattern as a sample... will be more helpful) A: In Real World scenario the first decision should be buy vs build. if your application is a serious one and not just for hobby and there is budget for it I would check some of those great controls collections like DevExpress or Telerik for WinForms. You would need a grid as well at some point, eventually, and surely your custom or framework one cannot compete theirs. I refer to those libraries because i believe they already have a listbox with autocomplete as you described in your requirements. check the online demos on their websites...
{ "language": "en", "url": "https://stackoverflow.com/questions/7583984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Question about weird pointer I study C. Digging in some C source code where I found that line. I have read about pointers, but I did not see such an example. char *uppercase (char *s); What that mean ? A: It's a declaration of a function that takes a char pointer and returns a char pointer. A: char *uppercase (char *s); is the same as char* uppercase (char *s); Its return type is char*; it returns a pointer. A: That means that the function takes a pointer to a character and returns a pointer to a character i.e the start of the string. A: uppercase is afunction which returns a char type address ( that is, it can be stored in a char pointer ) as its written as char *uppercase... uppercase() takes a char pointer as argument char *s... therefore its written as char *uppercase( char *s). A: In C the location of the * doesn't matter as long as it is somewhere between the type and name. So char* s is the same as char *s and even char * s. The same applies to functions and their return types, char* uppercase() is equivalent to char *uppercase() and char * uppercase(). White-space is more or less ignored in C so when writing your own code I recommend you pick one format and stick with it. A: The location of the asterisk * can be anywhere: between return type or function name. It is more logical to keep it on the return type's end i.e. char*
{ "language": "en", "url": "https://stackoverflow.com/questions/7583986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing a C# string to VBscript I am using a windows form and am trying to pass a string to a vbscript. The program is asking the user to select a folder, I am trying to take the folder selection and pass it through to the vbscript. C# Code: String SelectedFolder = @"C:\Users"; folderBrowserDialog1.SelectedPath = SelectedFolder; if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) //Set selectedFolder equal to the folder that was choosen SelectedFolder = folderBrowserDialog1.SelectedPath; //Call VBScript System.Diagnostics.Process.Start(".vbsPath"); VBScript: TargetFolder = Request.QueryString("SelectedFolder") Set objShell = CreateObject("Shell.Application") Set objFolder = objShell.Namespace(TargetFolder) Set colItems = objFolder.Items For Each objItem in colItems objItem.InvokeVerbEx("Print") Next Any help would be greatly appreciated. Thank you A: C# side Use the Process.Start overload that accepts command-line parameters: System.Diagnostics.Process.Start("C:\path\to\my.vbs", selectedFolder); If the selectedFolder can contain spaces (which is likely to happen), you should enclose the argument in quotes. System.Diagnostics.Process.Start("C:\path\to\my.vbs", "\"" + selectedFolder + "\""); In fact, if the path can contain quotes and/or trailing backslashes, escaping gets a lot more complicated, see these questions (and others) for details: Escape command line arguments in c#, Passing command-line arguments in C#. VBScript side In your VBScript, read the first command line parameter: targetFolder = WScript.Arguments.Item(0) A: You could write the string to a file which both sets of code can access, or a database. That way it won't matter which programming language you are using at all e.g. could be C# to PHP. Write file: string content = "folder=" + folder; System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\config.txt"); file.WriteLine(content); file.Close(); Read file: System.IO.StreamReader file = new System.IO.StreamReader(@"c:\config.txt"); string content = file.ReadToEnd(); // extract value of folder setting here file.Close(); (Of course the reading would need to be in VB, but would be very similar. Note: code based on: MSDN Example) A: Going back and forth from VBScript to C# is adding a lot of complexity. If possible, it would really be easier to choose one or the other. You can do anything in C# that you can in VBScript. (How you do it is probably different, but you can do all the same tasks - file access, database access, etc.) If it's feasible, you may be better off just working in C#. I'm doing a bit of a guess based on the context of the question here, but I'm trying to answer in my own head why you'd want to do this, and the only thing I can think of is that you don't know how to display a folder dialog box in VBScript, so you're resorting to trying to do it in C#. Is that correct? If so, you can show a folder dialog in VBScript as shown here: http://www.robvanderwoude.com/vbstech_ui_browsefolder.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7583993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mapping to a nested class I am getting the following error when my application runs: System.InvalidOperationException: The type 'ContactModels+Contact' was not mapped. Check that the type has not been explicitly excluded by using the Ignore method or NotMappedAttribute data annotation. Verify that the type was defined as a class, is not primitive, nested or generic, and does not inherit from EntityObject. It is failing when my DBContext class tries to initialize the entities: public class DB : DbContext { public DbSet<ContactModels.Contact> Contacts { get; set; } .... } The Contact model is as follows: public class ContactModels { public class Contact { public int ID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } ... } } Connection string: <add name="DB" connectionString="Data Source=XXXXX;Initial Catalog=XXXX;Trusted_Connection=True" providerName="System.Data.SqlClient" /> I get the error whether the database exists or even if it does not exist and I have it being initialized: protected void Application_Start() { Database.SetInitializer(new CreateDatabaseIfNotExists<Models.DB>()); .... } This is my first time using EF, I've followed a few tutorials but I am using SQL Server 2008 R2 and would prefer to have the database created myself rather than have EF create it for me. Though at this point I'll take either if it works. A: The wrong part is that you are trying to map nested class. It is not supported by entity framework. A: I don't know what is wrong with your code but if you want to start with a database and generate the C# code use the entity framework power tools CTP1 http://blogs.msdn.com/b/adonet/archive/2011/05/18/ef-power-tools-ctp1-released.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7583996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }