text
stringlengths
8
267k
meta
dict
Q: Adobe Flex help with accessing database for mobile web? Thanks in advance for any help. Here is the issue: a client wants his entire equipment inventory accessible by persons navigating to his jquery mobile site. The inventory that exists on the desktop site was, as I understood, built with Flex. Is it possible to access this database for the jquery mobile site? I believe it is. I was then given this information from someone in the know: Database: mlxx.db.xxxxxxx.hostedresource.com login: mxxx Pass: dmxxxxx DSN: mssql_mlxx.dsn Cold Fusion DSN: mssqlcf_mlxx But I have no idea where to go from here. If you could point me in the right direction, I would appreciate it. I haven't done too much server side work which is why my question is probably really comprehensive. Thanks. A: Based on an interpretation of the access data, It sounds like the data is stored in a SQL Server database, and accessed from ColdFusion. In theory you can reuse the ColdFusion services that the Flex/AIR app uses from a HTML/JavaScrript website. Without a full code review, I don't think we'll be able to give you any more specifics than that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Emailing the contents of a Textbox with Outlook I have a simple application written that allows users to pick inventory items with checkboxes. When the items are checked a textbox is populated showing the user's input. I would like to have a class that would take the contents of the textbox and copy it to a new outlook email with the TO address pre-populated with myemail@gmail.com. ASP.Net is foreign to me and I am a very new C# coder SO I have no idea how to do this. Any ideas. I have seen an example online as follows... System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage(); message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate",1 ); message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendusername","SmtpHostUserName" ); message.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendpassword","SmtpHostPassword" ); message.From="from e-mail"; message.To="to e-mail"; message.Subject="Message Subject"; message.Body="Message Body"; System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address"; System.Web.Mail.SmtpMail.Send(message); but I have errors everywhere and think that I'm not implementing this right. Is there a simpler way to do this or just a way I might be able to understand. Thanks to any and all answers. I can only check one but I appreciate them all. A: http://support.microsoft.com/kb/310263 I am guessing you are not using the Outlook object library. If you want to, then the code is right there. The only change you will have to make will be oMsg.Body = TextBox1.text; where TextBox1 has the all the contents that you wanted to send as the message body.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: node.js deployment questions Ive been given the task of localising a facebook app that is built in Node.js that am told uses Nginx for SSL. This is my first foray into the world of Node.js and I have hit a wall in understanding the deployment process involved in pushing an node app to the world wide web (in order to access it through facebook). I have a background in front-end development with javascript, AJAX, html and css. As well as backend PHP, and MYSQL. The task of localising the content I'm not worried about as it is only a matter of swapping out a couple of images. Its my core understanding of how the node.js puzzle fits together where it falls down. Not to metion how Nginx even fits in. I have done alot of searching online and found a lot of beginners tutorials eg http://www.nodebeginner.org/ which is fine but doesn't touch on how node web apps are deployed. I can build the simple hello world example locally but how does this become a "proper www.website". There are also a tonne of other resources out there but they presume a more advanced level of understanding and technical know-how. I just need it in layman's terms. I get that Node.js is server-side javascript so this obviously means it lives on a server right? i currently have a domain, website and hosting plan can i use this server? i access it through a cpanel or ftp. Or do i have to create a new server from scratch? Maybe a virtual server maybe using https://www.virtualbox.org/ what would be this involve? any help you guy may be able to give me is much appreciated. cheers A: So, you probably won't be able to use Node.js on a typical 'hosted server'. These servers are typically running Apache and only support a limited set of languages. There are several providers that offer Node.JS hosting, including the creators: Joyent. Otherwise, you'll need control of the actual server so that you can run the node myapp.js command. For a list of possible providers, see here. Once you get the app running node myapp.js, it should start handling incoming web requests, just like any other web server. Now, if someone is using nginx, they're probably using it as a load-balancer or to serve static content. If you don't understand how or why it's configured this way, you definitely need to talk to the project owners. The rest of the details depend completely on where / how you're hosting and the answers to the nginx questions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561129", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Difference between SOAP webservice and RESTFUL webservice I am new to Java.I know that there are two types of web service * *SOAP Webservice. *RESTful Webservice. can any one please tell me what is the basic difference between both of them.And in which situation the SOAP Webservice is created and in which situation RESTful Webservice is created. Thank You, A: As the first answer allready explains, SOAP Webservices and REST Webservices differ in various points. SOAP: * *you define your interface in a .wsdl file, which describes exactly which input parameters are expected and how the return values will look like *there are tools to generate the .wsdl files out of java class hirarchies. JAXB for example *there are also tools to generate java objects/classes as part of eclipse for example (don't know the name in the moment). *SOAP is very strict. Every request is validatet against the wsdl before processing. A good but not so easy to start with framework for SOAP WS is Apache CXF REST (no hands on experience up to now, feel free to correct and improve ;) ): * *a way to access a webserver or web application to retrieve data from or send to it. *it's only negotiated, how it is accessed. *common is something like this http://server.domain.com/app/type/id=123 to retrieve object of type type with id=123 *very intuitive, but no automatic validation of requests. *... I am sure, there are several other points I missed. But I think it's a usefull start. A: At a very basic level , SOAP is a messaging protocol , REST is a design philosophy , not a protocol. When you base a WebService on a SOAP protocol , you basically comply with SOAP rules of creating a Service Request , posting the request to server , receiving the request at server , processing the request and returning the results as a SOAP message.SOAP does not talk about the exact manner in which client benefits from the service, nor about how to design the client itself ( apart from the message it is posting ), it only tells how a message from client can be sent to service and back. REST is short for REpresentational State Transfer. It does not specify the rules to create a message and post it to server. You can do this by simple HTTP protocol. What REST specifies is the manner in which client and server manage their states so that they become useful to the client -server communication. Here , you are more focussed on designing the states of clients and servers rather than the messages they are exchanging.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: jquery colors, RGB to HSL and back I'm using jquery colors to transform a color from hex to hsl, modify it's hue by adding a number from 0 to 360 to it, then doing a mod 360 to get the new hue value that i'm actually interested in obtaining Problem is I can't figure out how to transform it back to RGB correctly Given the following example (you can test it on jsfiddle here), why does hslAfter have a different value than hsl? From what I can see, I'm just transforming originalColor which is in HEX, to a HSL array of values, then trying to make a string from it, in hslAfter. function testHue() { var originalColor = $.colors($("#originalColor").val()); var hsl = $.colors(originalColor).model('HSL').get(); var hslAfter = $.colors(hsl).toString('hsl'); var hex = $.colors(hsl).toString('hex'); } shouldn't hslAfter have the same values as hsl? (I'm not even mentioning the new hex value here, which of course in turn, should be the same as the original hex color) Am I missing something here (anyway to fix this)? A: You just missed some parameters as per the documentation... $.colors( colorInput, [formatName], [modelName] ) Creates a color based on the arguments. Returns the color object. colorInput A string or array representing a color formatName The name of the format of the color modelName The name of the color model of the color Here's a DEMO, where the HEX output is now the same as the HEX input... http://jsfiddle.net/uEUJq/9/ A: You can use the jscolor.js from jscolor.com. They have many examples. See this jsfiddle for my example. function testHue() { var originalColor = $.colors($("#originalColor").val()); var rgb = $.colors(originalColor).model('RGB').get(); var hsl = $.colors(originalColor).model('HSL').get(); var hslAfter = $.colors(hsl,'array3Normalized', 'HSL').toString('hsl'); var hex = $.colors(hsl,'array3Normalized', 'HSL').toString('hex'); $("#rgbColor").html("<b>rgb: </b>" + rgb); $("#hslColor").html("<b>hsl: </b>" + hsl); $("#hslAfter").html("<b>hsl.toString('hsl'):</b> " + hslAfter); $("#hexColor").html("<b>hsl.toString('hex'): </b>" + hex); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script src="https://code.jquery.com/color/jquery.color-2.1.2.min.js" ></script> <script src="http://http://jscolor.com/release/2.0/jscolor-2.0.4/jscolor.js"></script> <div style="width:500px; margin:5px;"> <div id="rgbColor"><b>rfb: </b></div> <div id="hslColor"><b>hsl: </b></div> <div id="hslAfter"><b>hsl.toString('hsl'):</b></div> <div id="hexColor"><b>hsl.toString('hex'): </b></div> <br/> <input type="text" id="originalColor" class="jscolor {hash:true}" onchange="testHue();" value="ab2567" /> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7561134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to sum all the numbers of one column in python? I need to know how to sum all the numbers of a column in a CSV file. For example. My data looks like this: column count min max sum mean 80 29573061 2 40 855179253 28.92 81 28861459 2 40 802912711 27.82 82 28165830 2 40 778234605 27.63 83 27479902 2 40 754170015 27.44 84 26800815 2 40 729443846 27.22 85 26127825 2 40 701704155 26.86 86 25473985 2 40 641663075 25.19 87 24827383 2 40 621981569 25.05 88 24189811 2 40 602566423 24.91 89 23566656 2 40 579432094 24.59 90 22975910 2 40 553092863 24.07 91 22412345 2 40 492993262 22 92 21864206 2 40 475135290 21.73 93 21377772 2 40 461532152 21.59 94 20968958 2 40 443921856 21.17 95 20593463 2 40 424887468 20.63 96 20329969 2 40 364319592 17.92 97 20157643 2 40 354989240 17.61 98 20104046 2 40 349594631 17.39 99 20103866 2 40 342152213 17.02 100 20103866 2 40 335379448 16.6 #But it's separated by tabs The code I've write so far is: import sys import csv def ErrorCalculator(file): reader = csv.reader(open(file), dialect='excel-tab' ) for row in reader: PxCount = 10**(-float(row[5])/10)*float(row[1]) if __name__ == '__main__': ErrorCalculator(sys.argv[1]) For this particular code I need to sum all the numbers in PxCount and divide by the sum of all numbers in row[1]... I'll be so grateful if tell me how to sum the numbers of a column or if you help me with this code. Also if you can give me a tip to skip the header. A: You could keep a running total using an "augmented assignment" +=: total=0 for row in reader: PxCount = 10**(-float(row[5])/10)*float(row[1]) total+=PxCount To skip the first line (header) in the csv file: with open(file) as f: next(f) # read and throw away first line in f reader = csv.reader(f, dialect='excel-tab' ) A: You can call "reader.next()" right after instantiating the reader to discard the first line. To sum the PxCount, just set sum = 0 before your loop and sum += PxCount after you calculate it for each row. PS You might find the csv.DictReader helpful too. A: Using a DictReader will result in far clearer code. Decimal will give you better precision. Also try to follow python naming conventions and use lowercase names for functions and variables. import decimal def calculate(file): reader = csv.DictReader(open(file), dialect='excel-tab' ) total_count = 0 total_sum = 0 for row in reader: r_count = decimal.Decimal(row['count']) r_sum = decimal.Decimal(row['sum']) r_mean = decimal.Decimal(row['mean']) # not sure if the below formula is actually what you want total_count += 10 ** (-r_mean / 10) * r_count total_sum += r_sum return total_count / total_sum
{ "language": "en", "url": "https://stackoverflow.com/questions/7561136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Notepad++, removing beginning text from each line? I have some junk before each line and the text I want eernnawer love.pdf nawewera man.pdf awettt sup.pdf I would like to do a find and replace to get love.pdf man.pdf sup.pdf How can I do this? Thanks A: * *Ctrl+H to open the search and replace dialog *Activate Regular Expressions as search mode, check Wrap around *Find: .* (.*\.pdf)$ *Replace: \1 *Click Replace All \1 is the text found by the expression in the (first) pair of parentheses. If you would want to remove the trailing text, you could use (.*) .*\.pdf$. A: You can do ctrl+R click the box for allowing RegEx Insert ^[^\s]+\s into the top box Then Find Then Replace Rest A: You could find ^[^ ]* and replace it with nothing (notice the space at the end of the regex). A: In Find and Replace in regular expression mode, find for .* (note, with a space in the end ) and replace with blank.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trust all certificates? X509Certificate I have following code which connects through HTTPS but i am getting following error during connection attempt. WARN/System.err(9456): javax.net.ssl.SSLHandshakeException: org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate signature. How do i get this solved? Trust all certificates? how do i do that? It would be no issue as i only connect to the same server. FY i already implemented EasyX509TrustManager as a class in my app. Thank you in advance. try { HttpClient client = new DefaultHttpClient(); // Setting up parameters SchemeRegistry schemeRegistry = new SchemeRegistry(); // http scheme schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // https scheme schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient httpClient = new DefaultHttpClient(cm, client.getParams()); // Example send HttpsPost request final String url = "https://www.xxxx.com/web/restricted/form/formelement"; // Do the HTTPS Post HttpPost httpPost = new HttpPost(url); ArrayList<NameValuePair> postParameters; postParameters = new ArrayList<NameValuePair>(2); postParameters.add(new BasicNameValuePair("usr_name", username)); postParameters.add(new BasicNameValuePair("usr_password", password)); System.out.println(postParameters); HttpResponse response = httpClient.execute(httpPost); Log.w("Response ","Status line : "+ response.toString()); Hi Peter, Thx for your answer, i followed your advise and the could not validate message is gone. However now i am getting the following message: 09-26 23:47:20.381: WARN/ResponseProcessCookies(10704): Cookie rejected: "BasicClientCookie[version=0,name=ObFormLoginCookie,domain=www.kpn.com,path=/web/restricted/form?formelement=512663,expiry=null]". Illegal path attribute "/web/restricted/form?formelement=512663". Path of origin: "/web/restricted/form/formelement=512663" 09-26 23:47:20.461: WARN/Response(10704): Status line : org.apache.http.message.BasicHttpResponse@407afb98 So something seems to be wrong in the headers? A: Don't trust all certificates, that is a very, very bad idea. Create a keystore with your server's certificate, put in the app's raw assets, and load it into HttpClient's SSLSocketFactory. Then register this factory for https in the SchemeRegistry. A: You need to provide your own TrustManager which trusts all certificates. See this answer: HTTPS and self-signed certificate issue
{ "language": "en", "url": "https://stackoverflow.com/questions/7561142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Launch an application from a windows 7 service We are currently using a report printing application launched by a user-defined function located in a Firebird database which runs as a service. The UDF consists of a simple DLL that launches the reporting application and pass the report ID to be printed through "CreateProcessAsUser" API. In details, we are impersonating a particular windows account in order to have access to the user's printer. The computer on which the software is run is never attended. No one actually open a session on it. So here's how we're doing it: LogonUser( sUser, nil, sPass, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, hToken ); ... LoadUserProfile(hToken, ProfileInfo); ... ImpersonateLoggedOnUser(hToken); ... StartupInfo.lpDesktop := Pchar('Winsta0\Default'); CreateProcessAsUser(hToken,nil, Pchar(sCommand), nil, nil, False, 0, nil, nil, StartupInfo, ProcessInfo); ... UnloadUserProfile(hToken,ProfileInfo.hProfile); Now we have moved to windows 7 platform and obviously, it doesn't work anymore. Is it still possible to impersonate a user account and use his printer from a service under windows vista/7 even if the user is not logged on ? (Otherwise I'd use the user's currently active session ID) Thanks for your help
{ "language": "en", "url": "https://stackoverflow.com/questions/7561146", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Retrieve data from public Google Spreadsheet using gdata library? I'm working in Python and trying to retrieve data from a public Google Spreadsheet (this one) but struggling a bit with the developer documentation. I'd like to avoid client authentication if possible, as it's a public spreadsheet. Here's my current code, with the gdata library: client = gdata.spreadsheet.service.SpreadsheetsService() key = '0Atncguwd4yTedEx3Nzd2aUZyNmVmZGRHY3Nmb3I2ZXc' worksheets_feed = client.GetWorksheetsFeed(key) This fails on line 3 with BadStatusLine. How can I read in the data from the spreadsheet? A: I want to start out by echoing your sentiment that the Documentation is really poor. But, here's what I've been able to figure out so far. Published of Public It is very important that your spreadsheet be "Published to The Web" as opposed to just being "Public on the web." The first is achieved by going to the "File -> Publish to The Web ..." menu item. The second is achieved by clicking the "Share" button in the upper left-hand corner of the spreadsheet. I checked, and your spreadsheet with key = '0Atncguwd4yTedEx3Nzd2aUZyNmVmZGRHY3Nmb3I2ZXc' is only "Public on the web." I made a copy of it to play around with for my example code. My copy has a key = '0Aip8Kl9b7wdidFBzRGpEZkhoUlVPaEg2X0F2YWtwYkE' which you will see in my sample code later. This "Public on the Web" vs. "Published on The Web" nonsense is obviously a point of common confusion. It is actually documented in a red box in the "Visibilities and Projections" sections of the main API documentation. However, it is really hard to read that document. Visibility and Projections As that same document says, there are projections other than "full." And in fact (undocumented), "full" doesn't seem to play nicely with a visibility of "public" which is also important to set when making unauthenticated calls. You can kind of glean from the pydocs that many of the methods on the SpreadsheetsService object can take "visibility" and "projection" parameters. I know only of "public" and "private" visibilities. If you learn of any others, I'd like to know about them too. It seems that "public" is what you should use when making unauthenticated calls. As for Projections, it is even more complicated. I know of "full", "basic", and "values" projections. I only got lucky and found the "values" projection by reading the source code to the excellent Tabletop javascript library. And, guess what, that's the secret missing ingredient to make things work. Working Code Here is some code you can use to query the worksheets from my copy of your spreadsheet. #!/usr/bin/python from gdata.spreadsheet.service import SpreadsheetsService key = '0Aip8Kl9b7wdidFBzRGpEZkhoUlVPaEg2X0F2YWtwYkE' client = SpreadsheetsService() feed = client.GetWorksheetsFeed(key, visibility='public', projection='basic') for sheet in feed.entry: print sheet.title.text ** Tips ** I find it really helpful when working with terribly documented python APIs to use the dir() method in a running python interpreter to find out more about the kind of information I can get from the python objects. In this case, it doesn't help too much because the abstraction above the XML and URL based API is pretty poor. By the way, I'm sure you are going to want to start dealing with the actual data in the spreadsheet, so I'll go ahead and toss in one more pointer. The data for each row organized as a dictionary can be found using GetListFeed(key, sheet_key, visibility='public', projection='values').entry[0].custom
{ "language": "en", "url": "https://stackoverflow.com/questions/7561148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Can't seem to bind two text inputs together I have two form inputs that I need have matching field content. Meaning if I enter text in one field it is the exact same on the other field (they are in separate forms). I thought I could use .bind() to do it but my script would not allow my text to bind to another input. var inp = $("#text1"); if ("onpropertychange" in inp) inp.attachEvent($.proxy(function () { if (event.propertyName == "value") $("div").text(this.value); }, inp)); else inp.addEventListener("input", function () { $("#text2").text(this.value); }, false); <input type="text" id="text1" /> <input type="text" id="text2" /> A: change keyup to change if you don`t want to edit it letter by letter; jsfiddle there var $inputs = $('#input1, #input2'); $inputs.keyup(function(){ $inputs.val($(this).val()); }); A: $("#text1").change({ $("#text2").val(this.val()); }); A: What about this? $('#input01').keyup(function() { value = $(this).val(); $("#input02").val(value); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7561151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: c# DirectoryEntry InvokeSet HomeDirectory and HomeDrive, errors I'm trying to modify the Profiles / Home Directory / Home Drive setting for each AD user in a specified OU, I have below some very basic code that should achieve this feat but is instead throwing the following exception: The requested operation did not satisfy one or more constraints associated with the class of the object. Has anyone had this problem and if so, have a way of fixing it? Thank you. DirectoryEntry Entry = new DirectoryEntry("LDAP://OU=Company,DC=corp,DC=Placeholder,DC=com", null, null, AuthenticationTypes.Secure); DirectorySearcher Searcher = new DirectorySearcher(Entry); Searcher.SearchScope = SearchScope.Subtree; Searcher.PropertiesToLoad.Add("sAMAccountName"); Searcher.Filter = "(&(objectClass=user)(objectCategory=person))"; foreach (SearchResult AdObj in Searcher.FindAll()) { Entry.InvokeSet("HomeDirectory", @"\\winfileserver\" + Convert.ToString(AdObj.Properties["sAMAccountName"][0])); Entry.InvokeSet("HomeDrive", "H"); Entry.CommitChanges(); } catch (Exception ex) { richTextBox1.Text += ex.Message; } A: There's no reason to call InvokeSet, also. This is the correct way to do this: foreach (SearchResult AdObj in Searcher.FindAll()) { DirectoryEntry user = AdObj.GetDirectoryEntry(); user.Properties["HomeDirectory"].Value = @"\\winfileserver\" + Convert.ToString(AdObj.Properties["sAMAccountName"][0]); user.Properties["HomeDrive"].Value = "H"; user.CommitChanges(); } A: It looks like you're using Entry which is pointing to your directory root, not the object you found and that's why the call is failing. I believe you can change your foreach loop to: foreach (SearchResult AdObj in Searcher.FindAll()) { DirectoryEntry user = AdObj.GetDirectoryEntry(); user.InvokeSet("HomeDirectory", @"\\winfileserver\" + Convert.ToString(AdObj.Properties["sAMAccountName"][0])); user.InvokeSet("HomeDrive", "H"); user.CommitChanges(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Facebook / Graph API - How do I find the app id of another application (that I don't own)? I need to find the developer contact info / app profile page for an application I don't own. How do I find the app id for a particular namespace (eg. http://apps.facebook.com/some_app_namespace)? The namespace directs to a 404, so the owner hasn't setup a canvas url or anything. A: It may be assigned to a deactivated or disabled app, locked for copyright or trademark reasons, too long / too short, etc. Short answer is there's probably no way to get it. If you already have a trademark which covers the name you want to use, you could contact Facebook and ask for it to be assigned to you, i'm not 100% sure in which circumstances such a request would succeed, but i recommend here as a starting point: https://www.facebook.com/legal/copyright.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7561154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reading Geolocation from Quicktime Movies with Java (Xuggler)? I need to retrieve geolocation data from QuickTime MOVs recorded on the iPhone/iPad, from a Java application. I am currently investigating the Xuggler media framework; I was hoping I could use Xuggler's IMetaData interface to read out the UserData portion of the Quicktime file. Unfortunately, the only fields retrieved by Xuggler are "major_brand", "minor_version", "compatible_brands", "year", and "year-eng". I know from viewing the video's info in Quicktime that GPS coordinates are embedded. Exiftool also correctly displays the metadata. I need to stick with Java for cross-platform compatibility (I develop on OS X and deploy to Windows and Linux as well). I know that Quicktime for Java is deprecated, so that's not a factor. Any thoughts on how to get the right data out of Xuggler, or how to use a different API? As a last resort, I've considered parsing the output of Exiftool through Java, but that seems unpleasant and hackish at best.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Rendering Kinect Point Cloud with Vertex Buffer Object (VBO) I´m trying to make a dynamic point cloud visualizer. The points are updated every frame with Kinect Sensor. To grab the frames I´m using OpenCV and GLUT to display. The OpenCV API returns a 640 x 480 (float *), for the points xyz position , and a 640 x 480 (int *) for the rgb color data. To get the maximum performance, I´m trying to use Vertex Buffer Object in stream mode instead of a simple Vertex Array. I´m being able to render it with Vertex Array, but nothing is being rendered with my VBO implementation. I tryied a bunch of different orders in the declarations, but i can't find what I'm missing. Can someone try to point me to the right direction? Here is the simpflified code: (I´ve rewrited the wrong version as asked by Christian Rau, so you guys can understand my mistakes) int main() { //Delaring variables, inittiating glut, setting camera and checking the compatibility as http://www.songho.ca/opengl/gl_vbo.html glutDisplayFunc(displayCB); glutIdleFunc(displayCB); ... //Inittiating the vertex buffers if(vboSupported) { glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER_ARB, buffer); glBufferData(GL_ARRAY_BUFFER_ARB, (sizeof(GLfloat) * 640 * 480 * 3), 0, GL_STREAM_DRAW_ARB); glBufferSubData(GL_ARRAY_BUFFER_ARB, 0, (sizeof(float) * 640 * 480 * 3), point_cloud.points_position); glGenBuffers(2, &color_buffer); glBindBuffer(GL_ARRAY_BUFFER_ARB, buffer); glBufferData(GL_ARRAY_BUFFER_ARB, (sizeof(GLbyte) * 640 * 480 * 3), 0, GL_STREAM_DRAW_ARB); glBufferSubData(GL_ARRAY_BUFFER_ARB, 0, (sizeof(char) * 640 * 480 * 3), point_cloud.points_color); } //glutMainLoop(), cleaning memory, ending main .. } //Updating the screen void displayCB() { point_cloud.update(); // clear buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // save the initial ModelView matrix before modifying ModelView matrix glPushMatrix(); glBindBuffer(GL_ARRAY_BUFFER_ARB, color_buffer); glBufferSubData(GL_ARRAY_BUFFER_ARB, 0, (sizeof(char) * 640 * 480 * 3), point_cloud.points_color); glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER_ARB, vertex_buffer); glBufferSubData(GL_ARRAY_BUFFER_ARB, 0, (sizeof(float) * 640 * 480 * 3), point_cloud.points_position); glVertexPointer(3, GL_FLOAT, 0, 0)); // enable vertex arrays glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glDrawArrays(GL_POINT, 0, 640*480); glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays glDisableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER_ARB, 0); glPopMatrix(); glutSwapBuffers(); } A: PS: The program is up and running, but I can't see any improvement in the average performance when compared to the Vertex Array version. Is that alright? THE PROBLEM WAS SOLVED. I´ve done three alterations: 1 - I though that glGenBuffers first parameter was the number that would be associated to the buffer, instead, its the number of buffers that would be allocated. This doesn't matter anyway, because now I'm using a single buffer and adding all the data to it. Didn't solved the problem, but was going in the right way. 2 - There are two ways of being able to use OpenGL VBO functions. First, you can bind the ARB version functions by yourself OR you can add glew.h and use glewInit() after starting an OpenGL context. The second option is a LOT cleaner and I changed my code so I don't use the ARB versions anymore. Still didn't solved the problem. 3 - Christian Rau asked me for glErrors in the code, so, I wrote it after each OpenGL operation in displayCB. After glDrawArrays I got an 0x00500 error, that means there is an invalid enum, so I noticed I was using GL_POINT as parameter to glDrawArrays, instead of GL_POINTS, so silly that makes me want to kill myself. The final code: //EDIT: Added glew.h as a header and I´m not using the ARB version anymore #include <glew.h> int main() { //Declaring variables, initiating glut, setting camera and checking the compatibility as http://www.songho.ca/opengl/gl_vbo.html glutDisplayFunc(displayCB); glutIdleFunc(displayCB); ... //EDIT: IS VERY IMPORTANT TO ADD IT AS SOON AS YOU START AN OPENGL CONTEXT. initGlew(); //Inittiating the vertex buffers if(vboSupported) { //EDIT: I was using two buffers, one for color and another for the vertex. I changed the code so I use a single buffer now. //EDIT: Notice that I'm not using the ARB version of the functions anymore. glGenBuffers(1, &buffer); glBindBuffer(GL_ARRAY_BUFFER_ARB, buffer); glBufferData(GL_ARRAY_BUFFER_ARB, (sizeof(GLfloat) * 640 * 480 * 3) + (sizeof(GLbyte) * 640 * 480 * 3), 0, GL_STREAM_DRAW_ARB); } //glutMainLoop(), cleaning memory, ending main .. } //Updating the screen void displayCB() { point_cloud.update(); // clear buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // save the initial ModelView matrix before modifying ModelView matrix glPushMatrix(); glBindBuffer(GL_ARRAY_BUFFER_ARB, buffer); glBufferSubData(GL_ARRAY_BUFFER_ARB, 0, (sizeof(char) * 640 * 480 * 3), point_cloud.points_color); glBufferSubData(GL_ARRAY_BUFFER_ARB, (sizeof(char) * 640 * 480 * 3), (sizeof(float) * 640 * 480 * 3), point_cloud.points_position); // enable vertex arrays glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(3, GL_UNSIGNED_BYTE, 0, 0); //EDIT: Added the right offset at the vertex pointer position glVertexPointer(3, GL_FLOAT, 0, (void*)(sizeof(char) * 640 * 480 * 3)); //EDIT: Was using GL_POINT instead of GL_POINTS glDrawArrays(GL_POINTS, 0, 640*480); glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays glDisableClientState(GL_COLOR_ARRAY); glBindBuffer(GL_ARRAY_BUFFER_ARB, 0); glPopMatrix(); glutSwapBuffers(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Hibernate serverside or on each instance of a Swing application? I would like to know what is the best desing for an existing heavy swing application. This application need a database access (new) and I am using hibernate for that. This application is running on many computers and need few things : * *ability to 'lock' a record for modifications (an other instance will not be able to edit the records) but I have to find a way to protect from record being locked beacause of a crash or something. *ability to be notified from database updates events (I am using posrgresql, maybe it can helps) So my question : where do I have to instanciate hibernate ? on each application instance ? or an unique instance 'server side' and had to code a protocol mecanism (RMI ? EHCache distribuated ? ...) The problem with the server model, is that I will have to code mecanisms to detect application shutdown / crash. Thanks. A: To answer your overall question, we first need to explore the question of how heavy your database interaction is. In general, in a Java EE context, the recommended course of action is to keep all your database interaction on the server and design a useful, usable remote interface which you provide access to via EJB. However, this course of action assumes that it is less expensive to transmit a high-level objective from the client to the server and do all the processing there, in other words, a service API rather than a data API. It's often useful to examine the recommended patterns of use in Java EE, because there's often a hidden hint in there. Using EJBs, for example, allow you to treat the application server as the gateway to all modification of your data. This gives you a great deal more control and lets you offload a lot of the work you would ordinarily have to do yourself, such as managing transactions, onto the container. It also alleviates the need for fancy locking strategies—for the most part. From a concurrency perspective, there are pros and cons to each approach. Server-side Pros * *No need to worry about cache synchronization with clients *Simplified transaction handling *Lots of existing infrastructure (EJB) *No direct access to the database from a malicious client (no need for clients to have database passwords, for example) Client-side Pros * *No detached objects or data-transfer object woes *Simplified programming model *No need for a fancy Java EE application server PostgreSQL has support for explicit row locks by issuing a SELECT FOR UPDATE against the rows you want to lock. This prevents other processes from issuing UPDATEs or DELETEs against the rows you have locked. However, this is a definite code smell. PostgreSQL has extremely powerful algorithms for handling concurrency. In general, I find people wanting to handle locks in the database explicitly usually do not understand how databases handle concurrency and it almost always leads to pain. So some questions you should ask yourself before proceeding with an application design that requires explicit locks are: why am I locking the data? Why am I worried about other processes accessing these rows at the same time? Is it really bad for other processes to update these rows at the same time? Often I find that this is an indication that there should be another entity and rows should be owned by particular users instead. Another important point is that locks in PostgreSQL are only live as long as the transaction is open. Long-running transactions are a very bad idea, because they increase the possibility of deadlock. If PostgreSQL detects deadlock, it will pick one of the connections and kill it, and odds are very low it will kill the one you want. Hibernate also abhors long-running transactions. Your temptation to move access to the database to a Swing client, odds are very good you are planning on allowing extremely long-running transactions, either explicitly with PostgreSQL directly or implicitly by holding Hibernate Sessions or EntityManagers open for long periods of time. These are both really bad ideas that introduce a lot of memory overhead and room for concurrency problems. Additionally, I would be outright shocked if Hibernate cooperated nicely with manually acquired locks. Once Hibernate is involved with your database, I would consider it a very bad idea to expect to retain any amount of control over aspects of the database having to do with transactions. Hibernate really expects to own the process and is, in a sense, hijacking it for its own purposes; mucking around with the same connection directly will lead to pain sooner or later. There are two pieces of good news to be salvaged from all of this bad news: * *PostgreSQL has a neat notification facility that can be used to synchronize between different processes. I have no idea how one would go about using this with Hibernate though. *PostgreSQL will not retain a lock longer than a transaction lasts. If your connection acquires a lock and then disconnects, the lock is forfeited. You don't need to worry about that. (Even if this weren't the case, PostgreSQL will notice deadlock and murder one of the transactions to allow work to proceed). In the event you decide to allow distributed clients to directly access the database with long-running transactions, you may want to investigate using Terracotta for distributed 2nd-level caching. This is a way to keep a distributed set of processes to share a cache, effectively. In Conclusion It sounds from the way the question is worded as though you want a lot of explicit control over the database while also using Hibernate. This indicates to me that there is a confusion of needs. Hibernate is a database abstraction layer; it is about hiding the kinds of details you are actively interested in. Moreover, PostgreSQL itself is also an abstraction, particularly over concurrency concerns. I think you would probably find it easier to implement the design you seem to be requiring over a flat file with a custom server to support it, which is a good indication that either your needs are very specialized and poorly matched to the candidate technologies, or you misunderstand the candidate technologies. I see a lot more misunderstanding than special needs (though it happens). Relational databases are not just a persistence mechanism: they are also an integration point that manages data integrity. ACID compliance implies that the database will itself ensure that data is not left in a corrupted state by multiple processes writing the same things at the same time. Moreover, because multiple processes can be changing the data, you must write your software aware that the data it has just fetched from the database is already potentially out-of-date. This is why Hibernate performs all of its SELECTs inside a transaction: it's the only way to get a coherent snapshot of a system that is currently undergoing change. Writing your application with explicit locking implies that you and your application think of the database as being merely some kind of storage which you can use as a synchronization point, by preventing or allowing other processes to make changes. I assure you that locks in a relational database context are the enemy of both performance and frequently of data integrity as well. Additionally, they usually don't work as you expect or need; for example, even PostgreSQL's highest row lock level will not prevent another process from examining the current value the row has, and your changes to that value will not take effect until the transaction is committed. This is very different from the way locks work in a traditional multi-threaded process with ordinary variables and ordinary locks. Usually if you think you need locks in a relational database, you either don't, or you need to rethink your application's design so as not to need them, or perhaps you simply need to rethink your database design to eliminate the need. In any case, the scenario you describe is a very poor fit for distributed computing of any kind, and an especially poor fit for Hibernate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: passing array between two C# Windows Form application I have two C# application and I want interactive them by calling one program giveMeDataArray(xIndex,yIndex) and then second program send response to first program by sending an array to it please help me on this issue.... thnx EDIT: I have a program that generate numbers and a program show that. when user scroll in presentation program, that request for data. this data provided by second program and type of data is array i just want have this array in first application A: You should reference one app to another with dll.if you don't know how to add dll you can visit Adding a dll file to a C# project
{ "language": "en", "url": "https://stackoverflow.com/questions/7561177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I properly encode a mailto link? I am generating some HTML and I want to generate an XSS- and database-content-safe mailto link. What is the proper encoding to use here? How's this? myLiteral.Text = string.Format( "mailto:{0}?Content-Type=text/html&amp;Subject={1}&amp;body={2}", HttpUtility.UrlEncode(email_address), HttpUtility.UrlEncode(subject), HttpUtility.UrlEncode(body_message)); Should I use UrlEncode here? HtmlEncode? Do what I did, then HtmlEncode the entirety? I'm writing HTML of a URL, so I'm a little unclear... @Quentin, is this what you're describing? (Changed &amp;s to & since I'm about to HtmlEncode...) myLiteral.Text = HttpUtility.HtmlEncode(HttpUtility.UrlEncode( string.Format( "mailto:{0}?Content-Type=text/html&Subject={1}&body={2}", email_address, subject, body_message))); A: You are putting some content in a URL, then representing that URL in HTML. So URLEncode it then HTMLEncode what you get from URLEncode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: More than 100 connections to sql server 2008 in "sleeping" status I have a big trouble here, well at my server. I have an ASP .net web (framework 4.x) running on my server, all the transactions/select/update/insert are made with ADO.NET. The problem is that after being using for a while (a couple of updates/selects/inserts) sometimes I got more than 100 connections on "sleeping" status when check for the connections on sql server with this query: SELECT spid, a.status, hostname, program_name, cmd, cpu, physical_io, blocked, b.name, loginame FROM master.dbo.sysprocesses a INNER JOIN master.dbo.sysdatabases b ON a.dbid = b.dbid where program_name like '%TMS%' ORDER BY spid I've been checking my code and closing every time I make a connection, I'm gonna test the new class, but I'm afraid the problem doesn't be fixed. It suppose that the connection pooling, keep the connections to re-use them, but until I see don't re-use them always. Any idea besides check for close all the connections open after use them? SOLVED(now I have just one and beautiful connection on "sleeping" status): Besides the anwser of David Stratton, I would like to share this link that help explain really well how the connection pool it works: http://dinesql.blogspot.com/2010/07/sql-server-sleeping-status-and.html Just to be short, you need to close every connection (sql connection objects) in order that the connection pool can re-use the connection and use the same connectinos string, to ensure this is highly recommended use one of the webConfig. Be careful with dataReaders you should close its connection to (that was what make me mad for while). A: It sounds like it is connection pooling. From here: http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx A connection pool is created for each unique connection string. When a pool is created, multiple connection objects are created and added to the pool so that the minimum pool size requirement is satisfied. Connections are added to the pool as needed, up to the maximum pool size specified (100 is the default). Connections are released back into the pool when they are closed or disposed. To ensure you're not creating unnecessary pools, ensure that the exact same connection string is used each time you connect - store it in the .config file. You can also reduce the Maximum Pool Size if you like. Actually, I'd recommend just reading the entire article linked to above. It talks about clearing the pools, and gives you the best practices for using pooling properly. Edit - added the next day The pools on your server are there because of how Connection pooling works. Per the documentation linked to above: The connection pooler removes a connection from the pool after it has been idle for a long time, or if the pooler detects that the connection with the server has been severed. Note that a severed connection can be detected only after attempting to communicate with the server. If a connection is found that is no longer connected to the server, it is marked as invalid. Invalid connections are removed from the connection pool only when they are closed or reclaimed. This means that the server itself will clean up those pools eventually, if they remain unused. If the are NOT cleaned up,l that means that the server believes that the connections are still in use, and is hanging on to them to increase your performance. In other words, I wouldn't worry about it unless you see a problem. Connection Pooling is happening exactly as it should be. If you REALLY want to clear the pools, again, per the documentation: Clearing the Pool ADO.NET 2.0 introduced two new methods to clear the pool: ClearAllPools and ClearPool. ClearAllPools clears the connection pools for a given provider, and ClearPool clears the connection pool that is associated with a specific connection. If there are connections being used at the time of the call, they are marked appropriately. When they are closed, they are discarded instead of being returned to the pool. However, if you want to adjust pooling, the Connection String can be modified. See this page, and search for the word "pool": http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx Or you can enlist a DBA to assist and set pooling at the server-level. That's off-topic here, but ServerFault.com might have people to assist there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: EditText display wrong text i'm stuck whit a very strange problem. I have an editText in a dialog. If I open the dialog one time (tapping on a element of a ListView) and do some stuff all ok. If I open the dialog the next time (tapping on a different element of a ListView) the editText display the same value of the first time. toast(profilesList.get(toEdit).get(NAME).toString()); //toast say Bob et_profileName.setText(profilesList.get(toEdit).get(NAME).toString()); //I see Alice Another strange thing: if I rotate the display the text change in "BobAlice". If I close the dialog, and then I reopen it, all work well and the dialog display the right Strings. Any suggestions? EDIT: et_profileName is in a dialog that opens when you click an item in the ListView. More code: protected Dialog onCreateDialog(int id) { dialog = new Dialog(this); ... et_profileName= (EditText)dialog.findViewById(R.id.et_profileName); ... } Here is when I call the dialog: showDialog(DIALOG_EDIT_PROFILE); toast(profilesList.get(toEdit).get(NAME).toString()); et_profileName.setText(profilesList.get(toEdit).get(NAME).toString()); Also don't work if I put et_profileName= (EditText)dialog.findViewById(R.id.et_profileName); before the et_profileName.setText(...) A: SOLVED: Should override the onPrepareDialog(int id, Dialog dialog) to prepare a managed dialog before it is being shown. Added this code, it works: @Override protected void onPrepareDialog(int id, Dialog dialog){ et_profileName= (EditText)dialog.findViewById(R.id.et_profileName); if(id==DIALOG_EDIT_PROFILE){ et_profileName.setText(profilesList.get(toEdit).get(NAME).toString()); } } Thanks you all!
{ "language": "en", "url": "https://stackoverflow.com/questions/7561190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting ArrayList or Array to String Array I'm working on a project where i need to convert either an ArrayList or and Array to an String array. I need each word/string to convert to seperate strings. Something like this: public ArrayList<String> arrList2 = new ArrayList<String>(); and then convert it and past into public String arrList4 [] = new String [250]; Hope this is detaild enough so you get what i want. A: ArrayList<String> al = new ArrayList<String>(); al.add("C"); al.add("java2s.com"); al.add("D"); al.add("F"); al.add(1, "java2s.com"); String[] strings = al.toArray(new String[al.size()]); System.out.println(Arrays.toString(strings)); Here is an interesting link: http://www.google.be/search?gcx=w&sourceid=chrome&ie=UTF-8&q=ArrayList+to+array A: String []strArray = new String[250]; arrList2.toArray(strArray);
{ "language": "en", "url": "https://stackoverflow.com/questions/7561193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Thread.Sleep blocking parallel execution of tasks I'm calling a worker method that calls to the database that then iterates and yield returns values for parallel processing. To prevent it from hammering the database, I have a Thread.Sleep in there to pause the execution to the DB. However, this appears to be blocking executions that are still occurring in the Parallel.ForEach. What is the best way to achieve this to prevent blocking? private void ProcessWorkItems() { _cancellation = new CancellationTokenSource(); _cancellation.Token.Register(() => WorkItemRepository.ResetAbandonedWorkItems()); Task.Factory.StartNew(() => Parallel.ForEach(GetWorkItems().AsParallel().WithDegreeOfParallelism(10), workItem => { var x = ItemFactory(workItem); x.doWork(); }), _cancellation.Token); } private IEnumerable<IAnalysisServiceWorkItem> GetWorkItems() { while (!_cancellation.IsCancellationRequested) { var workItems = WorkItemRepository.GetItemList(); //database call workItems.ForEach(item => { item.QueueWorkItem(WorkItemRepository); }); foreach (var item in workItems) { yield return item; } if (workItems.Count == 0) { Thread.Sleep(30000); //sleep this thread for 30 seconds if no work items. } } yield break; } Edit: I changed it to include the answer and it's still not working as I'm expecting. I added the .AsParallel().WithDegreeOfParallelism(10) to the GetWorkItems() call. Are my expectations incorrect when I think that Parallel should continue to execute even though the base thread is sleeping? Example: I have 15 items, it iterates and grabs 10 items and starts them. As each one finishes, it asks for another one from GetWorkItems until it tries to ask for a 16th item. At that point it should stop trying to grab more items but should continue processing items 11-15 until those are complete. Is that how parallel should be working? Because it's not currently doing that. What it's currently doing is when it completes 6, it locks the subsequent 10 still being run in the Parallel.ForEach. A: I would suggest that you create a BlockingCollection (a queue) of work items, and a timer that calls the database every 30 seconds to populate it. Something like: BlockingCollection<WorkItem> WorkItems = new BlockingCollection<WorkItem>(); And on initialization: System.Threading.Timer WorkItemTimer = new Timer((s) => { var items = WorkItemRepository.GetItemList(); //database call foreach (var item in items) { WorkItems.Add(item); } }, null, 30000, 30000); That will query the database for items every 30 seconds. For scheduling the work items to be processed, you have a number of different solutions. The closest to what you have would be this: WorkItem item; while (WorkItems.TryTake(out item, Timeout.Infinite, _cancellation)) { Task.Factory.StartNew((s) => { var myItem = (WorkItem)s; // process here }, item); } That eliminates blocking in any of the threads, and lets the TPL decide how best to allocate the parallel tasks. EDIT: Actually, closer to what you have is: foreach (var item in WorkItems.GetConsumingEnumerable(_cancellation)) { // start task to process item } You might be able to use: Parallel.Foreach(WorkItems.GetConsumingEnumerable(_cancellation).AsParallel ... I don't know if that will work or how well. Might be worth a try . . . END OF EDIT In general, what I'm suggesting is that you treat this as a producer/consumer application, with the producer being the thread that queries the database periodically for new items. My example queries the database once every N (30 in this case) seconds, which will work well if, on average, you can empty your work queue every 30 seconds. That will give an average latency of less than a minute from the time an item is posted to the database until you have the results. You can reduce the polling frequency (and thus the latency), but that will cause more database traffic. You can get fancier with it, too. For example, if you poll the database after 30 seconds and you get a huge number of items, then it's likely that you'll be getting more soon, and you'll want to poll again in 15 seconds (or less). Conversely, if you poll the database after 30 seconds and get nothing, then you can probably wait longer before you poll again. You can set up that kind of adaptive polling using a one-shot timer. That is, you specify -1 for the last parameter when you create the timer, which causes it to fire only once. Your timer callback figures out how long to wait before the next poll and calls Timer.Change to initialize the timer with the new value. A: You can use the .WithDegreeOfParallelism() extension method to force PLinq to run the tasks simultaneously. There's a good example in the Call Blocking or I/O Intensive section in th C# Threading Handbook A: You may be falling foul of the Partitioner. Because you are passing an IEnumerable, Parallel.ForEach will use a Chunk Partitioner which can try to grab a few elements at a time from the enumeration in a chunk. But your IEnumerable.MoveNext can sleep, which will upset things. You could write your own Partitioner that returns one element at a time, but in any case, I think a producer/consumer approach such as Jim Mischel's suggestion will work better. A: What are you trying to accomplish with the sleeping? From what I can tell, you're trying to avoid pounding database calls. I don't know of a better way to do that, but it seems like ideally your GetItemList call would be blocking until data was available to process.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: String vs. Enum for checking type of object in Python Say I have an object called Tag, and I have three types of tags as indicated by an instance variable in the following way, class Tag(object): def __init__(self, name, type): self.name = name self.type = type t1 = Tag("blue", "cold") t2 = Tag("red", "warm") t3 = Tag("black", "hot") Let's say I only allowed three types: cold, warm, and hot. Would it be better to go checking if it is one of these types like this? if t1.type == "cold": # do something elif t1.type == "warm": # do something else else t1.type == "hot": # do something even elser Or should I create an enum-like object like the one from this question, class Type: COLD=1 WARM=2 HOT=3 And instead create Tags like this? t1 = Tag("blue", Type.COLD) The reason I ask this question is because I heard a lot of processing power goes into comparing strings, and even though these are short 3, 4 letter long words, it is possible that I'd be making tens of thousands of comparisons of these types. Do you think its worth it to go creating enum objects for determining the type of an object as in the example I've shown above? Or is there a better way to do what I'm attempting to do? A: It's possible the performance difference may not be significant enough for you to worry about it. You should make a simple test if you're concerned about performance. Use Python's timeit module to test the performance of both cases. A: I wouldn't be worried about the performance of this unless profiling shows that it indeed is a problem. If you're using an IDE, the enum approach has the benefit of typo-checking. A: I would go with a combination approach -- have the 'enum' be part of the Tag class, accept a string for initialization, and then convert it. Also, instead of using a bunch of if/else branches, you can use a dict to create a dispatch table. class Tag(object): COLD = 0 WARM = 1 HOT = 2 def __init__(self, name, temp): if temp.upper() not in ('COLD', 'WARM', 'HOT'): raise ValueError("Invalid temp: %r" % temp) self.temp = getattr(self, temp.upper()) self.name = name def process(self): func = self.temp_dispatch[self.temp] func(self) # NOTE: have to pass 'self' explicitly def cold(self): print('brrr') def warm(self): print('ahhh') def hot(self): print('ouch!') temp_dispatch = {COLD:cold, WARM:warm, HOT:hot} tag = Tag('testing', 'Cold') tag.process() A: In python, it's frequently advantageous to use a dictionary for dispatch rather than a tower of if/elif/else. So: class Tag(object): def __init__(self, name, type): self.name = name self.type = type self.dispatch = {"cold":Tag.process_cold, "warm":Tag.process_warm, "hot":Tag.process_hot} def process(self): self.dispatch[type](self) def process_cold(self): # do something def process_warm(self): # do something else def process_hot(self): # do something even elser And a small additional bit of code can build the dispatch table automatically: def dispatchTable( klass, prefix ): """ Given a class and a method prefix string, collect all methods in the class that start with the prefix, and return a dict mapping from the part of the method name after the prefix to the method itself. e.g. you have a class Machine with methods opcode_foo, opcode_bar. create_dispatch_table( Machine, "opcode_" ) yields a dict { "foo": Machine.opcode_foo, "bar": Machine.opcode_bar } """ dispatch = {} for name, fun in inspect.getmembers( klass, inspect.ismethod ): if name.startswith(prefix): # print "found %s.%s"%(k.__name__,name) dispatch[ name.split(prefix)[1] ] = fun return dispatch
{ "language": "en", "url": "https://stackoverflow.com/questions/7561199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Green screen / chroma key iOS I am trying to do green screen subtraction in real time on iOS. I have included openCV in my project and I can get the raw data from the camera using this tutorial: http://www.benjaminloulier.com/articles/ios4-and-direct-access-to-the-camera Then after I convert from CGImageRef to IplImage. What I am stuck at is, using openCV, how can I do this green screen subtraction? Or is there a simpler image library I can use for iOS to achieve this? Thanks A: EDIT: Link broken. Looks like the company may have folded. Here is a Chroma Key package that (supposedly) supports iOS: https://tastyblowfish.com/chromagic/index.html It is a commercial package - I'm not associated with them. A: For those looking for an answer to this, I ended up using openCV. It's works great (for an iPhone app). Take a look at the source code in the description of this video: http://www.youtube.com/watch?v=aE0F4F5WIuI
{ "language": "en", "url": "https://stackoverflow.com/questions/7561203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: what does means Binding with no source property in silverlight? I am little new and I have a doubt in relation with databinding. To bind something I usually use {binding propertyName,...} but in some post/blogs I can see the kind of code like ItemsSource="{Binding}". Why not use ItemsSource="{Binding YourCollection}"? What are the differences? Thank you! :=) A: Some times the current DataContext is the collection that supplies the items for some ItemsControl like a ListBox. In which case there is no property to bind to, the source object as a whole is the value to be assigned to the ItemsSource property. That's what ItemsSource="{Binding}" means. When no property path is specified the binding's Source object is passed in. Whereas ItemsSource="{Binding YourCollection}" means find the property called YourCollection on the Source object and pass its value to ItemsSource.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using createElement('img') to get .jpeg instead of .png I would like to use createElement("img') to create .jpeg extension instead of .png According to Flanagan's book JavaScript: The Definitive Guide: Activate Your Web Pages By David Flanagan, For jpeg image type, the second argument should be a number between 0 and 1 specifying the image quality level. I am not sure what the syntax for the code would be. Is it something like this? createElement("img",1) A: The book is talking about html5's canvas tag and specifically its .toDataURL method. I think you want to do something like: var img = document.createElement('img'); img.src = 'myImageSource.jpg'; In this case, it's up to the web server to deliver the image and its type information to the web browser. A: The book that you're referring to seems to be talking about the toDataURL method of the canvas API (see this), which accepts type and quality arguments. You can use document.createElement without worrying about MIME types or quality. A: you can use setAttrebure() Method or built-in 'src' property. var img = document.createElement('img'); img.setAttibute('src', 'img.jpg'); document.body.appendChild(img); or use var img = document.createElement('img'); img.src = "img.jpg"; document.body.appendChild(img);
{ "language": "en", "url": "https://stackoverflow.com/questions/7561215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Excel Data to TreeView C# I am looking to create a windows form that contains a tree view of data that I have in excel. I have the windows form I am just trying to figure out how to export the excel data into that data tree. Any links? A: If you import Microsoft.Office.Interop.Excel assembly you can access Excel files and use every property and method easily. Example: using Excel = Microsoft.Office.Interop.Excel; public static object GetCellValue( string filename, string sheet, int row, int column) { Excel.Application excel = new Excel.Application(); Excel.Workbook wb = excel.Open(filename); Excel.Worksheet sh = wb.Sheets[sheet]; object ret = sh.Cells[row, column].Value2; wb.Close(); excel.Quit(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: "undefined symbol: _PyObject_NextNotImplemented" error when loading psycopg2 module environment: Ubuntu 10.04 LTS build Python 2.7.2 with ./configure --with-zlib --enable-unicode=ucs4 postgresql-9.0 wsgi Django 1.3 virtualenv apache I am trying to build Ubuntu Django App Server. The installation completed with no error message. The exact installation method was successful with Ubuntu 11.04. However, when installation is completed on Ubuntu 10.04 and try to load psycopg2 from Django, I got the following error (I did not get this error on 11.04): File "/home/nreeves/venv/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 24, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) ImproperlyConfigured: Error loading psycopg2 module: /home/nreeves/venv/lib/python2.7/site-packages/psycopg2/_psycopg.so: undefined symbol: _PyObject_NextNotImplemented My guess is that some linkage to library is incorrect... but I have no idea where to start... I have a following output - not sure if this will help you help me... $ ldd /home/nreeves/venv/lib/python2.7/site-packages/psycopg2/_psycopg.so linux-gate.so.1 => (0xb77da000) libpq.so.5 => /usr/lib/libpq.so.5 (0xb7788000) libpthread.so.0 => /lib/tls/i686/cmov/libpthread.so.0 (0xb776f000) libc.so.6 => /lib/tls/i686/cmov/libc.so.6 (0xb7614000) libssl.so.0.9.8 => /lib/i686/cmov/libssl.so.0.9.8 (0xb75cc000) libcrypto.so.0.9.8 => /lib/i686/cmov/libcrypto.so.0.9.8 (0xb747a000) libkrb5.so.3 => /usr/lib/libkrb5.so.3 (0xb73c9000) libcom_err.so.2 => /lib/libcom_err.so.2 (0xb73c5000) libgssapi_krb5.so.2 => /usr/lib/libgssapi_krb5.so.2 (0xb7395000) libldap_r-2.4.so.2 => /usr/lib/libldap_r-2.4.so.2 (0xb734e000) /lib/ld-linux.so.2 (0xb77db000) libdl.so.2 => /lib/tls/i686/cmov/libdl.so.2 (0xb734a000) libz.so.1 => /lib/libz.so.1 (0xb7335000) libk5crypto.so.3 => /usr/lib/libk5crypto.so.3 (0xb7311000) libkrb5support.so.0 => /usr/lib/libkrb5support.so.0 (0xb7308000) libkeyutils.so.1 => /lib/libkeyutils.so.1 (0xb7304000) libresolv.so.2 => /lib/tls/i686/cmov/libresolv.so.2 (0xb72f0000) liblber-2.4.so.2 => /usr/lib/liblber-2.4.so.2 (0xb72e3000) libsasl2.so.2 => /usr/lib/libsasl2.so.2 (0xb72cb000) libgnutls.so.26 => /usr/lib/libgnutls.so.26 (0xb722f000) libtasn1.so.3 => /usr/lib/libtasn1.so.3 (0xb721e000) libgcrypt.so.11 => /lib/libgcrypt.so.11 (0xb71ab000) libgpg-error.so.0 => /lib/libgpg-error.so.0 (0xb71a6000) And the following command outputs: $ ls -l /usr/lib/libpq* -rw-r--r-- 1 root root 224904 2011-09-26 06:33 /usr/lib/libpq.a lrwxrwxrwx 1 root root 12 2011-09-26 10:51 /usr/lib/libpq.so -> libpq.so.5.4 lrwxrwxrwx 1 root root 12 2011-09-26 10:51 /usr/lib/libpq.so.5 -> libpq.so.5.4 -rw-r--r-- 1 root root 150976 2011-09-26 06:33 /usr/lib/libpq.so.5.4 To me it appears that all is correct. Any advice would be appreciated. A: You mention 'wsgi' as a tag. If that means you are using Apache/mod_wsgi then be aware that mod_wsgi must be compiled against the same Python version/installation and you need to verify that mod_wsgi is picking up the same libpython.so at run time as it is mod_wsgi that dictates the Python library linked in. A: [SOLVED] Thanks to both patrys and Graham Dumpleton, it was clear that my custom build Python 2.7 and wsgi installation was wrong and critical library linking was absent. Now the problem is resolved by following the instruction below resolved this issue. Thanks to all smart and kind people who is sharing information. * *Reinstall Python: https://askubuntu.com/questions/17841/will-python2-7-be-available-for-lucid-in-future *Then uninstall WSGI: sudo apt-get purge libapache2-mod-wsgi *Install WSGI: http://grok.zope.org/documentation/tutorial/installing-and-setting-up-grok-under-mod-wsgi/installing-and-configuring-mod-wsgi A: This particular symbol comes from libpython*.*.so.1.0 (replace wildcards with your version of python). You should see it when listing dynamic symbols using nm: $ ldd /usr/lib64/python2.7/site-packages/psycopg2/_psycopg.so | grep libpython libpython2.7.so.1.0 => /usr/lib64/libpython2.7.so.1.0 (0x00007fe14f0c6000) $ nm -D /usr/lib64/libpython2.7.so.1.0 | grep PyObject_NextNotImplemented 000000000008a880 T _PyObject_NextNotImplemented Are you using a custom build? It seems your version of _psycopg.so is not linked to libpython at all.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: JavaScript get original caller object Here is a sample situation: <smth onmouseover="test('hello')"> ... function test(pLabel) { var sender = ?; var evt = ? || window.event; } In the function test() - how do I get the object that I hovered the mouse on and the mouse event? I've tried playing with the callee property but didn't get it to work in IE. A: It's best not to define your event handlers in the HTML itself. Try this: <div id="something">...</div> ... document.getElementById('something').onmouseover = function() { // use `this` to reference the <div> alert(this.id); // alerts "something" };
{ "language": "en", "url": "https://stackoverflow.com/questions/7561224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to test the speed of a query without downloading the actual data? I have a multiple result-set store procedure on a remote Sql Server 2008. Currently, the procedure is returning a rather large result set that is to be parsed and used on a website that is hosted on the same server as the database. When Sql Server is displaying the time it take to get the data, most of that time is spent in actually download the data from the remote server to my local development machine. How can I better test the actual speed of a query by removing the download time associated to the data returned by that query? I want to get the execution time of a query as if the database server was local to my computer. A: SentryOne Plan Explorer - a free download - lets you do this when you generate an actual execution plan from within the tool. It runs the query on the server and discards the results, so the timings indicated are purely the time on the server. For a heap more info on Plan Explorer: * *SentryOne Plan Explorer *SentryOne Plan Explorer 3.0 Demo Kit A: You can inject the data to a temporary table. You're adding a bit of overhead to the process but negligible compared to network latency. SELECT * INTO #TempTable FROM [Table] INTO Clause (Transact-SQL) A: To remove network issues from consideration and just look at execution stats I often assign the results to variables. So instead of SELECT name,type, COUNT(*) FROM master..spt_values GROUP BY name,type For example I would use DECLARE @name nvarchar(35), @type nchar(3), @count int SELECT @name= name, @type = type, @count = COUNT(*) FROM master..spt_values GROUP BY name,type There is an option in SSMS to discard results after execution but that also discards the output of SET STATISTICS IO ON etc. which isn't that useful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Updating an Attribute of a Component embedded in an AbstractDocument I'm inserting a component into an AbstractDocument as shown in the code below. final MutableAttributeSet aS = new SimpleAttributeSet(); aS.addAttribute(Utils.STYLE_ATTRIBUTE, attributeValue); Component myComponent = new MyComponent(); myComponent.addMouseListener(l); StyleConstants.setComponent(aS, myComponent); insertString(caretPosition, REPLACEMENT_CHARACTER, aS); Note that I'm also adding a mouse listener to this component. When the user double-clicks on the component embedded in the document, I wish to change the value of the Utils.STYLE_ATTRIBUTE attribute in the associated attribute set in the document to a new value. How do I do this? How can I get a handle to this attribute set or the element containing the attribute set? A: You can get the component's bounds in the mouseListener (use e.getSource()). Then use viewToModel() method of JEditorPane to get offset in the Document for the bounds' position. Then get leaf Element (character element) from the Document's structure and change style.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex matching? I have the below regular expression in Python, ^1?$|^(11+?)\1+$ Since there is a pipe '|', I will split it into 2 regex, ^1?$ For this, it should validate 1 or empty value. Am I correct? ^(11+?)\1+$ For the above regex, it would validate value of 1111. The first pair of 11 is based on (11+?) and the second pair of 11 is due to \1. When I attempt to execute it in Python, it returns true only for 1111 but not 11 or empty value. Am I wrong somewhere? A: Ted wrote: For this, it should validate 1 or empty value. Am I correct? Yes, that is correct. Ted wrote: When I attempt to execute it in Python, it returns true only for 1111 but not 11 or empty value. Am I wrong somewhere? The empty string does get matched. The following snippet: #!/usr/bin/env python import re for n in xrange(0, 51): ones = '1' * n matches = re.match(r'^1?$|^(11+?)\1+$', ones) if matches: div1 = n if matches.group(1) is None else len(matches.group(1)) div2 = 0 if div1 is 0 else len(ones)/div1 print "[{0:2}]:{1:2} * {2:2} = '{3}'".format(n, div1, div2, ones) will print: [ 0]: 0 * 0 = '' [ 1]: 1 * 1 = '1' [ 4]: 2 * 2 = '1111' [ 6]: 2 * 3 = '111111' [ 8]: 2 * 4 = '11111111' [ 9]: 3 * 3 = '111111111' [10]: 2 * 5 = '1111111111' [12]: 2 * 6 = '111111111111' [14]: 2 * 7 = '11111111111111' [15]: 3 * 5 = '111111111111111' [16]: 2 * 8 = '1111111111111111' [18]: 2 * 9 = '111111111111111111' [20]: 2 * 10 = '11111111111111111111' [21]: 3 * 7 = '111111111111111111111' [22]: 2 * 11 = '1111111111111111111111' [24]: 2 * 12 = '111111111111111111111111' [25]: 5 * 5 = '1111111111111111111111111' [26]: 2 * 13 = '11111111111111111111111111' [27]: 3 * 9 = '111111111111111111111111111' [28]: 2 * 14 = '1111111111111111111111111111' [30]: 2 * 15 = '111111111111111111111111111111' [32]: 2 * 16 = '11111111111111111111111111111111' [33]: 3 * 11 = '111111111111111111111111111111111' [34]: 2 * 17 = '1111111111111111111111111111111111' [35]: 5 * 7 = '11111111111111111111111111111111111' [36]: 2 * 18 = '111111111111111111111111111111111111' [38]: 2 * 19 = '11111111111111111111111111111111111111' [39]: 3 * 13 = '111111111111111111111111111111111111111' [40]: 2 * 20 = '1111111111111111111111111111111111111111' [42]: 2 * 21 = '111111111111111111111111111111111111111111' [44]: 2 * 22 = '11111111111111111111111111111111111111111111' [45]: 3 * 15 = '111111111111111111111111111111111111111111111' [46]: 2 * 23 = '1111111111111111111111111111111111111111111111' [48]: 2 * 24 = '111111111111111111111111111111111111111111111111' [49]: 7 * 7 = '1111111111111111111111111111111111111111111111111' [50]: 2 * 25 = '11111111111111111111111111111111111111111111111111' And the input 11 is not matched because 11 is matched in group 1 ((11+?)), which should then be repeated at least once (\1+), which is not the case (it is not repeated). A: You have a + after the \1 meaning a greedy 1 or more. Are you trying to match 1 between 1 and 4 times? Use: r'^(1+){1,4}$' The easiest is to use one of the great regex tools out there. Here is my favorite. With the same site, you can see why your regex does not work. Here is a site that explains regex's. A: If you want the second expression to match '11', '1111', '111111', etc. Use: ^(1+)\1$ A: I think you need more parenthesis to define what the | refers to. I would write the regex like this: /^(1?|^(11+?)\2+)$/ note there is only one start and end used
{ "language": "en", "url": "https://stackoverflow.com/questions/7561232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Symfony2 change validation group based on field value I have controller action like this: public function createAction() { $entity = new Client(); $request = $this->getRequest(); $form = $this->createForm(new ClientType(), $entity); $form->bindRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getEntityManager(); $em->persist($entity); $em->flush(); return $this->redirect($this->generateUrl('client_show', array('id' => $entity->getId()))); } return array( 'entity' => $entity, 'form' => $form->createView() ); } The underlying Client Entity has a field type witch can take values [0, 1] now, I have defined the 2 validation groups for Client entity: person and company. How can I change/choose validation group based on user entered value into type field? A: You can add a callback validation constraint for your class (Client entity), from the docs: Classes Some constraints apply to the entire class being validated. For example, the Callback constraint is a generic constraint that's applied to the class itself. When that class is validated, methods specified by that constraint are simply executed so that each can provide more custom validation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Map reduce problem in python I am currently struggling with an assignment. The solution would input a txt file and run through counting the number of palindromes and their frequency. I need to use Map reduce to create to do so For example: the string "bab bab bab cab cac dad" would output: bab 3 cab 1 dad 1 Here is what I have so far def palindrome(string): palindromes = [] for word in string.split(" "): if (word == word[::-1]): palindromes.append(word) return palindromes string = "abc abd bab tab cab tat yay uaefdfdu" print map(lambda x: palindrome(x), ["bab abc dab bab bab dad crap pap pap "]) Currently prints [['bab', 'bab', 'bab', 'dad', 'pap', 'pap', '']] Here is my attempt so far at the reduce section def p(lists): for list in lists: set_h = set(list) return set_h with the p function I want to create a set of all palindromes found. Then run a count of the palindromes on the list and make a dict out of this print reduce(p, [['bab', 'bab', 'bab', 'dad', 'pap', 'pap', '']]) Am I on the right track? A: I think it would be much easier for you if your map() and reduce() input was an actual list of words. To achieve that, .split() the string before passing it to map(). Then map() a word either to itself (if your mapper encounters a palindrome) or None. You can then filter() the results to discard None values, sort it and pass it to reduce(). reduce() would then reduce it to a dict mapping words to their total count. I will not provide you with a working solution not to take away from the learning factor. A: Split your string into a list before you map it. map() is for lists, sets, and dicts, not strings. word_list = words_str.split(" ") Avoid using map-filter-reduce unless your assignment dictates it; GVR says so. The proper solution uses Python's list comprehension syntax. In fact, you can do it with a pretty nasty one-liner: pal_count = { x: word_list.count(x) # reduce-ish for x in word_list # map-ish if x == x[::-1] # filter-ish } for x, y in pal_count.iteritems(): print x, y # print the results! Breaking it down... * *Catch this in a dictionary object to print it later: pal_count = { *Define the return objects: x: word_list.count(x) We use key:value syntax to associate the palindrome, x, with its number of occurrences. count() is like a built-in reduce function for lists. *Iterate through our list with a for loop, assigning the current value to 'x': for x in word_list *We only want to return palindromes, so we add a comparison operator to filter out bad values: if x == x[::-1] # cool logic, btw *Hurray! } By the way, I'm only doing your homework because I never did mine. The slower, less flexible, less portable, less awesome equivalent uses nested for loops: pal_count = dict() for x in word_list: # same loop if x == x[::-1] # is this a palindrome? if x in pal_count: # have we seen before? pal_count[x] += 1 else: # this one is new! pal_count.setdefault(x, 1) A: For your reduce function, you should start off with an empty dict and update/populate your counts. Reduce functions require 2 parameters, so one can be your dict, and the other, your palindrome. You can feed in an initial value in reduce like so: reduce(lambda x, y: x+y, some_list, initial_value_for_x) Take a look at dict's get for how to set default values, which should help you simplify your reduce function a lot. A: It would be very simple if we decompose the problem into small challenges. In our case this could be: * *Filter out all the palindromes from the list of words. *Get unique words to find the count. *Map all the unique words to their appropriate count. Code: words = "bab bab bab cab cac dad" is_palindrome = lambda word : word == word[::-1] palindromes = filter(is_palindrome,words.split(" ")) get_count = lambda word : (word , palindromes.count(word)) unique = set(palindromes) dict(map(get_count,unique)) Out[1]: {'bab': 3, 'cac': 1, 'dad': 1} Here is the short explanation: #Input: words = "bab bab bab cab cac dad" #Step 1: Filter out the palindromes. is_palindrome = lambda word : word == word[::-1] palindromes = filter(is_palindrome,words.split(" ")) #Step 2: Get the unique set of string to find their counts. unique = set(palindromes) #Step 3: Map every unique palindrome to their respective count. get_count = lambda word : (word , palindromes.count(word)) dict(map(get_count,unique)) #Output: Out[1]: {'bab': 3, 'cac': 1, 'dad': 1} NOTE: map in python can accept any sequence, not just list, set or dict. Strings in python are also sequence, hence not satisfied with Cody Hess's statement: map cannot accept strings. To demonstrate here is the very simple demo: In [10]: map(echo, "python") Out[10]: ['p', 'y', 't', 'h', 'o', 'n'] A: For map/reduce, using Counter object is pretty straight forward. from collections import Counter words = "bab bab bab cab cac dad" words_list = words.split(" ") cont = Counter() for word in words_list: cont[word] += 1 print(cont) # or if you want dict print(dict(cont)) https://docs.python.org/3/library/collections.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7561234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Menu bar overlay in Firefox I tried to overlay an option in the Tools menu of the Firefox menu bar but is not working. Below is the code: <?xml version="1.0"?> <?xml-stylesheet href="chrome://linktargetfinder/skin/skin.css" type="text/css"?> <!DOCTYPE linktargetfinder SYSTEM "chrome://linktargetfinder/locale/translations.dtd"> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script src="linkTargetFinder.js" /> <menupopup id="menu_ToolsPopup"> <menuitem label="&runlinktargetfinder;" key="link-target-finder-run-key" oncommand="linkTargetFinder.run()"/> </menupopup> <keyset> <key id="link-target-finder-run-key" modifiers="accel alt shift" key="L" oncommand="linkTargetFinder.run()"/> </keyset> <statusbar id="status-bar"> <statusbarpanel id="link-target-finder-status-bar-icon" class="statusbarpanel-iconic" src="chrome://linktargetfinder/skin/status-bar.png" tooltiptext="&runlinktargetfinder;" onclick="linkTargetFinder.run()" /> </statusbar> <toolbarpalette id="BrowserToolbarPalette"> <toolbarbutton id="link-target-finder-toolbar-button" label="Link Target Finder" tooltiptext="&runlinktargetfinder;" oncommand="linkTargetFinder.run()"/> </toolbarpalette> </overlay> But it is not appearing.Blow is my chrome.manifest file.Please help. content linktargetfinder chrome/content/ content linktargetfinder chrome/content/ contentaccessible=yes overlay chrome://browser/content/browser.xul chrome://linktargetfinder/content/browser.xul locale linktargetfinder en-US locale/en-US/ skin linktargetfinder classic/1.0 skin/ style chrome://global/content/customizeToolbar.xul chrome://linktargetfinder/skin/skin.css A: overlay chrome://browser/content/browser.xul chrome://linktargetfinder/content/browserOverlay.xul or overlay chrome://browser/content/browser.xul chrome://linktargetfinder/content/overlay.xul Try any one of these in your chrome.manifestfile. And the rest everything is fine in your file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get selected dropdown option in code-behind when ajax population I had a huge problem and spend hours trying to make it work, but no luck. My issue was, I had 2 dropdowns, once the first one is selected, the second is ajax populated. But when I want to capture it using C# codebehind, the selected value won't reflect. Is there any proper way by doing this and capturing the second dropdown, using code behind only, without using the isPostBack Request method? If you check out my new running website, below the navigation, you will see my scenario. http://www.mabinx.com/ I had to capture it on this page : http://www.mabinx.com/AddYourWebsite Any help will be appreciated! :) A: Put the second Drop Down in an Update Panel, then assign a code behind method to the attribute OnSelectedIndexChange, like so: <asp:UpdatePanel runat="server"> <ContentPanel> <asp:DropDownList ID="MYDDL" runat="server" OnSelectedIndexChanged="MethodThatRunsWhenChangeIsMade" AutoPostBack="true"> </asp:DropDownList> </ContentPanel> </asp:UpdatePanel And then in code behind: protected void MethodThatRunsWhenChangeIsMade(object sender, EventArgs e) { // Do something, like populate a third dropdown // If you need to populate another drop down, or something similar, put that in the same update panel } A: Solution : * *If you populate a .Net dropdown with ajax, the codebehind won't get the dynamically added list items on postback. *All you have to do is to create a .Net hidden input tag (runat server), and bind an onChange event, and populate the .Net hidden field with the selected dropdown selection value. *To reference the selected ajax'ed dropdown list item in the codebehind, just reference the .Net hidden field value. A: Your click event redirects the browser to perform the search: $('.btnSearch').click(function (e) { e.preventDefault(); window.location = "/Search/" + $('.ddlCountry option:selected').val() + "/" + $('.ddlState option:selected').val() + "/" + $('.ddlCategory option:selected').val(); }); As the page is redirecting and not posting back the selected value from the ddlState DropDownList will not be available when the page loads the subsequent time. Instead of changing the location using JavaScript, why not use an ImageButton control which posts back, enabling you to retrieve whatever values you need from the page and then redirect the response to perform your search.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Image list, removing reference Currently I'm using an ImageList control, attempting to copy files off the network and overwrite whats on the ImageList. However, when I try to copy the images once the List has be populated I'm unable since the images are loaded. I've tried using .Dispose() and .Images.Clear() but from what I've read nothing removes the reference to the Image itself so it can be replaced. imageList1.Images.Clear(); imageList2.Images.Clear(); int i = 1500; string fileName,sourcePath,targetPath,destFile = string.Empty; Image img = null; int counter = 0; bool exists = false; string image = string.Empty; MiscManager MM = new MiscManager(); //filePath = MM.GetBobbinImagePath(); filePath = @"C:\Program Files\Images"; sourcePath = @"\\network Images"; targetPath = filePath; if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } if (System.IO.Directory.Exists(sourcePath)) { string[] files = System.IO.Directory.GetFiles(sourcePath); foreach (string n in files) { fileName = System.IO.Path.GetFileName(n); destFile = System.IO.Path.Combine(targetPath, fileName); try { System.IO.File.Copy(n, destFile, true); } catch { MessageBox.Show("File in use",fileName); } } } do { if (i < 10) { fileName = "000" + Convert.ToString(i); } else if (i > 10 && i < 100) { fileName = "00" + Convert.ToString(i); } else if (i >= 100 && i < 1000) { fileName = "0" + Convert.ToString(i); } else { fileName = Convert.ToString(i); } image = filePath + fileName + ".bmp"; exists = File.Exists(image); if (exists) { img = Image.FromFile(image); imageList1.Images.Add(img); imageList2.Images.Add(img); imageList1.Images.SetKeyName(counter, Convert.ToString(i) + ".bmp"); imageList2.Images.SetKeyName(counter, Convert.ToString(i) + ".bmp"); counter++; } i++; } while (i < 10000); I don't know much about an Image list so any assistance is always greatly appreciated. Doing this in c# and VS 2010 A: You can use a MemoryStream so your image doesn't hold on to the reference to the file stream: using(MemoryStream ms = new MemoryStream(File.ReadAllBytes(image)) { img = Image.FromStream(ms); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: My DevExpress GridControl scrollbar won't scroll? I have a DevExpress GridControl on a WinForms app that has a lot of columns in it. My horizontal scrollbar is shown on the GridControl. But, when I expand one of my columns, instead of scrolling horizontally, it just shrinks another column in the same GridControl! It's nutty! Does anybody have any ideas? A: If you have fixed the size of the grid control than when you expand any column it'll take place form the next column and that will get shrink. Use min Width property also for column width that will fix the minimum size of the column.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the fastest way in iOS to retrieve the number of songs for a specific artist? I am trying to retrieve all the artists on the local iOS device, and for each artist, the number of songs available for that artist. I currently am doing this in a straight-forward fashion, by querying for all artists, and for each artist, counting the number of items (songs) in its collection: MPMediaQuery *query = [[MPMediaQuery alloc] init]; [query setGroupingType:MPMediaGroupingArtist]; NSArray *collections = [query collections]; for (MPMediaItemCollection *collection in collections) { MPMediaItem *representativeItem = [collection representativeItem]; int songs = [[collection items] count]; // do stuff here with the number of songs for this artist } However, this doesn't seem very efficient, or at least, it's slower than I had anticipated. On a demo iPhone 4 device with several hundred artists, the above code took about 7 seconds to run. When I commented out the line that obtains the count of "collection items," the time is reduced to 1 second. So I am wondering if there is a faster way to retrieve the song counts for artists than what I am doing above? Update 09/27/2011. I see that I can simplify the song count retrieval for an artist using this: int songs = [collection count]; Rather than what I was doing: int songs = [[collection items] count]; However, in reality this has had little effect on performance. I borrowed an iPhone 3G to try the performance of this issue on a slower device. My code takes 17.5 seconds to run on this 3G with only 637 songs spread across 308 artists. If I comment out the line that retrieves the number of songs, the same device finishes in only 0.7 seconds... There must be a faster way to retrieve number of songs per artist on an iOS device. A: After further research and trial and error, I believe the fastest way is to query the media library using an artistsQuery, and instead of looping through each artist's collection, you keep track of the number of songs per artist using an NSMutableDictionary of NSNumbers. Using the code below, I'm seeing a speed improvement of 1.5x to 7x over my initial approach, depending on the device speed, number of artists, and number of songs per artist. (Biggest increase was an iPhone 3G which was taking 21.5 seconds for 945 songs initially, and now takes 2.7 seconds!) I will edit this answer if I discover any speed improvements. Please feel free to correct anything directly in my answer, as I am still new to Objective-C and the iOS APIs. (In particular, I might be missing a faster way to store integers in a hash table than what I've got below with NSNumbers in an NSMutableDictionary?) NSMutableDictionary *artists = [[NSMutableDictionary alloc] init]; MPMediaQuery *query = [MPMediaQuery artistsQuery]; NSArray *items = [query items]; for (MPMediaItem *item in items) { NSString *artistName = [item valueForProperty:MPMediaItemPropertyArtist]; if (artistName != nil) { // retrieve current number of songs (could be nil) int numSongs = [(NSNumber*)[artists objectForKey:artistName] intValue]; // increment the counter (could be set to 1 if numSongs was nil) ++numSongs; // store the new count [artists setObject:[NSNumber numberWithInt:numSongs] forKey:artistName]; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android borders on individual views I have trouble making borders for android views What I try to do for simulating a border is to create a view with the main background, then create a view around it with the border color as the background. the first view then has a padding around it, but the wrapping border view still does not show reliably How do I fix this problem and what is a better way to add a border color around an element? A: You can define a Shape (make it a rectangle, define a stroke) and use that shape as the background of yout view. You can also define rounded corners. If you need something more elaborated, you can make a 9-patch image and use that as the background.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get alternate name in Facebook? I can't find it in the Graph API, is there some way to get the alternate name someone fills out in their Account Settings? A: It's not currently possible to access this field via the API by any means i'm aware of, you could file a wishlist item in the bug tracker, it may get picked up and implemented. A: Do you mean the user's 'username'? It's a field in the User Graph Object. For example, if you want 'btaylor' returned for this user, https://www.facebook.com/btaylor, you'd grab the 'username' field from the User Graph Object, as in this example: https://graph.facebook.com/btaylor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recording an audio stream in C# from C++ ASIO library I need to find the best way to record an audio stream. I have already built the low level code in C++ and interfaced parts of it to C#. So i have a C++ callback that gives me an array of array of floats - the audio signal. At the moment, my C++ lib is recording the data straight to the file in the wav format and it just notify my C# app when it ends recording. But, I would like to have more interactivity on the UI side, like 'infinite' progress bar, amount of the data recorded, cancel button etc, and since it's gonna be a minute at worst, maybe it's better to keep it in memory. I know very little about .NET and C# memory management, so i don't know how to make it efficiently. Is there any fast resizable container in C#, where i could just put the data inside and later access it like an array? I also would like to build a waveform image off it. I already have those things done in C++, but somehow i don't like the idea to write too much messaging, transfer objects etc. So to put things together: * *I have C++ unmanaged callback that does some stuff and from within i'd like to call C# method once it has processed the data, the C prototype would be: void process(float **signal, int n); (usually [2][n] - for stereo) What would be C# equivalent and how do i call it from that C++ callback ? *What is the best class to write continuous stream to (like mem.put(float[][] data, int size) ) and then read it as an array or with other easy way (to save a wav file from it for example or make a waveform bitmap) *Is there going to be a significant performance loss if i do it in C#? (managed c++ wrapper calling c# function etc... and probably some DSP stuff) or i am just paranoid ? :) Cheers, pablox My solution Ok i solved it that way: In my C++ header file i got transfer structure: public ref struct CVAudio { public: float *left; float *right; int length; }; Then in managed C++ class i have declared: delegate void GetAudioData([In, Out] CVAudio^ audio); Then i can use it as an argument to the method that initialize audio: void initializeSoundSystem(void *HWnd, GetAudioData ^audio); That delegate has also a C prototype of typedef void (CALLBACK *GETAUDIODATA)(CVAudio ^a); Which is used in the internal C++ class as: void initializeSoundSystem(HWND HWnd, GETAUDIODATA audio); Then body of the first method is: void VDAudio::initializeSoundSystem(void *HWnd, GetAudioData ^audio) { HWND h = (HWND) HWnd; acb = audio; pin_ptr<GetAudioData ^> tmp = &audio; IntPtr ip = Marshal::GetFunctionPointerForDelegate(audio); GETAUDIODATA cb = static_cast<GETAUDIODATA>(ip.ToPointer()); audioObserver->initializeSoundSystem(h, cb); } Body of audioObserver just stores that callback in the object and do some audio related things. Callback is then called in the processing method like that: VDAudio^ a = gcnew VDAudio(); a->left = VHOST->Master->getSample()[0]; //returns left channel float* a->right = VHOST->Master->getSample()[1]; a->length = length; (*callback)(a); And the body of C# delegate: public void GetSamples(CVAudio audio) { unsafe { float* l = (float*)audio.left; float* r = (float*)audio.right; if (l != null) { SamplePack sample = new SamplePack(); sample.left = new float[audio.length]; sample.right = new float[audio.length]; IntPtr lptr = new IntPtr((void*)l); IntPtr rptr = new IntPtr((void*)r); Marshal.Copy(lptr, sample.left, 0, audio.length); Marshal.Copy(rptr, sample.right, 0, audio.length); this.Dispatcher.Invoke(new Action(delegate() { GetSamples(sample); })); } } } So probably that's not a best code around - i have no idea. Only can say it works, doesn't seem to leak etc. :) A: Question 1: You want to pass a C# delegate matching the unmanaged C signature into your C++. You can then call back on this as if it was a C function pointer. For example, delegate void ASIOCallback(IntPtr signal, int n); You would then need to either manually marshal the signal memory into a managed buffer, or copy it into a unmanaged buffer. Either would be done using methods on the Marshal class. This leads into question 2. Question 2: You have a couple of choices, primarily determined by whether you want to store the data in managed or unmanaged memory. Storing it unmanaged memory may make it easy to interact with you unmanaged code and could theoretically be more efficient by reducing the number of copies of the data. However, storing it in managed memory (via an array, generic collection, MemoryStream, etc) would make it much easier to access from managed code. Question 3: The two considerations you need to make regarding performance are raw number crunching and duplicating you data. In general, numerical operations in C# are not much slower than C/C++. There are multiple good sources on the web for comparing this type of performance. As far as copying data, I think this may cause more of an issue for you. Both due to the time spent copying the data and the extra memory you application will use. You need to consider whether you want a copy of your data in both managed and unmanaged memory, and I am guessing this will be driven by how much you want to access it in C# and/or C++.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: User Agent Switcher for Chrome I'm looking for a User Agent Switcher for Chrome. Searching the Chrome Web Store does not come up with a simple switcher. I understand I can run the browser via command line and arguments: Google Chrome: Change User Agent to Access Website. Is there a user agent switcher built in to the UI of Google Chrome? If so, how do I access it? A: dunno but i found this: http://www.hacker10.com/tag/internet-browser-headers/ saying: Chrome browser, User-Agent Switcher extension: UPDATE: Addon erased from Chrome Store and this where they say (as you mention) you can do it with a command line switch: http://www.google.com/support/forum/p/Chrome/thread?tid=64e4e45037f55919&hl=en for example, this is how to make chrome report itself as IE8.0 on my machine C:\Users\XXXX\AppData\Local\Google\Chrome\Application\chrome.exe --user-agent="Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 3.5.30729)" If you really just want to change the user agent for some sites or testing one little thing you could do to make it faster is create shortcuts to the site that includes the switch of user agent. at least that way its not so fiddly. another silly idea: If you need exactly two user agents in chrome you could use canary build as one, I do this to have my apps account and google account open at the same time. A: In version 66 of Chrome the option to set User Agent is hidden in Network Conditions, which can be accessed by pressing f12 to bring up the developer tools box > clicking the 3 dots next to the close button of the developer tools box > More tools > Network conditions Further reading: https://developers.google.com/web/tools/chrome-devtools/device-mode/override-user-agent A: Chrome Developer Tools (as of version 17+) have the ability to supply custom User-Agent header * *Bring up the developer tools by pressing f12 *Look in the Console "drawer" (make it visible if not visible) *Click the Emulation tab in the console drawer. *Tick "Spoof user agent" and select an agent (or enter your own User-Agent string using the Other... option). A: You can use this technique to change UA. It relies on changing the User-Agent header using the (still experimental) webRequest API A: Update for 12/2019 OPTION 1: Chrome Developer Tools Chrome's built-in user-agent switcher has moved several times, but it seems to have stayed in one place for the past few years. As of the time of writing, here's how you get it: * *Open DevTools: hit F12 or right-click and select "Inspect." *Open the drawer (the bottom pane) if it is not already open: hit Esc *Go to the "Network conditions" panel. (You may need to click the ⋮ menu button on the left to view a list of all available panels.) *Next to "User agent," deselect "Select automatically." *Select a user agent from the dropdown or enter a custom string in the text box. For the official documentation, which has (presumably) up-to-date instructions with screen grabs, go to: https://developers.google.com/web/tools/chrome-devtools/device-mode/override-user-agent OPTION 2: Extensions If you'd like a more convenient or feature-rich option, or if you're using a chromium browser other than Chrome, your best bet is a browser extension. Here are several that are up-to-date, and well-reviewed as of the time of writing: * *User-Agent Switcher and Manager *User-Agent Switcher Google also offers its own user-agent extension for Chrome (which does apparently work in some other chromium browsers, according to an Edge user): * *User-Agent Switcher for Chrome A few notes on this last option: Although Google's UA switcher extension was updated only a few months ago (as of 12/19), reviews indicate that it might be somewhat out of touch when it comes to current browsers. It may also cause performance issues if you leave it enabled all the time. That said, this extension does work, and it is overall positively reviewed, so it could be a viable option if you want a convenient, albeit simple, UA switcher for Chrome. A: You can use webRequest API to create a chrome extension to modify the headers. When OP asked this question, this API may not exist or may be in experimental phase but now this api is quite stable. chrome.webRequest.onBeforeSendHeaders.addListener( function(details) { for (var i = 0; i < details.requestHeaders.length; ++i) { if (details.requestHeaders[i].name === 'User-Agent') { details.requestHeaders[i].value = "Android_Browser" // Set your value here break; } } return { requestHeaders: details.requestHeaders }; }, {urls: ['<all_urls>']}, [ 'blocking', 'requestHeaders'] ); If you are looking for an already built extension, you can try Requestly where allows you to easily setup rules on website URLs or domains so that whenever that website is opened in browser, the User Agent is automatically overridden. The best part here is that you can simultaneously run multiple rules for multiple websites. Most of the other options either allow to override User Agent for one browser tab or all of the tabs. Here is a screenshot for your reference: For more info, please visit blog: https://medium.com/@requestly_ext/switching-user-agent-in-browser-f57fcf42a4b5 To install, visit chrome store page: https://chrome.google.com/webstore/detail/requestly-redirect-url-mo/mdnleldcmiljblolnjhpnblkcekpdkpa The extension is also available for Firefox. Visit http://www.requestly.in for details. A: If you would like change the user agent in chrome you can not do it in the developer tools by checking the spoof user agent box in the emulation tab.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: How to iterate a synchronized treeMap? Currently have this implementation: static Map s_AvailableGameTables = Collections.synchronizedMap(new TreeMap<Integer,Table>()); How can I iterate over all it's content from the start to the end like an array? Thanks A: Assuming the declaration is static Map<Integer,Table> s_AvailableGameTables = Collections.synchronizedMap(new TreeMap<Integer,Table>()); (not just Map) The following will iterate over all key/value pairs: for (Map.Entry<Integer,Table> e : s_AvailableGameTables.entrySet()) { int key = e.getKey(); Table tbl = e.getValue(); } A: If you want to iterate over the entries (key-value pairs in the map): for (Map.Entry<Integer, Table> entry : s_AvailableGameTables.entrySet()) { System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue()); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Data Modeling: Class vs. ER Diagram I know that both concepts are alot different, and I have had the opportunity to work with both. However, I still don't feel confortable answering the question "when one designs a database system, should one class-diagram or ER-diagram it?"... Can anyone please elaborate on this? A: My two cents on the subjest, is always ER-design your database system.. why? Classes and objects are a more natural way of expressing Domain Models (object abstractions of business domains, etc..) they will contain properties that map to or make more sense within the sphere of the business domain, they might also encapsulate logical operations on those properties. Entity Model, indeed might be similar to the Object Domain Model (classes), but will not be polluted with certain business concepts that should exist only in the business domain. This is more visible in the DDD (Domain Driven Development) world where, your domain model (classes) might contain objects such as ShippingStrategy and SalesTax, but the underlying data model might be completely agnostic to the idea of Shipping Strategies, and might only be concerned with Location, Shipper, Commodity, etc.. So in my mind I'd rather have a pure entity model for the database design. Further more, when it comes to notation. Moving from ERM to database Schema is much easier than class diagram.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ManyToManyField Relationships Between Multiple Models I have the following models that represent books and authors. A single book can have multiple authors and an author could have written multiple books. So I am using Django's ManyToManyField type to link the two models to each other. I can add a Book, using the Django Admin perhaps, and create an Author in the process. But when I view the Author I just created it's not linked to the Book. I have to explicitly set the reverse relationship between the Author instance and the Book instance. Is that just the way it is or could I be doing something different? Models.py class Book(models.Model): book_title = models.CharField(max_length=255, blank=False) authors = models.ManyToManyField('Author', blank=True) class Author(models.Model): author_first_name = models.CharField(max_length=255, blank=False) author_last_name = models.CharField(max_length=255, blank=False) books = models.ManyToManyField(Book, blank=True) A: You don't need two ManyToManyField definitions because the model class without the ManyToManyField is related to the other through the reverse relationship. See: https://docs.djangoproject.com/en/dev/topics/db/queries/#many-to-many-relationships If you defined the two model classes as: class Book(models.Model): book_title = models.CharField(max_length=255, blank=False) authors = models.ManyToManyField('Author', blank=True) class Author(models.Model): author_first_name = models.CharField(max_length=255, blank=False) author_last_name = models.CharField(max_length=255, blank=False) then for any Author instance a, a.book_set.all() consists of the books that the author wrote (or co-wrote).
{ "language": "en", "url": "https://stackoverflow.com/questions/7561276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Remove an element from the DOM from reference to element only This is either very simple or impossible. I know I can do this: var element = document.getElementById('some_element'); element.parentNode.removeChild(element); ...but it feels messy. Is there a tidier - and universally supported - way to do the same thing? It's seems - to me at least - like there should be something like this: document.getElementById('some_element').remove(); ...but that doesn't work, and searching Google/SO has not yielded any alternative. I know it doesn't matter that much, but parentNode.removeChild() just feels hacky/messy/inefficient/bad practice-y. A: The DOM level 4 specs seems to have adopted the "jQuery philosophy" of doing several DOM changing operations (see https://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#interface-element). Remove is one of them: var el = document.getElementById("myEl"); el.remove(); At this time, it's only supported in later version of Chrome, Opera, Firefox, but there are shims to patch this up if you want to use this functionality in production today: https://github.com/Raynos/DOM-shim Wether it's preferable to removeChild or not, I leave undebated for now. A: It can seem a bit messy, but that is the standard way of removing an element from its parent. The DOM element itself can exist on its own, without a parentNode, so it makes sense that the removeChild method is on the parent. IMO a generic .remove() method on the DOM node itself might be misleading, after all, we're not removing the element from existence, just from its parent. You can always create your own wrappers for this functionality though. E.g. function removeElement(element) { element && element.parentNode && element.parentNode.removeChild(element); } // Usage: removeElement( document.getElementById('some_element') ); Or, use a DOM library like jQuery which provides a bunch of wrappers for you, e.g. in jQuery: $('#some_element').remove(); This edit is in response to your comment, in which you inquired about the possibility to extend native DOM implementation. This is considered a bad practice, so what we do instead, is create our own wrappers to contain the elements and then we create whatever methods we want. E.g. function CoolElement(element) { this.element = element; } CoolElement.prototype = { redify: function() { this.element.style.color = 'red'; }, remove: function() { if (this.element.parentNode) { this.element.parentNode.removeChild(this.element); } } }; // Usage: var myElement = new CoolElement( document.getElementById('some_element') ); myElement.redify(); myElement.remove(); This is, in essence, what jQuery does, although it's a little more advanced because it wraps collections of DOM nodes instead of just an individual element like above. A: Your code is the correct and best way to do it. jQuery has what you're looking for: $("#someId").remove();
{ "language": "en", "url": "https://stackoverflow.com/questions/7561277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: solr filter or tokenizer to make combinations of words I'm trying to implement a reasonable name suggest feature using a series of filters. At the moment I have <fieldType name="suggester" class="solr.TextField" positionIncrementGap="1" autoGeneratePhraseQueries="true"> <analyzer type="index"> <tokenizer class="solr.WhitespaceTokenizerFactory"/> <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/> <filter class="solr.ASCIIFoldingFilterFactory"/> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.ShingleFilterFactory" outputUnigramsIfNoShingles="true" maxShingleSize="2" outputUnigrams="true"/> <filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="15"/> </analyzer> <analyzer type="query"> <tokenizer class="solr.WhitespaceTokenizerFactory"/> <filter class="solr.WordDelimiterFilterFactory" generateWordParts="1" generateNumberParts="1" catenateWords="1" catenateNumbers="1" catenateAll="0" splitOnCaseChange="1"/> <filter class="solr.ASCIIFoldingFilterFactory"/> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.ShingleFilterFactory" outputUnigramsIfNoShingles="true" maxShingleSize="2" outputUnigrams="true"/> <filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="15"/> </analyzer> </fieldType> Which certainly needs more tuning, but I'm after one particular aspect for this question. For an input string mark daniel sievers the above will match on a query onmark and sievers but what I really want is to reduce the verbosity of the EdgeNGramFilter because it causes overmatching and use a filter/tokenizer that can combine words in some configurable manner, eg for input mark daniel rex sievers create tokens mark sievers, mark daniel sievers, mark rex sievers and so on. I didnt apply any paricular algorithm to that, but I'm wondering if such a beast exists (almost certainly does) or its best to write my own as a filter plugin? Solr 3.3.0 A: I'd use a ShingleFilter : http://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters#solr.ShingleFilterFactory For example : <filter class="solr.ShingleFilterFactory" maxShingleSize="3" outputUnigrams="true"/> Input : mark daniel sievers. Tokens produced : mark, mark daniel, mark daniel sievers, daniel, daniel sievers, sievers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Saving Score in a Label and loading when the app opens I'm setting up a "click counter" on my iOS app, so the user will know how many times he performed an action. I'm using NSUserDefaults, for I'm can't make it load when the app opens. First I created a UILabel that stores the number and increases it each time the user click on it: - (IBAction) increaseScore { self.currentScore = self.currentScore + 1; currentScoreLabel.text = [NSString stringWithFormat: @"%ld", self.currentScore]; // Saving: NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:currentScoreLabel.text forKey: @"Score"]; [defaults synchronize]; } This works OK, the Label increases +1 each time I click on the button. Not sure if it is saving correctly, because when I close the app opens again, it doesn't load, the label goes back to zero: - (void)viewDidLoad { [super viewDidLoad]; currentScoreLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey: @"Store"]; } Any ideas??? A: Looks like you got a typo there. In your increaseScore method you're setting an object for key "Score" and in your viewDidLoad you're trying to get a string for key "Store". Bummer but I always try to setup up a static NSString of they keys I'm using for this exact reason. Ex: static NSString* kScoreKey = @"Score"; this way you call [defaults setObject:currentScoreLabel.text forKey:kScoreKey]; and currentScoreLabel.text = [[NSUserDefaults standardUserDefaults] stringForKey:kScoreKey];
{ "language": "en", "url": "https://stackoverflow.com/questions/7561285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: find all pages on a site that use a particular selector I need to modify properties of a selector(let's say #myList) that is used on few pages of website I'm working on. I want to make sure my changes won't ruin the design. Is there a tool that will generate a list of all pages on a website that uses a particular selector? (I don't know on which pages selector is used. The site has too many pages so doing it manually won't work.) A: I have built a command line tool called Element Finder which lets you enter in a CSS selector, like "#myList", and then searches through the directory and finds all of the HTML files with elements matching that selector. You will need to install Element Finder, cd into the directory you want to search, and then run: elfinder -s "#myList" Or: elfinder -s "#foo > .bar p > td .baz" For more info please see http://keegan.st/2012/06/03/find-in-files-with-css-selectors/ A: find /path/to/your/project -name '*.html' -exec grep -l 'id="myList"' {} \; Of course, change the path and/or extension to suit your needs. Edit: I should also note that this method will only work for non-nested/advanced selectors. If you're trying to find elements matching #foo > .bar p > td .baz or something ridiculous, then the answer is probably no.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: prevent js module execution I am working on integrating a javascript compiler into my web framework, and am running into a bit of a snag. When running in development mode, all javascript modules are loaded individualy by ajax, but when switching to production mode, it compiles multiple modules into one file to reduce the number of HTTP requests. Each module can call a function to 'require' another module. The problem I have is if moduleA requires moduleB, and moduleB is not loaded, it makes an ajax request. Consider the following code sample (extremely simplified), where moduleA and moduleB are compiled together. moduleA requires moduleB, and moduleB has not been loaded by that point in the script, so it makes an ajax request. A few lines later moduleB is run, and so it has been run twice. /* compiled script file (multiple files combined) */ util.require = function(moduleName) { if (moduleIsNotLoaded(moduleName)) { loadByAjax(moduleName); } } /* start module a */ util.require('moduleB'); moduleB.func(); /* end module a */ util.setModuleLoaded('moduleA'); /* start module b */ moduleB.func = function() { alert('hello world'); }; bind_some_event(); /* end module b */ util.setModuleLoaded('moduleB'); This is unnacceptable because it defeats the initial purpose of reducing HTTP requests, and some modules bind event handlers, which cannot be bound twice. Some modules are not only function definitions and have code that is immediatly run. Is there a way that I can force all modules to be available and registered as loaded, without actually running the code inside each module until the entire file has been run? I understand there is probably not a simple solution, and may require a paradigm shift. A: Our web app is made of modules too. The way it works may give you some ideas: The most common modules, are embedded in the initial HTML page (HTML, JS, CSS, data images). The app start with that page(300-400kb, then from the cache), and a single HTTP call for data.This makes the app start very quickly. Then if the user choose a new module, not loaded yet. It gets it through an iframe. HTML, CSS and Javascript objects are imported by the parent page. The new module is then started from the parent page too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What needs to be released in the AppDelegate? I have a project that I created by using Xcode's Single View Application template. Obviously, it comes with a view controller and an app delegate file. Everything works fine. I just wanted to use Xcode's Analyze tool for the first time to make sure everything is fine before submitting to the App store. I get the potential leak error for the following lines of code in the app delegate: self.viewController = [[myViewController alloc] initWithNibName:@"myViewController" bundle:nil]; self.window.rootViewController = self.viewController; Full app delegate is as follows: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[myViewController alloc] initWithNibName:@"myViewController" bundle:nil]; self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; } I didn't modify the app delegate myself. I am using whatever the template gave me. Do I need to release something somewhere in the app delegate? If so, what? and in which method of app delegate? A: Nothing needs to be released in the application delegate since the app is terminating and the OS will recover all resources. Indeed, it is improbably that dealloc will even be called. See SO link for more information. If you need to do cleanup when the app quits, use applicationWillTerminate:. A: The line self.viewController = [[myViewController alloc] ... allocates an instance and then assigns it to the property self.viewController. On the alloc, the reference count will be 1, but assigning to a property with retain set will increment the reference count again. Since the reference count is only decremented by 1 in the dealloc, this object will never be freed = a leak. See the section on Objective-C memory management in the iOS developer docs for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Model Binding RadioButtonFor() default Select MVC3.0? Hi I have a ModelBinded View foreach (var Model in Model) { @Html.RadioButtonFor(modelItem => Model.DefaultLocation, Model.AddressID, new { @Checked = Model.DefaultLocation, id = Model.AddressID }) } @Checked is retrieved from Database as Boolean True or False. HTML generated for this Razor code is as Below <input checked="True" id="27" name="model.DefaultLocation" type="radio" value="27"> <input checked="False" id="28" name="Model.DefaultLocation" type="radio" value="28"> Though it says id="27" as Checked= "true" my page is showing the last radio button as selected. I am trying to achieve that what ever the return value form the database says true, that Radio button should be selected by default. I am not able to figure out whats wrong. can any one help me to fix this issue? thank you for your time. A: I know this is a old thread, but just had the same problem. RadioButtonFor is the right way to go, but instead of new { @Checked = Model.DefaultLocation, id = Model.AddressID } just use new { @isChecked = Model.DefaultLocation, id = Model.AddressID } A: @Html.EditorFor( modelItem => Model.DefaultLocation, Model.AddressID, new { @Checked = Model.DefaultLocation, id = Model.AddressID } )
{ "language": "en", "url": "https://stackoverflow.com/questions/7561300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show a progress bar on HTTP POST? I am trying to upload a video to an api and I was wondering how you show a progress bar show and also dismiss it when an upload has finished? public class Loadvid extends AsyncTask <Object,Integer,String>{ EditText etxt_user = (EditText) findViewById(R.id.user_email); EditText etxt_pass = (EditText) findViewById(R.id.friend_email); protected void onPreExecute(){ dialog = new ProgressDialog(share.this); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setMax(100); dialog.show(); super.onPreExecute(); } @Override protected String doInBackground(Object... params) { if(etxt_user.equals("")||etxt_pass.equals("")){ dialog.dismiss(); Alert.setMessage("Please fill in the Blanks"); Alert.show(); } else{ Pattern keys= Pattern.compile("[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+"); Matcher matcher = keys.matcher((CharSequence) etxt_user); Matcher matcher1 = keys.matcher((CharSequence) etxt_pass); if(!matcher.matches()|| !matcher1.matches()) { dialog.dismiss(); Alert.setMessage("Wrong email address."); Alert.show(); } } //implement the httppost. try { MultipartEntity me = new MultipartEntity(); me.addPart("file", new FileBody(new File("/"))); httppost.setEntity(me); HttpResponse responsePOST = client.execute(httppost); HttpEntity resEntity = responsePOST.getEntity(); InputStream inputstream = resEntity.getContent(); BufferedReader buffered = new BufferedReader(new InputStreamReader(inputstream)); StringBuilder stringbuilder = new StringBuilder(); String currentline = null; while ((currentline = buffered.readLine()) != null) { stringbuilder.append(currentline + "\n"); String result = stringbuilder.toString(); Log.v("HTTP UPLOAD REQUEST",result); inputstream.close();} } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(String result){ super.onPostExecute(result); if(result==null){ dialog.dismiss(); Alert.setMessage("The result failed"); Alert.show(); return; } else { Intent intent = new Intent("com..."); startActivity(intent); } } } But it doesn't work. When i click on the button to send, it shows the handler for 2 seconds then brings up an error close. Error log tells me that i have my errors caused at the Matcher matcher = keys.matcher((CharSequence) etxt_user); @ "do in background" and somewhere in my onPrexecute. What am I doing wrong, help please! A: Just use AsyncTask. It was made specifically for such tasks: executing long-running code in the background and updating the UI properly (on UI thread).
{ "language": "en", "url": "https://stackoverflow.com/questions/7561305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: getting more then one column on an inner join i have the following query: SELECT c.company_id, c.company_title, c.featured, a.address, a.postal_code, pc.city, pc.region,cat.category_title, p.phone FROM dloc.companies c INNER JOIN dloc.address a ON ( c.address_id = a.address_id ) INNER JOIN dloc.postal_code pc ON ( a.postal_code = pc.postal_code ) INNER JOIN dloc.company_categories cc ON ( c.company_id = cc.company_id ) INNER JOIN dloc.categories cat ON ( cc.category_id = cat.category_id ) INNER JOIN dloc.phones p ON ( c.company_id = p.company_id ) WHERE c.company_title like '%gge%' everything works just fine. the only thing is.. well. phones contains more then one phone number for some companies... and i guess i get only the first one... or random, im not sure. how can i rewrite this query so it will return all the phone numbers for each company? A: Given that query, you should get one row for each phone number row (per company). SQL works as relationship/set math/theory - having a '-many' relationship means multiple rows returned (So, your query should already be perfroming the desired behaviour). Often, the problem people writing queries experience isn't getting multiple rows - it's restricting it to the desired 'single' row. EDIT: Result Ordering - SQL, by convention, returns things unordered, unless some sort of explicit ordering is given (through the use of an ORDER BY clause). You are seeing 'random' phone numbers being returned 'first' because the RDBMS still has to read/return results sequentially; this order is determined at runtime (...usually), when the system picks what indicies to use while accessing data. The full interaction is rather complex (and is probably vendor specific), so just keep this in mind: UNLESS YOU SPECIFY ORDERING OF YOUR RESULTS, THE RESULTS ARE RETURNED IN A RANDOM ORDER period. A: I would suggest you using GROUP_CONCAT on the p.phone field. A few considerations, though: * *It looks like a company can have more than one phone. But also, none! So you should change your INNER JOIN to LEFT JOIN to take that into consideration. *It also looks like a company can have more than one address. If that's true, not only previous consideration should be taken into, but also you should rework your query to accommodate this. A: You should get all phone numbers for the given company id because the join begins by doing a cartesian product between the two tables and then removing all "rows" that doesn't match the criteria in the join. A: group_concat will collect all phonenumbers in one column. Add a group by on company_id, if you are sure no other values are listed more than once per company. If not, put those 'duplicate' (for want of a better word) values in a group_concat as well. SELECT c.company_id , c.company_title , c.featured , a.address , a.postal_code , pc.city , pc.region , cat.category_title , GROUP_CONCAT(p.phone) as phonenumbers FROM dloc.companies c INNER JOIN dloc.address a ON ( c.address_id = a.address_id ) INNER JOIN dloc.postal_code pc ON ( a.postal_code = pc.postal_code ) INNER JOIN dloc.company_categories cc ON ( c.company_id = cc.company_id ) INNER JOIN dloc.categories cat ON ( cc.category_id = cat.category_id ) INNER JOIN dloc.phones p ON ( c.company_id = p.company_id ) WHERE c.company_title like '%gge%' GROUP BY c.companyid See: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
{ "language": "en", "url": "https://stackoverflow.com/questions/7561309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OpenGL ES Faces appear to be transparent when alpha is 1.0? I am working on an object (OBJ File) loader for my app on iOS, currently I have successfully read the vertices and the faces of the object, and I am now just adding colours to the imported models. I am coming across a major problem now. Out of a cube with six faces, all coloured red apart from two opposite faces which are coloured blue. This cube is set to rotate so I can see all sides, but the colours do not appear correctly as shown in the video below: http://youtu.be/0L2AIFkd2Qk The blue faces only shows when the two blue sections overlap, I cannot figure out why - I am used to OpenGL for PC, is there something I am missing which is causing this strange colouring? The colouring is achieved by sending a large float array of the format RGBA RGBA RGBA etc for each vertex; // colours is the name of the array of floats glColorPointer(colorStride, GL_FLOAT, 0, colors); glEnableClientState(GL_COLOR_ARRAY); glDrawArrays(renderStyle, 0, vertexCount); [EDIT] Problem has now been solved, I was just drawing all the triangles from the model calling glColor4f(0.5f, 0.5f, 0.0f, 1.0f); glDrawArrays(GL_TRIANGLES, 4, 4); only once for the whole array, when I split this up for each face in the model it allowed me to use GL_DEPTH_TEST without causing the screen to go blank! A: The problem is that GL_DEPTH_TEST is disabled. Opengl is not making any depth testing so all your objects look weird. In order to enable depth testing you must create yourself new render buffer. This is a small snippet on how to crate this buffer: // Create the depth buffer. glGenRenderbuffersOES(1, &m_depthRenderbuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_depthRenderbuffer); glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height); This buffer is created for OpenGL ES 1.1, for 2.0 just delete all "OES" extensions. When you have created depth buffer you may now enable depth testing like this: glEnable(GL_DEPTH_TEST); Had this problem few times myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: From a .py file converted to an .exe (using py2exe), how do you import data from a written file? My program saves data to an external .py file for use later on. This works fine normally, however once converted to an executable, it saves a file externally, but only draws from the internal data. This is what the code looks like: def save_game(): with open("save.py") as _save: _save.write("""variables to be used later""") _save.close() def load_game(): import save reload(save) x = save.x In the .py, it creates save.py and writes all the variables. When it loads, all of the variables are imported exactly as written. After the .exe was created, it creates save.py with all the variables, but it only uses the iteration of save.py that existed when the .exe was created. Is there any way to achieve similar functionality after converting my app to an executable? A: Use the official method and use pickle instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alternative to I'm trying to fix an old script written for me. I need it to run without <body onload="init ();">. I'd like to run the function from inside the script without inline code like that command. Sorry I'm not a JS expert but how do I do this? A: Here's a slight variation on Tejs' response. I often find it more readable and manageable to separate the init() function from the code registering the event handler: function init(e) { //statements... } document.addEventListener('DOMContentLoaded', init, false); Also, in place of an explicit init() function, I've sometimes used a self-executing anonymous function placed at the very, very bottom of the page, just before the </body> tag: (function() { //statements... })(); A: <script type="text/javascript"> function init() { // Put your code here } window.onload = init; </script> Or, if you are using jQuery: $(function() { // Your code here }); A: best option is to just put the call to init() at the bottom of the page: <html> <head> ... </head> <body> .... page content here ... <script type="text/javascript">init();</script> </body> </html> By placing it at the bottom like that, you'll be sure that it runs as pretty much the very last thing on the page. However, note that it's not as reliable as using the onload option in the body tag, or jquery's $('document').ready() or mootool's window.addEvent('domready', ...). A: In a pure JavaScript implementation, you'd want to wait for the page to be ready to invoke your events. The simplest solution is like so: <script type="text/javascript" language="javascript"> window.onload = function() { init(); }; </script> But that's not much better than your original implementation via placing that on the tag itself. What you can do is wait for a specific event though: document.addEventListener("DOMContentLoaded", function() { init(); }, false); This should be fired a little earlier in the cycle and should do nicely. Additionally, if you are using jQuery, you can simply add a function to be executed when that event is fired using the simple syntax: $(document).ready(function() // or $(function() { init(); }); A: <script type="text/javascript"> function init() { // Put your code here } window.onload = init; </script> it is not work should be use this <script type="text/javascript"> function init() { // Put your code here } window.onload = init(); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7561315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Why is there a gap between status bar and main view I am using a UITabBarController to switch between two view controllers. The first view controller looks fine but the second view controller has a white gap between the status bar and the root view equaling the height of the status bar. Here is the nib file for the second view controller. I've turned on the simulated status bar and tab bar and placed the UIImageView flush between those two bars. My code does nothing to change the position of the UIImageView. I noticed that the Facebook app sometimes has this problem when returning from viewing a photo to the news feed. My problem is similar, except it happens 100% of the time. What could be the problem? A: What is the origin of your containing view and image view? If you have manually adjusted these to compensate for the status bar and then your nib is set to want full screen, this may cause it to be one status bar's height below the top of it's content view, which looks like the situation you have. The origins of both views should be (0,0), I think.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Django: What's the best way to create different "kinds" of users and use them interchangeably? I'm building a site similar to eBay. I have two kind of users: Sellers and Buyers. I've read this https://docs.djangoproject.com/en/1.3/topics/auth/#storing-additional-information-about-users and i've created a UserProfile(abstract) model and two other models: Seller and Buyer. Now, i've other model: Comment. Comment can be wrote by Sellers and Buyers. How should i relate them? I've been thinking these options, but i have no expirience with Django and maybe you have a better idea: class Comment(models.Model): created_by = models.ForeignKey(UserProfile) or class Comment(models.Model): created_by = models.ForeignKey(auth.models.User) EDIT: I want to have different Classes (Seller and Buyer) becouse they can have different data. A: Groups. It's already part of Django authentication. https://docs.djangoproject.com/en/1.3/topics/auth/#groups How should [I] relate them? Relate to the User. You get the profile from the User. You get the groups from the User. Relate to the primary, central, important entity. Think of a Profile as an add-on thing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP: while or foreach. I want to save an array of input data which also uses a counter I'm trying to achieve the following I have post data which is an array[] I'm using a foreach to run through the array foreach($images as $image){ update_option( 'image-'. $mycounter .'', $image ); } I need $mycounter to be counting as it runs through the foreach. How can I achieve that. I tried it with a while loop but not working :( Thanks A: You could use the incrementing operator: $mycounter = 0; foreach($images as $image){ update_option( 'image-'. $mycounter .'', $image ); $mycounter++; // increments through each iteration } OR use the unique numerical indices as your counter, assuming the indices are numerical. foreach($images as $index => $image){ update_option( 'image-'. $index .'', $image ); } A: $mycounter = 0; foreach($images as $image){ update_option( 'image-'. $mycounter .'', $image ); $mycounter++; } Like that? A: Have you tried incrementing $mycounter every iteration? $mycounter = 0; foreach($images as $image) { update_option('image-' . $mycounter, $image); $mycounter++; } Or am I misunderstanding the question?
{ "language": "en", "url": "https://stackoverflow.com/questions/7561328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple Jquery conflict I'm new to the whole forum thing, so I'll try my best to describe my problem clearly. I'm trying to use two different jquery scripts on my page, one being Bxslider and the other being Captify. In general, Whenever I try to implement more than one script, they can never work simultaneously. I don't think its a matter of one affecting the other, they just fail to work together AT ALL. My website is couchkumaras.com, I'm only trying out the captify on my local copy, so you'll see I haven't got it on there at the moment. Any answers you guys have will be greatly appreciated, I've had this problem for a while, and I've usually been able to compromise, but if it's a small mistake I'm making, it'd be really useful! Cheers, Finn. A: If you open the error console in your browser (Google for a howto), or use a tool like Firebug (Firefox Addon) or the Chrome web inspector you'll see that there is an error when your script executes: JQuery is not defined [Break On This Error] JQuery.crash=function(x)... < line 549 You've mistyped jQuery as JQuery (there shouldn't be a capital J -- it's lowercase). Using the error console can be a great aid in finding out what parts of the scripts that you're using are not functioning correctly. A: I don't see captify.js being included anywhere in source. if you have access could you stick it in there so I can see what's going awry?
{ "language": "en", "url": "https://stackoverflow.com/questions/7561330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transfer Backup Files from One Domain to Another Domain I need to transfer Backup Files from one Domain to another domain. I have some production databases where I am taking backups every night. I need to transfer those backup file from one domain to another domain and place it in a folder. Then I need to restore those backup files to the Destination Sql server. Thanks in advance...
{ "language": "en", "url": "https://stackoverflow.com/questions/7561335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mootools table pushmany I'm trying to build a table using the Mootools HMTLTable class, specifically using the pushMany method. I have built a sample using the same syntax that they show in the docs at http://mootools.net/docs/more/Interface/HtmlTable#HtmlTable:pushMany, but I can't get the data to display. Is there somethign obvious I'm missing? Thanks A fiddle: http://jsfiddle.net/W2nMn/1/ A: Its an error in the docs, you should just use myTable.pushMany http://jsfiddle.net/W2nMn/2/
{ "language": "en", "url": "https://stackoverflow.com/questions/7561341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Completer of QLineEdit get Memory I have q method that shown at below: void MainWindow::slotResults( const QList<QSqlRecord>& records ) { ui->lineEditWord->setCompleter(0); QStringList wordList; for(int i = 0; i < records.count(); i++) { wordList.append( QString("%1").arg( records.value(i).value(0).toString())); } QCompleter *completer = new QCompleter(wordList, this); // completer->setCaseSensitivity(Qt::CaseInsensitive); ui->lineEditWord->setCompleter(completer); } But, when line ui->lineEditWord->setCompleter(completer) have beeen execited; memory usage increase and when i call this method for several times, memory usage grow up. so how can i release memory from this? Should i remove current completer of lineEdit pls help A: The QCompleter constructor you are using takes a QStringList as parameter. It is certainly (while this is not documented properly), a convenience constructor that creates a QStringListModel filled with the strings passed to the constructor and set this model as the completion model with QCompleter::setModel(). You can update the string list represented by the model using the following code: QStringList originalStringList; originalStringList << "red" <<"orange" << "yellow"; QCompleter *completer = new QCompleter(originalStringList); QStringListModel *stringListModel = qobject_cast< QStringListModel* >(completer->model()); QStringList newStringList; newStringList << "blue" <<"green" << "purple"; stringListModel->setStringList(wewStringList); If you want to be sure of what you are doing, I suggest to create the completer and data model separately: QCompleter *completer = new QCompleter(); QStringListModel *stringListModel = new QStringListModel(); completer->setModel(stringListModel); QStringList originalStringList; originalStringList << "red" <<"orange" << "yellow"; stringListModel->setStringList(originalStringList); In this case, you just have to store the stringListModel as a member of your MainWindow and update the string list each time you pass through the MainWindow::slotResults() method. A: You are allocating a QCompleter on each pass through this method. Unless the QLineEdit is deallocating it this is a memory leak One solution is to store the pointer as a member of MainWindow then delete it in ~MainWindow() another way would be to have a smart pointer member to store it so the memory is automatically deleted when the window goes out of scope. You really shouldn't need to create more than one completer. If you do just remember to delete the previous in whatever way works best for your implementation requirements. A: This isn't documented, but if the old completer has the QLineEdit as parent, when you set a new completer, the old completer is deleted automatically when you call QLineEdit::setCompleter. You just have to create the completer like that: QCompleter *completer = new QCompleter(wordList, ui->lineEditWord); Since you are apparently creating the completer from a SQL query, you could use a QSqlQueryModel or a QSqlTableModel instead of the list of records and pass it to QCompleter constructor, this way, you will only have to create the completer once and call QSqlQueryModel::setQuery or QSqlTableModel::select to update the completer whenever you make any change to that part of the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split a value in one column to two columns I have a column in SQL that I would like to split a column into two columns on select (by a delimiter). For example, the table currently has: --------- Mary - 16 I'd like two columns as the result of the query: -------- -------- Mary 16 Thanks for your help. A: SELECT left_side = RTRIM(SUBSTRING(col, 1, CHARINDEX('->', col)-2)), right_side = LTRIM(SUBSTRING(col, CHARINDEX('->', col) + 2, 4000)) FROM dbo.table; Ah, I see. | characters are column specifiers, not part of the output. Try: SELECT left_side = LTRIM(RTRIM(SUBSTRING(col, 1, CHARINDEX('-', col)-1))), right_side = LTRIM(RTRIM(SUBSTRING(col, CHARINDEX('-', col) + 1, 4000))) FROM dbo.table; A: If your not worried about edge cases, something like this will work: Declare @Var varchar(200) SET @Var = 'Mary - 16' SELECT LEFT(@Var, PATINDEX('%-%', @Var) - 1), Right(@Var, LEN(@Var) - PATINDEX('%-%', @Var)) Just change @Var to your field name in the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: can't edit NSTextField in sheet at runtime When clicking on a button, I'd like to display a sheet with an email+password prompt with options to save and cancel. The UI is all set up, the actions are in place, and the sheet appears and cancels as expected. The problem is that I can't edit either of the NSTextFields at runtime; they appear to disabled, and the OS error sound plays on every key press when the sheet is open. I read on SO that UIActionSheet is appropriate, but this is not an iOS app. The textfields are enabled, and had previously been working in another panel. I made sure that the IBAction links are intact, but I'm otherwise not even sure how to troubleshoot. What about a sheet would cause an otherwise healthy NSTextField to refuse input? // show the sheet -(IBAction)showAccount:(id)sender { [NSApp beginSheet:accountWindow modalForWindow:prefsWindow modalDelegate:self didEndSelector:NULL contextInfo:NULL]; } // cancel/hide the sheet -(IBAction)cancelAccount:(id)sender { [NSApp endSheet:accountWindow]; [accountWindow orderOut:nil]; } Edit: I've just discovered that I can right-click and paste text into each field, but I can't select or delete. It seems like the NSTextFields aren't getting focus and don't receive keyboard input like they usually would. I also forgot to mention that my Save button calls and executes its related method properly. A: It turns out that I haphazardly found the solution, which I will now post for posterity... The view that gets used as the sheet (NSWindow or NSPanel) needs to have a title bar. As soon as I toggled this in Interface Builder's inspector (Window → Appearance → Title Bar checkbox), I recompiled and the NSTextFields highlighted, tabbed, and accepted input like they would in any other view. Not sure why the title bar makes a difference, but there you have it. A: The view does not absolutely have to have a title bar. See Why NSWindow without styleMask:NSTitledWindowMask can not be keyWindow? Which states: If you want a titleless window to be able to become a key window, you need to create a subclass of NSWindow and override -canBecomeKeyWindow as follows: - (BOOL)canBecomeKeyWindow { return YES; } This worked for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Programmatically scroll to a specific position in an Android ListView How can I programmatically scroll to a specific position in a ListView? For example, I have a String[] {A,B,C,D....}, and I need to set the top visible item of the ListView to the index 21 of my String[]. A: The Listview scroll will be positioned to top by default, but want to scroll if not visible then use this: if (listView1.getFirstVisiblePosition() > position || listView1.getLastVisiblePosition() < position) listView1.setSelection(position); A: I have set OnGroupExpandListener and override onGroupExpand() as: and use setSelectionFromTop() method which Sets the selected item and positions the selection y pixels from the top edge of the ListView. (If in touch mode, the item will not be selected but it will still be positioned appropriately.) (android docs) yourlist.setOnGroupExpandListener (new ExpandableListView.OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { expList.setSelectionFromTop(groupPosition, 0); //your other code } }); A: For a SmoothScroll with Scroll duration: getListView().smoothScrollToPositionFromTop(position,offset,duration); Parameters position -> Position to scroll to offset ---->Desired distance in pixels of position from the top of the view when scrolling is finished duration-> Number of milliseconds to use for the scroll Note: From API 11. HandlerExploit's answer was what I was looking for, but My listview is quite lengthy and also with alphabet scroller. Then I found that the same function can take other parameters as well :) Edit:(From AFDs suggestion) To position the current selection: int h1 = mListView.getHeight(); int h2 = listViewRow.getHeight(); mListView.smoothScrollToPositionFromTop(position, h1/2 - h2/2, duration); A: If someone looking for a similar functionality like Gmail app, The Listview scroll will be positioned to top by default. Thanks for the hint. amalBit. Just subtract it. That's it. Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { int h1 = mDrawerList.getHeight(); int h2 = header.getHeight(); mDrawerList.smoothScrollToPosition(h2-h1); } }, 1000); A: If you want to jump directly to the desired position in a listView just use listView.setSelection(int position); and if you want to jump smoothly to the desired position in listView just use listView.smoothScrollToPosition(int position); A: For a direct scroll: getListView().setSelection(21); For a smooth scroll: getListView().smoothScrollToPosition(21); A: Handling listView scrolling using UP/ Down using.button If someone is interested in handling listView one row up/down using button. then. public View.OnClickListener onChk = new View.OnClickListener() { public void onClick(View v) { int index = list.getFirstVisiblePosition(); getListView().smoothScrollToPosition(index+1); // For increment. } }); A: This is what worked for me. Combination of answers by amalBit & Melbourne Lopes public void timerDelayRunForScroll(long time) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { try { int h1 = mListView.getHeight(); int h2 = v.getHeight(); mListView.smoothScrollToPositionFromTop(YOUR_POSITION, h1/2 - h2/2, 500); } catch (Exception e) {} } }, time); } and then call this method like: timerDelayRunForScroll(400); A: it is easy list-view.set selection(you pos); or you can save your position with SharedPreference and when you start activity it get preferences and setSeletion to that int A: -If you just want the list to scroll up\dawn to a specific position: myListView.smoothScrollToPosition(i); -if you want to get the position of a specific item in myListView: myListView.getItemAtPosition(i); -also this myListView.getVerticalScrollbarPosition(i);can helps you. Good Luck :) A: You need two things to precisely define the scroll position of a listView: To get the current listView Scroll position: int firstVisiblePosition = listView.getFirstVisiblePosition(); int topEdge=listView.getChildAt(0).getTop(); //This gives how much the top view has been scrolled. To set the listView Scroll position: listView.setSelectionFromTop(firstVisiblePosition,0); // Note the '-' sign for scrollTo.. listView.scrollTo(0,-topEdge); A: Put your code in handler as follows, public void timerDelayRunForScroll(long time) { Handler handler = new Handler(); handler.postDelayed(new Runnable() { public void run() { try { lstView.smoothScrollToPosition(YOUR_POSITION); } catch (Exception e) {} } }, time); } and then call this method like, timerDelayRunForScroll(100); CHEERS!!! A: I found this solution to allow the scroll up and down using two different buttons. As suggested by @Nepster I implement the scroll programmatically using the getFirstVisiblePosition() and getLastVisiblePosition() to get the current position. final ListView lwresult = (ListView) findViewById(R.id.rds_rdi_mat_list); ..... if (list.size() > 0) { ImageButton bnt = (ImageButton) findViewById(R.id.down_action); bnt.setVisibility(View.VISIBLE); bnt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(lwresult.getLastVisiblePosition()<lwresult.getAdapter().getCount()){ lwresult.smoothScrollToPosition(lwresult.getLastVisiblePosition()+5); }else{ lwresult.smoothScrollToPosition(lwresult.getAdapter().getCount()); } } }); bnt = (ImageButton) findViewById(R.id.up_action); bnt.setVisibility(View.VISIBLE); bnt.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(lwresult.getFirstVisiblePosition()>0){ lwresult.smoothScrollToPosition(lwresult.getFirstVisiblePosition()-5); }else{ lwresult.smoothScrollToPosition(0); } } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561353", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "165" }
Q: Can I get the progress of a git clone command, issued in grit, output to stdout? I'm fairly confident this is either not possible or I'm missing an obvious option, but after consulting grit's Git class, the gist linked in this SO post, and the other grit tagged questions on SO, I'm coming up blank. I'm using grit for a series of rake tasks that install my application. One of these tasks clones a few repositories. Using the code in the linked gist as an example, this is the output of git cloning in grit (should work out of the box after a gem install grit in irb, ruby 1.9.2): > require 'grit' > gritty = Grit::Git.new('/tmp/filling-in') => #<Grit::Git:0x007f93ae105df8 @git_dir="/tmp/filling-in", @work_tree="/tmp/filling-in", @bytes_read=0> > gritty.clone({:quiet => false, :verbose => true, :progress => true, :branch => '37s', :timeout => false}, "git://github.com/cookbooks/aws.git", "/tmp/aws") => "Cloning into /tmp/aws...\n" My question is this: Can I recover the rest of the clone command's stdout, preferably while the clone is actually happening? The "Cloning into /tmp/aws...\n" is the first line of output, and is only returned once the clone completes. A secondary question would be: If it's not possible to recover the clone's progress while it's happening with grit, is there another way to show progress of the command while it happens? My concern is a few of our repositories are quite large, and I'd like to give my rakefile's users something so they don't conclude the script is simply hanging while trying to communicate with the remote. For reference, the "normal" out put of the git clone command would be: $ git clone git://github.com/cookbooks/aws.git /tmp/test-aws Cloning into /tmp/test-aws... remote: Counting objects: 12364, done. remote: Compressing objects: 100% (3724/3724), done. remote: Total 12364 (delta 7220), reused 12330 (delta 7203) Receiving objects: 100% (12364/12364), 5.92 MiB | 70 KiB/s, done. Resolving deltas: 100% (7220/7220), done. Quick note: Some of the functionality described here, namely :process_info requires an up-to-date version of the gem, which hasn't been updated since 23 Jan 2011, as of today, 26 Sept 2011 (many thanks to Daniel Brockman for pointing that out, below). You'll have to clone it from github and build it manually. SOLUTION Clone passes the correct information to stderr if you give it :process_info and :progress (my original example failed because I had an outdated gem). The following is working code. You need to build the gem manually for reasons described above, at least at this time. > require 'grit' > repo = Grit::Git.new('/tmp/throw-away') > process = repo.clone({:process_info => true, :progress => true, :timeout => false}, 'git://github.com/cookbooks/aws.git', '/tmp/testing-aws-again') # output supressed > print process[2] # i.e. the stderr string of the output remote: Counting objects: 12364, done. remote: Compressing objects: 100% (3724/3724), done. remote: Total 12364 (delta 7220), reused 12330 (delta 7203) Receiving objects: 100% (12364/12364), 5.92 MiB | 801 KiB/s, done. Resolving deltas: 100% (7220/7220), done. A: The reason you’re only getting the first line of output is that the rest of it is sent to stderr, not stdout. There is a :process_info option you can pass to get both exit status, stdout and stderr. See https://github.com/mojombo/grit/blob/master/lib/grit/git.rb#L290.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Spring @Transaction not starting transactions I am using Spring 3 with Hibernate 3. I am trying to configure Spring declarative transaction, but no matter what I try, Spring transaction is not getting started. Here is my configuration File: applicationContext-hibernate.xml <tx:annotation-driven transaction-manager="txManager" /> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="mdbDataSource" class="org.apache.commons.dbcp.BasicDataSource"> ... </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="mdbDataSource" /> <property name="annotatedClasses"> ..... </bean> I have a class ServiceLocatorImpl which implements ServiceLocator interface @Service("serviceLocator") @Transactional public class ServiceLocatorImpl implements ApplicationContextAware, Serializable, ServletContextAware, ServiceLocator { public ResultObject executeService( Map objArgs ) { if(TransactionSynchronizationManager.isActualTransactionActive()) { LOGGER.debug("ServiceLocator:executeService - Active transaction found"); } else { LOGGER.error("No active transaction found"); } ...... } .... } It seems to me that all my configuration is correct. But when executeService method is called, TransactionSynchronizationManager.isActualTransactionActive() is always returning false. Please help me solving this problem. Let me know if any more information required. Update: I have wired the ServiceLocator into one of the other classes, as follows: @Autowired private ServiceLocator serviceLocator; // ServiceLocator is interface I am using Spring 3.0.0 version. executeService() is one the method defined in the ServiceLocator interface. I updated the code to throw exception instead of just logging an error. Following is the stack trace, I don't see any proxy creation in this trace. Please help. java.lang.RuntimeException: No active transaction found at com.nihilent.venice.common.service.ServiceLocatorImpl.logTransactionStatus(ServiceLocatorImpl.java:102) at com.nihilent.venice.common.service.ServiceLocatorImpl.executeService(ServiceLocatorImpl.java:47) at com.nihilent.venice.web.controller.CommonController.handleRequest(CommonController.java:184) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552) at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302) at org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:709) at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:680) at org.apache.jsp.index_jsp._jspService(index_jsp.java:57) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:176) at org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145) at org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92) at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:381) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.nihilent.venice.web.filter.DyanamicResponseHeaderFilter.doFilter(DyanamicResponseHeaderFilter.java:33) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.opensymphony.module.sitemesh.filter.PageFilter.parsePage(PageFilter.java:118) at com.opensymphony.module.sitemesh.filter.PageFilter.doFilter(PageFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:343) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.nihilent.venice.web.filter.RequestFilter.doFilter(RequestFilter.java:44) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) at java.lang.Thread.run(Thread.java:619) Update [Solved] I got the issue fixed. Before giving the answer as how it was fixed, I need to provide some more information. I am using Spring MVC in my project. The control DispatchServlet is configured in the web.xml. This front controller has a configuration xml file abc-servlet.xml (abc being the servlet name in web.xml). I have other spring configuration files too which are defined as context-param in web.xml. One of the file is applicationContext-hibernate.xml file. I defined the txManager and <tx:annotation-driven />, in the applicationContext-hibernate.xml file. Today I was wondering whether @Autowired and @Transactional work with together, so I Google the information, and found this thread http://forum.springsource.org/showthread.php?48815-Repository-Autowired-Transaction-not-returning-proxy-and-causes-exception The thread talk about similar problem, and this solves the problem. I implemented one of the suggestion and added <tx:annotation-driven .../> to my servlet's application context xml and it fixes the problem. Thinking that I also moved my <tx:annotation-driven /> into abc-servlet.xml file and it worked. My logs are now shoulding the required messages: [venice] DEBUG [http-8080-1] 27 Sep 2011 14:24:06,312 ServiceLocatorImpl.logTransactionStatus(100) | ServiceLocator:executeService - Active transaction found Thanks to everyone for Helping. May be this information will be helpful to someone. I would still like to hear about the explanation as why it was not working earlier. A: My guess would be that you're trying to do something like: ServiceLocator locator = new ServiceLocatorImpl(); ... locator.executeService(someMap); and then being surprised that there's no transaction. Transaction management and all other Spring services only apply to beans in the application context*. You need to get your instance from the context one way or another instead of just instantiating one. Or else your locator bean is in a separate application context than the one where you declare tx:annotation-driven. *Unless you're using AspectJ build- or load-time bytecode weaving with Spring. Edit: The problem was exactly what I said (the second part). You create two application contexts. You were creating your ServiceLocator in the first one, but you only enabled annotation-driven transactions in the second one. You appear to not understand the boundaries between the contexts. Generally--at least in my experience--the "business" beans, like your ServiceLocator, live in the root context, which is the one started by the ContextLoaderListener and configured via contextConfigLocation. Controllers and other beans that configure or are used by a DispatcherServlet live in another context associated with that servlet which is configured by the *-servlet.xml file. This context becomes a child context of the root context, and the beans in it can be injected with beans from the root context, though not vice versa. From my perspective, you've broken things worse than they were before by adding tx:annotation-driven to the child context associated to your DispatcherServlet. Instead, you should ensure that the ServiceLocator is created in the root context, where transactional services are already available and are where they belong. A: You should simply rename your "txManager" to "transactionManager". From the EnableTransactionManagement's JavaDoc: …in the XML case, the name is "transactionManager". The <tx:annotation-driven/> is hard-wired to look for a bean named "transactionManager" by default…
{ "language": "en", "url": "https://stackoverflow.com/questions/7561360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: What can cause a program to run much faster the second time? Something I've noticed when testing code I write is that long-running operations tend to run much longer the first time a program is run than on subsequent runs, sometimes by a factor of 10 or more. Obviously there's some sort of cold cache/warm cache issue here, but I can't seem to figure out what it is. It's not the CPU cache, since these long-running operations tend to be loops that I feed a lot of data to, and they should be fully loaded after the first iteration. (Plus, unloading and reloading the program should clear the cache.) Also, it's not the disc cache. I've ruled that out by loading all data from disc up-front and processing it afterwards, and it's the actual CPU-bound data processing that's going slowly. So what can cause my program to run slow the first time I run it, but then if I close it and run it again, it runs dramatically faster? I've seen this in several different programs that do very different things, so it seems to be a general issue. EDIT: For clarification, I'm writing in Delphi, though I don't really think this is a Delphi-specific issue. But that means that whatever the problem is, it's not related to JIT issues, garbage collection issues, or any of the other baggage that managed code brings with it. And I'm not dealing with network connections. This is pure CPU-bound processing. One example: a script compiler. It runs like this: * *Load entire file into memory from disc *Lex the entire file into a queue of tokens *Parse the queue into a tree *Run codegen on the tree to produce bytecode If I feed it an enormous script file (~100k lines,) after loading the entire thing from disc into memory, the lex step takes about 15 seconds the first time I run, and 2 seconds on subsequent runs. (And yes, I know that's still a long time. I'm working on that...) I'd like to know where that slowdown is coming from and what I can do about it. A: Even (especially) for very small command-line program, the issue can be the time it takes to load the process, link to dynamically-linked libraries etc. I believe modern operating systems avoid repeating a lot of this work if the same program is run twice at once, or repeatedly. I wouldn't dismiss CPU cache so easily, as well. Level 0 cache is very relevant for inner loops, but much less so for a second run of the same application. On my cheap Athlon 2 X4 645 system, there's 64K + 64K (data + instruction) level 0 cache per core - not exactly a huge amount of memory. Level 1 cache is IIRC 512K per core, so less likely to be dirtied to complete irrelevance by the O/S code needed to start up a new run of the program, calls to operating system services and standard libraries, etc. Level 2 cache (on CPUs that have it - my Athlon 2 doesn't, IIRC) is larger still, and there may be some even higher level and larger cache provided by the motherboard/chipset. There's at least one other kind of cache - branch prediction tables. Though I'd have thought they'd be dirtied to irrelevance even quicker than the level 0 cache. I generally find that unit test programs run many times slower the first time. However, the larger and more complex the program, the less significant the effect. For some time now, performance of applications has often been considered non-deterministic. Although it isn't strictly true, the performance is determined by so many hard-to-predict factors that it's a good model. For example, if the CPU is a bit warm, the clock speed may be reduced to prevent overheating. And the temperature varies at different parts of the chip, with changes conducting across the chip in complex ways. As changes in clock speed and the different demands of different pieces of code alter the patterns of changing temperature, there's a clear potential for chaotic (as in chaos theory) behaviour. On some platforms, I wouldn't be surprised if the first run of the program got the processor to run if it's "fast" (rather than cool/quiet) mode, and that meant that the beginning of the second run benefitted from that speed boost as well as the end. However, this would be a tricky one - it would have to be a CPU-intensive program, and if your cooling is inadequate, the processor may then slow down again to avoid overheating. A: I'd guess it's all your libraries/DLLs. These are usually loaded on-demand at run-time, so the first time your program runs the OS will have to read them all from disk. Once read, though, they'll stay loaded unless your system starts running low on memory. So if you run the same program several times in succession, the first run takes the brunt of the load time, and the other runs benefit from the pre-loaded libraries. A: I usually experienced the contrary: for computation intensitive work (if anti virus is not working), I only have a 5-10% diff between calls. For instance, the 6,000,000 regression tests run for our framework have a very constant time of running, and it's very disk and CPU intensive work. I really don't believe of a CPU cache or pipelining / branch prediction issue either, since both processed data and code seem to be consistent, as you wrote. If anti virus is off, it may be about OS thread settings: did you try to change the process CPU affinity and priority? This should be very specific to the process you are running. Without any actual source code to reproduce it, it's almost impossible to tell what's happening with you. How many threads are there? What is the HW configuration (isn't there any Intel CPU boost there - are you using a laptop, and what are your energy settings)? Is it using CPU/FPU/MMX/SSE2 (e.g. MMX and FPU do not mix)? Does it move a lot of data, or process some existing data? Does your SW depends on external libraries (even some Windows libraries may need some time to initialize)? How do you use memory (did you try to pre-allocate the memory; or on a multi-threaded application, did you try using a scaling MM instead of FastMM4)? I think using a sample profiler may not help so much, since it will change the general CPU core use, but it's worth trying in all cases. I'd better rely on logging profiling - see e.g. this class or you may write your own timestamps to find where the timing changes in your app. AFAIK it has always been written that, when benchmarking, the first run of an application shall never be taken in account. Computer systems are so complex nowadays, that the first time, all the internal (SW and HW) plumbing is to be purged - so you shall not drink the first water coming out of your tap when you come back from 1 month of travel. ;) A: Other factors I can think of would be memory-alignment (and the subsequent cache line fills), but say there are 2 types : perfect alignment (being fastest) and imperfect (being slower), one would expect it to occur irregularly (depending on how memory is laid out). Perhaps it has something to do with physical page layout? As far as I know, each memory-access goes through the MMU page table entries, so dispersed physical pages could be slower than consecutive pages. (Just a wild guess, this one) Another thing I haven't seen mentioned yet, is on which core(s) your process is running - especially on hyper-threaded CPU's, running on the slower of the two cores might have a negative impact. Try setting the processor affinity mask on one and the same core for every run, and see if that impacts the measured runtime differences between first and subsequent runs. By the way - how do you define 'first run'? Could it be that you've just compiled the executable? In that case (and I'm just guessing again here), some process (either the OS, a virus-scanner, or even some root-kit) might be busy analyzing your executable's behaviour, which might be skipped once the executable has been analyzed before. You could try to prove that by changing some random unimportant byte of your executable between runs, and see if that impacts the runtime negatively again? Please post a summary once you figured out the cause(s) - this might help others too. Cheers! A: Just a random guess... Does your processor support adaptive frequency? Maybe it's just the processor that doesn't have time to adapt its frequency on the first run, and is running full speed on second one. A: Three things to try: * *Run it in a sampling profiler, including a "cold" run (first thing after a reboot). Should usually be enough. *Check memory usage, does it grow so high (even transiently) the OS would have to swap things out of RAM to make room for your app? That alone could be an explanation for what you're seeing. Also look at the amount of free RAM you have when you start your app. *Enable system performance tools and check the I/O counters or file accesses, and make sure under FileMon / Process Explorer that you don't have some file or network accesses you've forgotten about (leftover log/test code) A: There are lots of things that can cause this. Just as one example: if you're using ADO.NET for data access with connection pooling turned on (which is the default), the first time your application runs it will take the hit of creating the database connection. When your app is closed, the connection is maintained in its open state by ADO.NET, so the next time your app runs and does data access it will not have to take the hit of instantiating the connection, and thus will appear faster. A: Guessing your using .net if im wrong you could ignore most of my ideas... Connection pooling, JIT compilation, reflection, IO Caching the list goes on and on.... Try testing smaller portions of the code to see what parts change performance the most... You could try ngen'ing your assemblies as this removes the JIT compilation. A: where that slowdown is coming from and what I can do about it. I would speak about quick execution the next times can from from performance caching * *Disk internal cache (8MB or more) *Windows applicationDependencies (as DLL)/Core cache *CPU cache L3 (or L2 if some programming loop are small enough) So you see that the first time you do not benefits from these caching systems.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: 1->2->3 activities, at third "back button" I want to go to the first one I have a MainActivity, then I call SecondActivity (where I choose a file whose data is given to ThirdActivity. If back button is pushed, I want the app to go back yo MainActivity and not SecondActivity. How can I do that? A: There are two ways to do it. * *In SecondActivity, call finish() immediately after you start Activity 3. *Pass in the NO_HISTORY flag in the Intent for SecondActivity when starting it in MainActivity. A: Just after you call startActivity with the Intent for activity 3, call finish in activity 2: //in activity 2 Intent intent = new Intent(...); startActivity(intent); finish(); A: You could also override onKeyPressed() (or whatever it's called) for the back button and startActivity().
{ "language": "en", "url": "https://stackoverflow.com/questions/7561367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android AutoCompleteTextView displays suggestions after unrelated button is clicked I am having an issue where my AutoCompleteTextView is showing its suggestions if keyboard focus is in the ACTV and a button in the activity is clicked. The best I can seem to do is call .dismissDropDown() after it appears, but that seems sloppy. How can I keep it from appearing in the first place when the button is clicked? A: As mentioned above, this was due to me adding an element to the ArrayAdapter adapter of the ACTV. I just went ahead and added the new string to the original ArrayList used for initially creating the ArrayAdapter, then created a completely new AA and set that as the ACTV's adapter. That method of dynamic updating fixed the problem of the autocomplete list appearing when it wasn't supposed to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the difference in: Import module & From module import module? Here is my program that takes a list a words and sorts them from longest to shortest and breaks ties with the random module. import random def sort_by_length1(words): t = [] for word in words: t.append((len(word), random(), word)) t.sort(reverse = True) res = [] for length, randomm, word in t: res.append(word) return res I get this error: TypeError: 'module' object is not callable But when I do: from module import module It works?? Why is that? A: from random import random is equivalent to import random as _random random = _random.random so if you only do import random you have to use random.random() instead of random() A: random module has a random function. When you do import random you get the module, which obviously is not callable. When you do from random import random you get the function which is callable. That's why you don't see the error in the second case. You can test this in your REPL. >>> import random >>> type(random) module >>> from random import random >>> type(random) builtin_function_or_method A: from random import random is equivalent to: import random # assigns the module random to a local variable random = random.random # assigns the method random in the module random You can't call the module itself, but you can call its method random. Module and method having the same name is only confusing to humans; the syntax makes it clear which one you mean. A: When you invoke the command, import random You are importing a reference the module, which contains all the functions and classes. This reference is now in your namespace. The goodies inside the random module can now be accessed by random.func(arg1, arg2). This allows you to perform the following calls to the random module: >>> random.uniform(1, 5) 2.3904247888685806 >>> random.random() 0.3249685500172673 So in your above code when the python interpreter hits the line, t.append((len(word), random(), word)) The random is actually referring to the module name and throws an error because the module name isn't callable, unlike the function you're looking for which is inside. If you were to instead invoke from random import random You are adding a reference in your name space to the function random within the module random. You could have easily have said from random import randint which would let you call randint(1, 5) without a problem. I hope this explains things well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery ajax function call not made I am having problems calling the function callpage Here is the code were I am trying to call the function. I got a label that when click I want to call callpage: $('.gulemenu label, .payload label').toggle(function(){ $(this).find('input[type="checkbox"]').prop('checked',true); $.(this).callpage(); }, function(){ $(this).find('input[type="checkbox"]').prop('checked',false); $.(this).callpage(); }); $('.gulemenu input, .payload label').bind('click',function(e){ e.stopPropagation(); }); My callpage function: function callpage() { $('#formcontent').empty().html('<p style="margin-top:20px;text-align:center;font-family:verdana;font-size:14px;">Vent venligst, henter webhosts.</p><p style="margin-top:20px;margin-bottom:20px;text-align:center;"><img src="../images/ajax.gif" /></p>'); var form = $('form#search'); $.ajax({ type: form.attr('method'), url: form.attr('action'), data: form.serialize(), success:function(msg){ $('#formcontent').html(msg); }}) } A: Hope it works $(this).find('input[type="checkbox"]').prop('checked',true).end().callpage(); A: <script type="text/javascript"> var slider = $("#mySliderSelector").slider({whatever:'you need'}); $('.gulemenu label, .payload label').click(function(event){ e.stopPropagation(); var checkbox = $(this).find(":checkbox"); //child checkbox inputs. you are sure there is only one correct? var checked = checkbox.prop("checked"); checkbox.prop("checked", !checked); slider.trigger("slidestop"); //jQuery-ui documentation for slideStop event. }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7561372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split JavaScript array into smaller ones and get frequency of each value I have the following big array: var divs = [ {class:'A', top:0, left:0}, {class:'B', top:50, left:60}, {class:'C', top:30, left:10}, {class:'D', top:100, left:180}, {class:'E', top:80, left:50}, {class:'F', top:100, left:200}, {class:'G', top:50, left:80} ]; I'd like to isolate just the top values. I tried using split() but I might not be using it correctly because nothing returns as expected. Once the top values are isolated into their own smaller array I want to iterate over it and find the frequency of occurrence for each value. Can I please get some help? A: var divs = [ {class:'A', top:0, left:0}, {class:'B', top:50, left:60}, {class:'C', top:30, left:10}, {class:'D', top:100, left:180}, {class:'E', top:80, left:50}, {class:'F', top:100, left:200}, {class:'G', top:50, left:80} ]; var topsy = {}; for(var i = 0, max = divs.length; i < max; i++){ var a = divs[i]; topsy[a.top] = (topsy[a.top] + 1) || 1; } At this point, you will have a topsy that has all of the tops in there, with the key being the top, and the value being the number of times it was in there. To get a list of the keys, you say: Object.keys(topsy); Object.keys doesn't work in IE. You will end up with topsy = { 0: 1, 30: 1, 50: 2, 80: 1, 100: 2 } Then you can say Object.keys(topsy);//[3,30,50,80,100] You got your analysis and array done at one time. A: You can use .map to filter, and .forEach to iterate, although both are not available on older browsers. var freqs = {}, tops = divs.map(function(value) { return value.top; // map the array by only returning each 'top' }); tops.forEach(function(value) { // iterate over array, increment freqs of this top // or set to 1 if it's not in the object yet freqs[value] = freqs[value] + 1 || 1; }); // tops: [0, 50, 30, 100, 80, 100, 50] // freqs: {0: 1, 30: 1, 50: 2, 80: 1, 100: 2} A: You have to iterate through the array, and store the top values in a temporary variable. Choosing the variable to be an Array is wise, because an array can easily be looped through. var test = []; for(var i=0; i<divs.length; i++){ test.push(divs[i].top); } //test is an array which holds all value of "top" A: var divs = [ {class:'A', top:0, left:0}, {class:'B', top:50, left:60}, {class:'C', top:30, left:10}, {class:'D', top:100, left:180}, {class:'E', top:80, left:50}, {class:'F', top:100, left:200}, {class:'G', top:50, left:80} ]; var tops = []; for(var i = 0, l = divs.length; i < l; i++) { tops.push(divs[i].top); }; tops; // [ 0, 50, 30, 100, 80, 100, 50 ] A: var divs = [ {class:'A', top:0, left:0}, {class:'B', top:50, left:60}, {class:'C', top:30, left:10}, {class:'D', top:100, left:180}, {class:'E', top:80, left:50}, {class:'F', top:100, left:200}, {class:'G', top:50, left:80} ]; var divsTop = []; for(var i in divs) divsTop.push({"class":divs[i].class,"top":divs[i].top}); You can iterate through and push each (modified) object to another array.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: RoR Sorcery Routing Problem. Please help? This has been driving me mad for two days now and any insight is very much appreciated. Running Sorcery for authentication and everything seems to be setup fine, however when I go to register a user and enter submit I get a Action Controller: Exemption caught Routing Error No route matches "/pages/register" However, if I visit localhost:3000/pages/register it shows up fine. I've tried to change the users controller to redirect_to root_url (and yes the root is mapped in routes) but no change. Any help??? Thank you! A: Checkout the verbs. Most likely it tries to find a POST, while you have only GET defined
{ "language": "en", "url": "https://stackoverflow.com/questions/7561377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CustomValidator not firing in control So here is the issue. I have a DropDownList in a .ascx control with a CustomValidator on it. This control has a ValidationGroup set by a property in the PageLoad. The button that triggers the validation is in a another file that uses this control. The problem is that the server side validation is never getting fired. I add breakpoints in it and they are never hit. Anyone have any thoughts about what is going on? Here is the code: Dropdown.ascx: <asp:DropDownList ID="ddlQuestions" runat="server"> </asp:DropDownList> <asp:CustomValidator runat="server" ID="cvddlQuestions" OnServerValidate="cvddlQuestions_ServerValidate" ErrorMessage="* Parent question is required." ValidateEmptyText="true" Display="Dynamic" /> </p> </div> Code behind: protected void Page_Load(object sender, EventArgs e) { cvddlQuestions.ValidationGroup = ValidationGroup; //ValidationGroup is a property in the parent file that is being set on PageLoad } protected void cvddlQuestions_ServerValidate(object sender, ServerValidateEventArgs args) { args.IsValid = false;// (ddlQuestions.SelectedValue != "-1"); } In the parent file that uses Dropdown.ascx I have this button: <asp:LinkButton ID="btnQuestionAdd" runat="server" OnClick="btnQuestionAdd_Click" ValidationGroup="editQuestion" CommandName="add" /> Parent files code behind: protected void btnQuestionAdd_Click(object sender, EventArgs e) { Page.Validate("editQuestion"); if (Page.IsValid) //ALWAYS SEEMS TO BE TRUE { //Do something } } When I add a client validation function to the customvalidator it fires no problem. But the page is ALWAYS returning as valid. I have tried adding a ControlToValidate and setting ValidateEmptyText="true" and I still get the same result. What am I missing? A: Set DropDownList's CausesValidation-Property to true, default is false. <asp:DropDownList ID="ddlQuestions" CausesValidation="True" CssClass="if" DataTextField="Question" DataValueField="iD" runat="server"> And you also have to set it's Validationgroup property accordingly(see property below). A side note: You don't need the member variable ValidationGroup in your UserControl. Just use a public property ValidationGroup that directly set/get the Validator's ValidationGroup property. On this way you don't need to set it on every postback since it's stored in ViewState anyway and you could also set it in the UserControl itself if you want. public string ValidationGroup { get { return cvddlQuestions.ValidationGroup; } set { cvddlQuestions.ValidationGroup = value; ddlQuestions.ValidationGroup=value; } } A: It turns out that the answer was something incredibly stupid. When I instantiated the control that all this code was within I had to set the ValidationGroup property on the front end rather than the back end. Lets say the code I posted was within a .ascx file called QuestionControl.ascx. After registering the control on my page I had to write the following: <asp:QuestionControl runat="server" id="qcPage" ValidationGroup="editQuestion" /> No idea why saying: qcPage.ValidationGroup = "editQuestion"; didn't work since the property was only a string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: basics steps in converting xml file to html file I would like convert a xml file to a html file. Where i can find a step by step tutorial (for linux) to do this in shell script, or which are the steps to follow. Sorry for the very basic question, but i am an absolute begginer on this. thanx A: The basic tools to do this is XSLT. XSLT is a language that you can use to describe how XML elements should be converted into HTML elements. Once you have an XSLT files that suits your need (you will have to write it), you can use the xsltproc utility to convert that XML files into HTML files. How to write the XSLT transformation files depends on the exact kind of XML file you must translate. There are already-made XSLT-to-HTML transformation files for many formats, search for "[your format] xslt to html". You can learn more about XSLT in W3Schools tutorials. The xsltproc utility is available for most Linux distributions. A: You can use XSLT to map XML tags to HTML tags or fragments. There is no step-by-step guide on how to do this since the exact XSLT stylesheet to create depends on both what your XML looks like and what you want your HTML to look like. Once you have your stylesheet you can use xsltproc (part of libxslt) from the command line, or you can use the XSLT facilities available to most programming languages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Make style inline using jQuery Im experimenting with setting up a automatic way of converting clean stylesheet based designs to ugly inline styled design (for a newsletter editor). Is it possible to get all the styles that applies to an element (div, p, span, h1, h2 etc.) and apply them to that element as inline? So instead of having my style nice and beautiful like this in a stylesheet: #topHeader { color: #222; background: red; width: 210px; height: 110px;} Having it be inline like this: <div id="topHeader" style="color: #222; background: red; width: 210px; height: 110px;"> If anyone knows if this is at all possible, please send me in the right direction if you can. Thanks anyway :) A: This may be interesting to you: * *IE: currentStyle *Others: getComputedStyle A: You could possibly do this using the .style member of the DOM element you're referencing. Using your example, maybe something along these lines (untested): var el = document.getElementById('topHeader'); var styles = new Array(); for (var key in el.style) { // You'll probably need to do some more conditional work here... if (el.style[key]) { styles.push(key + ': ' + el.style[key]); } } el.setAttribute('style', styles.join('; ')); A: You could iterate the document's styleSheets and rules: $.each(document.styleSheets, function() { $.each(this.cssRules || this.rules, function() { var style = {}; var styles = this.cssText.split(/;\s*/g); $.each(styles, function() { var parts = styles.split(/\:\s*/g); style[parts[0]] = parts[1]; }); $(this.selectorText).css(style); }); }); Not all browsers expose .selectorText, and .cssText will require browser-specific parsing. Hopefully this is enough to point you in the right direction. A: I've used the following with moderate success: $('#parentidhere').find('*').each(function (i, elem){elem.style.cssText=document.defaultView.getComputedStyle(elem,"").cssText;}); Certain styling like background selectors for more complex styling still seem to vanish though, I haven't been able to figure out why yet. Also this won't work in older browsers, but in my case that doesn't matter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem with apache2 rewrite rule (mod_rewrite) I'm having problems with mod_rewrite and apache2. I want to do this: domain.com/{username}/{everything_else} to domain.com/users/{username}/{everything_else} {username} is everithing before first "/" and {everything_else} is everything after the first "/" simbol (may contain other "/", the exact number vary). I tried unsuccessfully this: RewriteRule ^(.*)/(.*)$ /users/$1/$2 [L,NC] RewriteRule ^([^/]+)/(.*)$ /users/$1/$2 [L,NC] this works only if {everything_else} doesn't contain other slashes RewriteRule ^([^/]+)/([^/]*) users/$1/$2 [L,NC] Would it be possible to make something like this? A: Give this a try: RewriteRule ^(.+?)/(.*)$ /users/$1/$2 The ? in the first capturing group means: capture as less characters as possible (so until the first /). The rest is captured as-is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Output issue Java Ok i have finally worked out this problem but i have one issue remaining, when i am entering the string in upon being asked, IF i put any spaces in the number i enter when the program runs it turns those spaces into the number 9 in my output, if i do not use spaces everything runs fine,any ideas as to how i can stop the 9 being added into my spaces? Thanks in advance. package chapter_9; import java.util.Scanner; public class Nine_Seven { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a string: "); String string = input.nextLine(); string = string.toUpperCase(); for (int i = 0;i<string.length();i++){ if(Character.isDigit(string.charAt(i))) System.out.print(string.charAt(i)); else System.out.print(getNumber(string.charAt(i))); } } public static int getNumber(char uppercaseLetter){ if (uppercaseLetter == 'A' || uppercaseLetter == 'B' || uppercaseLetter == 'C') return 2; else if (uppercaseLetter == 'D' || uppercaseLetter == 'E' || uppercaseLetter == 'F') return 3; else if (uppercaseLetter == 'G' || uppercaseLetter == 'H' || uppercaseLetter == 'I') return 4; else if (uppercaseLetter == 'J' || uppercaseLetter == 'K' || uppercaseLetter == 'L') return 5; else if (uppercaseLetter == 'M' || uppercaseLetter == 'N' || uppercaseLetter == 'O') return 6; else if (uppercaseLetter == 'P' || uppercaseLetter == 'Q' || uppercaseLetter == 'R' || uppercaseLetter == 'S') return 7; else if (uppercaseLetter == 'T' || uppercaseLetter == 'U' || uppercaseLetter == 'V') return 8; else return 9; } } Output example: Enter a string: 597 6630 597*9*6630 A: Well look at what getNumber() does - if it doesn't match any of the cases you've specified, it returns 9. Options: * *Change it to return a different number explicitly for space *Change the calling code to not call getNumber() if the value is ' '. I would also recommend refactoring the calling code to only call charAt(i) once, just for the sake of tidiness. For example, you might want: for (int i = 0; i < string.length(); i++){ char c = string.charAt(i); if (Character.isDigit(c) || c == ' ') { System.out.print(c); } else { System.out.print(getNumber(c)); } } As noted in comments, getNumber() can also be written with a simple switch/case: public static int getNumber(char uppercaseLetter) { switch (upperCaseLetter) { case 'A': case 'B': case 'C': return 2; case 'D': case 'E': case 'F': return 3; case 'G': case 'H': case 'I': return 4; case 'J': case 'K': case 'L': return 5; case 'M': case 'N': case 'O': return 6; case 'P': case 'Q': case 'R': case 'S' return 7; case 'T': case 'U': case 'V': return 8; default: return 9; } } (Obviously you could stack the cases vertically should you want to, as well...) A: Add an if statement between else and return 9; that only outputs 9 for W,X,Y,Z and append else return ""; A: Slightly off-topic but still important: big switch statements like this are frequently a suggestion that you are missing some kind of object abstraction. I love enums for situations like this, so I would encapsulate this logic in an enum, perhaps like this: public enum PhoneDigit { Zero(""), One(""), Two("ABC"), Three("DEF"), Four("GHI"), Five("JKL"), Six("MNO"), Seven("PQRS"), Eight("TUV"), Nine(""); private final String letters; private PhoneDigit(String letters) { this.letters = letters; } public boolean hasLetter(char character) { return letters.contains(String.valueOf(character)); } public PhoneDigit valueOf(char character) { for (PhoneDigit digit : values()) { if (digit.hasLetter(character)) { return digit; } } return null; } } This code is very easy to test, it's reusable in other parts of your system, etc. Although my "valueOf" method is not as efficient as a switch statement, you can easily improve this later should it turn out to matter, which is highly unlikely. Now you can add/test other methods like getPhoneNumberFromString(String), boolean isPhoneDigit(char) etc to this object, and not only are the methods very convenient to test, but it makes logical sense to store all of these methods in this location. Your code will be easier to read, the sun will shine brighter, it will be the best thing you've ever done short of buying a SlapChop. Finally, notice that you pick up useful methods like values(), ordinal() etc for free. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7561392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MYSQL: Multiple joins I am trying to put together a simple budget and expense tracking tool with three tables. Very simply, there is a budget table which includes the name of the budget and the budget amount. There is a table holding commitments, where each commitment has a number (for referencing), a amount and the name of the budget it is held against. The third table holds details of actual expenses, with the name of the budget the expense is held against and the expense amount. If the expense is linked to a commitment, then the commitment number can also be used. In summary, the rules are: * *every commitment must be held against a budget, although not every budget will have commitments, *every expense must be held against a budget, *not all expenses are held against a commitment, *a budget might have expenses but no commitments, *a commitment might not yet have an expense posted against it, and *all amounts are summarised. The result I am trying to produce is a report showing each budget, the total of expenses posted to it and the total of (commitments less expenses posted to the commitment) posted to that budget. I can (1) link a budgets to expenses or (2) link budgets to commitments. But I can't link all three to produce the right result - I end up with huge sums because every expense is shown against every commitment. I've looked at lots of the examples here (and will keep looking) but understanding the actual workings of what is presented is a bit beyond me right now. Instead of someone putting together a fully worked solution (which I don't really expect), can someone provide a simple explanation as to how to get the following results: * *Table 1: Budgets -> every row to appear *Table 2: Expenses -> summed by budget, where expenses exist for the budge *Table 3: Remaining commitment -> summed by budget, where a commitments exists AND less expenses where expenses have been posted to the commitment. I'm happy to post my database structures, but frankly I've been working for this on hours and there's not much to show as yet! [EDIT] The final result should look like (using the sample structure suggested by mellamokb): Budget item Budget amount Expenses Remaining commitment IT 5000 390 770 Admin 1000 250 20 Tech 300 100 0 Development 9000 350 0 A: Using the following DB structure that I have modelled from your description (I realize this structure is not normalized - I'm trying as best as possible to mimic the description given by OP): * *Budget: ID (PK), Name, Amount *Commitment: ID (PK), RefNumber, Budget, Amount *Expense: ID (PK), Budget, Amount, RefNumber (can be NULL) Here is the sample data I am using for the following examples (in thousands). Budget: ID Name Amount 1 IT 5000 2 Admin 1000 3 Tech 300 4 Development 9000 Commitment: ID RefNumber Budget Amount 1 SYSUPGRADE IT 750.00 2 PHONES Admin 35.00 3 WINDOWS7 IT 300.00 Expense: ID Budget Amount RefNumber 1 IT 35.00 NULL 2 IT 65.00 NULL 3 IT 125.00 SYSUPGRADE 4 IT 80.00 SYSUPGRADE 5 Tech 25.00 NULL 6 Tech 75.00 NULL 7 Admin 90.00 NULL 8 Development 300.00 NULL 9 Development 50.00 NULL 10 Admin 10.00 PHONES 11 Admin 5.00 PHONES 12 Admin 12.00 NULL 13 Admin 133.00 NULL 14 IT 25.00 WINDOWS7 15 IT 60.00 WINDOWS7 Here are the queries that would satisfy your three Table examples. Table 1: Budgets -> every row to appear select Name, Amount from Budget B Output: Name Amount IT 5000.00 Admin 1000.00 Tech 300.00 Development 9000.00 Table 2: Expenses -> summed by budget, where expenses exist for the budge select Budget, sum(Amount) As Amount from Expense E group by Budget Output: Budget Amount Admin 250.00 Development 350.00 IT 390.00 Tech 100.00 Table 3: Remaining commitment -> summed by budget, where a commitments exists AND less expenses where expenses have been posted to the commitment. select C.Budget, T.Amount - SUM(E.Amount) as RemainingCommitmentAmount from Commitment C inner join Expense E on C.RefNumber = E.RefNumber inner join (select Budget, SUM(Amount) as Amount from Commitment C group by Budget) T on T.Budget = C.Budget group by C.Budget, T.Amount Output: Budget RemainingCommitmentAmount Admin 20.00 IT 760.00 Edit: Combining them into a single output is as simple as left joining the three results together. Since we want all the budgets to display for sure, we use that as the base query, but since there may or may not be relevant expenses or commitments, we want to join those other results using a left join. Also, we will use the COALESCE command to replace NULL values with 0. Here is what the query would look like: select B.Name as `Budget Item`, B.Amount as `Budget amount`, COALESCE(E.Amount, 0) as `Expenses`, COALESCE(C.RemainingCommitmentAmount, 0) as `Remaining commitment` from ( select Name, Amount from Budget B ) B left join ( select Budget, sum(Amount) As Amount from Expense E group by Budget ) E on B.Name = E.Budget left join ( select C.Budget, T.Amount - SUM(E.Amount) as RemainingCommitmentAmount from Commitment C inner join Expense E on C.RefNumber = E.RefNumber inner join (select Budget, SUM(Amount) as Amount from Commitment C group by Budget) T on T.Budget = C.Budget group by C.Budget, T.Amount ) C on C.Budget = B.Name Output: Budget item Budget amount Expenses Remaining commitment IT 5000.00 390.00 760.00 Admin 1000.00 250.00 20.00 Tech 300.00 100.00 0.00 Development 9000.00 350.00 0.00 Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7561399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: strptime( ) function in [R] to manipulate date/time class So i'm working with a simple data set wanting to plot day x frequency the date is given in a human-readable format of > head(gb.day) [1] Sep 12, 2011 11:59 PM Sep 12, 2011 11:59 PM Sep 12, 2011 11:58 PM [4] Sep 12, 2011 11:56 PM Sep 12, 2011 11:55 PM Sep 12, 2011 11:55 PM 644 Levels: Sep 12, 2011 01:09 PM Sep 12, 2011 01:10 PM ... Sep 12, 2011 11:59 PM and is read as a factor. I'm trying to convert it into a date via the strptime( ) function in [R] and am running into problems > strptime(gb.day,"%b %d %Y %l %p") I thought would be the correct parameters but is returning NAs Are my parameters correct? Are there any other suggestions to accomplish this simple hassle A: You can also add the comma in the strptime() format: R> var <- "Sep 12, 2011 11:59 PM" R> strptime(var, "%b %d, %Y %I:%M %p") [1] "2011-09-12 23:59:00" R> Apart from that, your problem may have the use of factor encoding. Also try R> strptime( as.character(gb.day) ,"%b %d, %Y %I:%M %p") Lastly, you may have inadvertently swapped a '1' (digit one) or an 'I' (uppercase i). A: from datetime import datetime start_time = datetime.strptime(datetime.now(), "%Y-%m-%d %H:%M:%S")
{ "language": "en", "url": "https://stackoverflow.com/questions/7561400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MySQL Subqueries / Joins I have two different tables, products and inventory. Basically, what I'm trying to accomplish is I need to loop thru every row in my products table and reference the corresponding rows in the inventory table. My goal is to find out what products have a quantity of 0. The inventory table has multiple rows for each product id. The problem I'm facing is that ALL inventory rows that correspond to a particular product need to have a quantity of 0 for the result to be of any use to me (this is what I'm trying to figure out) Right now, I'm just looping thru every product and then executing a second SQL statement that checks for any occurrences of quantity > 0 in the inventory table for the selected product, but that doesn't work with my pagination script (20k rows in the product table, many more in the inventory table. displaying all at once is not an option) A: You should just preform an inner-join between the two tables and then select where quantity == 0. Something like: select products.* from products where (select sum(inventory.quantity) from inventory where products.id = inventory.productId) = 0 A: pseudo code The query becomes. SELECT p.*, SUM(i.qty,0) as number_in_stock FROM product p INNER JOIN inventory i ON (i.product_id = p.id) GROUP BY p.id HAVING number_in_stock = 0 This will be much slower though, because having only works after all the joining has been done. If you remove the inventory-line from the table when qty becomes 0, you can do this query, which is much faster: SELECT p.* FROM product p LEFT JOIN inventory i ON (i.product_id = p.id) WHERE i.id IS NULL A left join does this in the shoe store product id name inventory id prod_id qty ------------------ ------------------- 1 shoe 1 1 10 2 horse We have no horses, all nulls 3 boot 2 3 55 4 ferrari go to the cardealer, all nulls Now all we need to do is select all rows that have null in a field for inventory that cannot normally be null. Aha, the primary key can never be null, so if we select all rows where the inventory PK is null, we will have the products that are not in the inventory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ninject MVC Controller from external assembly I have some controllers in an external assembly, such as: namespace SomeExternalAssembly.Controllers { public class SomeExternalController : Controller { public ActionResult DoStuff() {...} } } then within my main mvc assembly I do the following: routes.MapRoute( "SomeExternalController", "external/{action}", new { controller = "SomeExternal", action = "Default"} ); Now the problem I am having is that I currently get an 404 when trying to hit that route, even though the route debugged shows it matching that route. I am only assuming that it is defaulting to the built in MVC controller factory to handle the type not being found. Is there any way around this... as currently most of my routes and controllers are injected by MEF at runtime...
{ "language": "en", "url": "https://stackoverflow.com/questions/7561408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search Multidimensional Array (Flash As3) using another array for search criteria Long story short: I want to search a multidimensional array in AS3 for (in this example) the location of 6 strings - all of which are stored in another unrelared array. Long story long: Once I get the locations (in the multidimensional array) of each string, i then know where it's located, and can access other atributes of that object - so if i found the string "box3" is located in element [5] of my multidimensional array, i can now target: multiArray[5][3] to return the 4th item stored (keeping in mind we're starting from 0, so 3 is the 4th position). I can get this to work once, but I'm trying to set up a for loop based on the length of my basic string storage array - this array holds (in this example) 6 instance name strings - each time my for loop loops, i need to run a search in my multdimensional array for the next consecutive instance name. Then, once I've located all of them (and store the results in a new temporary array) I can dig around in each location for the info I need. The only thing I can find is the post here: http://exoboy.wordpress.com/2010/07/15/successfully-searching-multidimensional-arrays-in-as3/ which works GREAT if I'm only searching for one elements in my array - but soon as I need to find multiple elements in a for loop using their code it falls apart. You can see my question/their response on that page as well for some more info. I need a simple to run function in the end that can be re-used over and over as I'll be doing a lot of searching in that array for the simulation i'm building. Thanks everyone, -Eric A: I guess you need two for loops then. use one loop for the searching in the array (that's the loop code you already have), and wrap it in another for loop which executes that searchloop. Makes sense? A: Here is the base function you could use. Obviously you will need to loop all your arrays calling this function for the test. function arrayContains( haystack:Array, needle:String ):Boolean{ for( var i:Number = 0;i < haystack.length; i++ ) { if( needle == haystack[i] ) { return true; } } return false; } // sample code var myArray:Array = new Array(); myArray.push(["granola","people... are great"," 4 ","10"]); myArray.push(["bill","orangutan","buster","keaton"]); myArray.push(["steve","gates","24","yes, sometimes"]); myArray.push(["help","dave","jobs","hal"]); var searchArray:Array = ["granola","orangutan","24","hal"]; for each( var arr:Array in myArray ){ for each( var searchString:String in searchArray ){ if( arrayContains( arr, searchString ) ){ trace( 'found ' + searchString + 'in myArray at ' + myArray.indexOf(arr) ) } } } A: This version loops using the method itself, searchArray(), and keeps track of the position in the tree. Once it finds a match, it outputs the position to searchResults. Then you can use getNestedItem() with each array of uints to retrieve the value. package { import flash.utils.getQualifiedClassName; public class NestedSearch { private var _multidimensionalArray :Array = [ //[0] [ // [0] // [0], [1], [2] ["one", "two", "three" ], // [1] // [0], [1], [2] ["eleven", "twelve", "thirteen" ] ], //[1] [ // [0] // [0], [1], [2] ["hyena", "iguana", "jackal" ], // [1] "koala" ] ]; private var queries :Array = new Array( "three", "twelve", "hyena", "koala" ); private var searchResults :Array = []; public function NestedSearch() { // Make multiple queries for ( var q in queries) { searchArray( queries[ q ], _multidimensionalArray, [] ); } // Use the results for ( var i in searchResults ) { trace( 'Found "' + searchResults[ i ].query + '" at _multidimensionalArray[' + searchResults[ i ].position + ']'); trace( "Test value: " + getNestedItem( _multidimensionalArray, searchResults[ i ].position )); } } // Searches any array for an exact String value. // Returns the found string as an Array of uints representing its position in the tree. public function searchArray ( s:String, a:Array, positionPath:Array ) { // Duplicate array to save it before going back out var _origPosPath = positionPath.concat(); for ( var i in a ) { if ( getQualifiedClassName( a[ i ] ) === "Array") { positionPath.push(i); searchArray( s, a[ i ], positionPath ); positionPath = _origPosPath; } else { if ( a[ i ] === s) searchResults.push( {query: s, position: positionPath.concat( i )} ); } } } private function getNestedItem ( arr:Array, pos:Array ) :* { var nestedItem; var p = pos.shift(); if ( pos.length === 0 ) { nestedItem = arr[ p ]; } else { nestedItem = getNestedItem( arr[ p ], pos ); } return nestedItem; } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Session Handling without Cookies and URL rewriting I have an old web site(servlets, JSP, and Struts). Currently, session management handled by using cookies. I wanted to redesign this site to make browser independent. I know there is an alternate - URL re-writing, however, this is not feasible for me to re-write(encode) all the URLs in my application. I am looking for a solution which should not impact my code much. Please suggest me, if anyone is having a feasible solution. It will be a great help to me. A: This makes no sense. Just use URL rewriting. Otherwise you basically end up in reinventing the whole HttpSession concept. You'd need to change every line in your code which uses HttpSession. This will require much more time than fixing your webapp to utilize URL rewriting. Bite the bullet and take this as a lesson learnt so that you don't make the same mistake of not doing URL rewriting for the future projects which requires supporting browsers which don't support cookies. A: As far as I can imagine there is only one third option other than session token in URL or Cookie that is so dirty and impractical that I would not recommend it ;) But here we go: Have a hidden form field on every page with the session token and every request to the server must be a form submit including the hidden fields value. A: From my point of view cookies are already the best solution when optimizing for browser independence only (excluding implicit sessions via GET). Rewrite all a.href with javascript to add the session hash as parameter. This shouldn't be your solution if you go for true browser independence as cookies are more widespread than javascript support. Larger chunks of data can be stored in LocalStorage. sessionStorage.setItem("key", "value"); and var key_value = sessionStorage.getItem("key"); Easy to set up and considerably faster for larger client side session data. But you still have to send some data to the server via POST/GET AJAX calls to actually track the session on the server-side. Cookies should be friends, not foes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery mobile: how to close a pop up dialog page from code? I am opening a pop-up dialog like- <a href="routeEdit.php" data-role="button" data-icon="gear" data-inline="true" data-theme="b" data-transition="pop" data-rel="dialog">Edit</a> Now, from that page, calling a method submit(). How will i close the pop-up from submit() method- without redirecting to main page? A: If you use pop in jQ Mobile 1.3.0,then $("#popupLogin").popup('close'); wourld be used. A: $('#myDialog').dialog('close'); Try above coding. It's working for me. A: Try this: $(".ui-popup").popup( "close" );
{ "language": "en", "url": "https://stackoverflow.com/questions/7561417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How do you adjust/control the scale in a treemap (using the 'portfolio' library) in R? I am using R and the 'portfolio' library to build a treemap. The scale is defaulting to '-1000 to 1000'. I need it to be '0 to 1000', for example. I know there is a 'scale' parameter to map.market(), but I can't figure out what to pass to it. A: A symmetric colour-mapping around zero is hard coded into map.market: legend.ncols <- 51 l.x <- (0:(legend.ncols - 1))/(legend.ncols) l.y <- unit(0.25, "npc") l.cols <- color.ramp.rgb(seq(-1, 1, by = 2/(legend.ncols - 1))) if (is.null(scale)) { l.end <- max(abs(data$color.orig)) } else { l.end <- scale } and, top.list <- gList(textGrob(label = main, y = unit(0.7, "npc"), just = c("center", "center"), gp = gpar(cex = 2)), segmentsGrob(x0 = seq(0, 1, by = 0.25), y0 = unit(0.25, "npc"), x1 = seq(0, 1, by = 0.25), y1 = unit(0.2, "npc")), rectGrob(x = l.x, y = l.y, width = 1/legend.ncols, height = unit(1, "lines"), just = c("left", "bottom"), gp = gpar(col = NA, fill = l.cols), default.units = "npc"), textGrob(label = format(l.end * seq(-1, 1, by = 0.5), trim = TRUE), x = seq(0, 1, by = 0.25), y = 0.1, default.units = "npc", just = c("center", "center"), gp = gpar(col = "black", cex = 0.8, fontface = "bold"))) Note the presence of seq(-1,1,...) statements. The scale parameter only affects the absolute size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Forms Authentication expiration + Silverlight I've got a Silverlight application, on which the server-side uses an authentication mode of type "Forms". This authentication expires after some time, which is the behavior we want. The server-side is a .svc web service. Problem is, if I send a request to the Server side after the authentication expires, I get the "The remote server returned an error: NotFound." message. Ideally, I want a way to know that the authentication is expired so that I can handle it in a more elegant way on the client-side. Has anyone had to deal with a similar problem? Thank you! A: I will assume that you have no control over the called service. If an immediate update on the client side is not required (it doesn't seem like it from your description), you could simply find out the exception that the service returns and wrap that to display however you like. ResultObject result; try { result = RetrieveDataFromWebService(); } catch (ExceptionThatIsThrownFromWebService exception) { DisplayErrorInCustomWayToUser(exception); } A: Out of the box, Silverlight/WCF communication doesn't handle Faults correctly. My first suggestion would be to read http://msdn.microsoft.com/en-us/library/ee844556(v=VS.95).aspx Which illustrates how to tell Silverlight to read the SOAP body when there's an error rather than defaulting to the std CommunicationException behavior.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use ruby array for a javascript array in erb. Escaping quotes i've found numerous things online for this but they dont work for me. am i missing something. In my controller i have @t = ["a","b","c"] in the erb file that is 'callback' the @t renders like so: [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;] i've done hacks to replace the " to proper ' symbols. I've read that to_json should work but it doesnt. The following does not work ["a","b","c"].to_json. The results are the same. A: to_json is working fine. What you're running into is Rails 3.x's XSS protection. There's a good article on this at Railscasts/ASCIIcasts. The gist, though, is that you need to use the raw or html_safe methods: In your controller: @t_json = @t.to_json.html_safe OR in your view: <%= raw @t %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7561430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: dia export to html Is there any way that I can export dia diagram into html (I know that dia exports to various formats such as svg, pdf, ... but I could not find anything that would allow me to export dia to html (with shapes being individual pictures) A: With modern browsers, you can embed SVG in HTML. This will give you shapes as indidual objects. With the upcoming Dia 0.98 your SVG could even include hyperlinks: http://www.dia-installer.de/images/linktest.svg Note that "shapes being individual pictures" would most likely involve overlapping pictures - is that what you're looking for?
{ "language": "en", "url": "https://stackoverflow.com/questions/7561432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Optimize this query with multiple joins I have a query that keeps timing out in SQL Server. The biggest table in the query only has a few hundred rows. Basically I'm trying to match up data in a bunch of tables with the novaPost field in tblNovaPosts to create a report. How should I change this query to make it run faster? SELECT TOP (100) PERCENT tblNovaPosts.type, tblNovaPosts.novaPost, ISNULL(SUM(tblAuditTrail.amount), 0) AS FUNDING, ISNULL(SUM(tbl510.allot), 0) AS ALLOT, ISNULL(SUM(tblStanfin.oblig), 0) + ISNULL(SUM(tblSof.obligationsCum), 0) + ISNULL(SUM(tblSpecAppt.obligations), 0) + ISNULL(SUM(tblJlens.obligationsCum), 0) - ISNULL(SUM(viewReimbObs.reimbObs), 0) AS OBLIGATED, ISNULL(SUM(tblSof.commitmentsNonCum), 0) + ISNULL(SUM(tblRmt.commitment),0) + ISNULL(SUM(tblReimb.commitmentsNonCum), 0) - ISNULL(SUM(viewReimbObs.reimbObs), 0) AS DIRCOMMIT FROM tblNovaPosts LEFT OUTER JOIN tblAuditTrail ON tblNovaPosts.novaPost = tblAuditTrail.novaPost LEFT OUTER JOIN tbl510 ON tblNovaPosts.novaPost = tbl510.novaPost LEFT OUTER JOIN tblStanfin ON tblNovaPosts.novaPost = tblStanfin.novaPost LEFT OUTER JOIN tblSof ON tblNovaPosts.novaPost = tblSof.novaPost LEFT OUTER JOIN tblSpecAppt ON tblNovaPosts.novaPost = tblSpecAppt.novaPost LEFT OUTER JOIN tblJlens ON tblNovaPosts.novaPost = tblJlens.novaPost LEFT OUTER JOIN viewReimbObs ON tblNovaPosts.novaPost = viewReimbObs.novaPost1 LEFT OUTER JOIN tblRmt on tblNovaPosts.novaPost = tblRmt.novaPost LEFT OUTER JOIN tblReimb ON tblNovaPosts.novaPost = tblReimb.novaPost GROUP BY tblNovaPosts.type, tblNovaPosts.novaPost ORDER BY tblNovaPosts.type, tblNovaPosts.novaPost A: View the query plan. Oftentimes SQL Server will give you an index recommendation. Click this button: A: There is something suspicious about all the LEFT OUTER JOINs. Are you quite sure that is what you need? Also, I notice you are outer joining to a table called tblAuditTrail. That seems likely to produce a cartesian product of 2 tables. Perhaps you should test each join individually to check you are not actually requesting ten gzillion rows instead of just the few hundred you were expecting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: selectedRowInComponent not working I have the following issue (with iPhone SDK) : The selectedRowInComponent method of UIPickerView returns the correct value the first time it is called and then keeps returning the same value eventhough the PickerView object has been moved. The first time answer is correct even if I make a first move before calling the method. Any idea for the possible cause of the problem ? Thanks. A: One possible cause for this issue is not making a connection in interface builder to the picker. Ensure you have an IBOutlet for your picker then drag from File's Owner to the picker in the xib file. Select the picker in the menu that pops up. Thats the obvious solution, however without viewing the code its hard to tell for sure what is going on. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Antialiased bezier curve with GDI / Winforms - c# .net I'm trying to paint a bezier curve in a sample Winforms application. I'm calculating the bezier points, and then painting using DrawImage to draw a custom image brush on each point. However I'm not exactly getting the result I was hoping for - the resulting curve is not smooth at the points that it bends (note the Y coordinates are increased / decreased with 1px): Here is an example of a "nice" curve quickly painted in "photoshop" with the brush tool: Does anyone know how to achieve this kind of "antialiasing"? I'm basically doing this: using(var g = Graphics.FromImage(bitmap)) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; //points - an array with calculated beziere curve points //image - the "image brush" that is painted at each curve point foreach (var p in points) { g.DrawImage(image, p); g.Flush(); } } Thank you! A: You're probably getting this because your points collection contains structs of type Point, which uses Int32 - as a result, you're quantizing your points yourself. Try using PointF instead - this allows you to draw images at any arbitrary location, instead of being quantized around integer locations. A: You're not actually using GDI to draw lines and so your Smoothing and InterpolationMode settings have no effect. You're simply drawing an image per every point in a point array and so there's no connecting those points or any kind of antialiasing. Try converting your points collection into a path and using g.DrawPath to draw your curve. A simpler, though Bezier-less, example of this would be to use the DrawLines method. Something like: g.DrawLines(Pens.Blue, points.ToArray()); You don't even need a loop for DrawLines and DrawPath. DrawLines is like a poor man's DrawPath...
{ "language": "en", "url": "https://stackoverflow.com/questions/7561442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Stop Executing Method on Event I have a property in a class that, when set, it will change some other properties's values, any of which may raise an specific event for rollback (say RollbackEvent). If such event is fired then all changes made by the original property have been rolled back and now I need that property to stop on its tracks. Throwing an exception is not an option (I think) 'cause there'll be another assembly(s) consuming the code (actually is the other assembly who captures a second event in my code and, if it fails to handle the situation, it commands my code to rollback and that's when the RollbackEvent is fired) for which no exception should be thrown. Update This is a general outline of my code, and AFAIK the code in the second Assembly should never realize an exception was thrown in the first one, but the after the "transaction" is rolled back (apparently) successfully the code on the second assembly stops executing. Assembly 1 public class Someclass { public String SomeField { get { return this._someField; } set { try { this.BackupSomeFields(); this._someField = value; //Some other Properties are changed //One of which may (and will for the purposes of the question) throw a DocumentRolledbackException exception } catch (DocumentRolledbackException ex) { return; } } } public String SomeOtherField { get { return this._someOtherField; } set { this._someOtherField = value; //Raise AN event (handled in Assembly 2) } } public void RollbackProcessTransaction() { //Rollback changes with the backup created by the SomeField property //Raise THE event DocumentRolledBack(this, new EventArgs()); } private void MyBase_DocumentRolledBack(Object sender, EventArgs e) { //This method is called when the DocumentRolledBack event is fired in the RollbackProcessTransaction method. throw new DocumentRolledbackException(this); } } Assembly 2 public class SomeOtherClass { private SomeClass obj; private HandleANEvent() { obj.RollbackProcessTransaction(); //Code in this line on never gets executed! >.< } } Basically it's all working good, when the exception is thrown in assembly 1 it gets captured by the property and such property then returns, but the code after the invocation of obj.RollbackProcessTransaction(); never gets executed... why? P.S. I wrote all that code here in the editor 'cause I actually program in VB, so don't take all the code there so literally, that's just for you to get the idea. A: Like this? public class Test { public object Foo1 { try { Foo2 = 1; Foo3 = 2; Foo4 = 3; } catch (RollbackException ex) { } } private void DoRollback() { throw new RollbackException(); } public object Foo2 { get; set; } public object Foo3 { get; set; } public object Foo4 { get; set; } private class RollbackException : Exception { } } EDIT: public class SomeOtherClass { private SomeClass obj; public SomeOtherClass() { var backup = obj.Clone(); try { obj.SomeField = "test"; } catch (RollbackException ex) { obj = backup; } } } A: The simplest way would be to record each property's value before changing it, then revert them in the event of an error. If each property has a quick exit if the value is set the same, it'll prevent further exceptions being thrown. I'm borrowing a little from Magnus' answer. public class Test { public object Foo1 { object oldfoo2 = Foo2; object oldfoo3 = Foo3; object oldfoo4 = Foo4; try { Foo2 = 1; Foo3 = 2; Foo4 = 3; } catch (RollbackException ex) { Foo4 = oldfoo4; Foo3 = oldfoo3; Foo2 = oldfoo2; } } public object Foo2 { get { return foo2; } set { if (value == foo2) return; if (isInvalid(value)) throw new RollbackException(); foo2 = value; } } private object foo2 = null; public object Foo3 { /* As Foo2 */ } public object Foo4 { /* As Foo2 */ } private class RollbackException : Exception { } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7561443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a loop to print html lists I need to create a html list similar in form to the following: <ul class="treeView"> <li> Root Item <ul class="collapsibleList"> <li> Sub-Folder 1 <ul> <li> Sub-Sub-Folder 1 <ul> <li>Item 1</li> <li class="lastChild">Item 2</li> </ul> </li> <li class="lastChild"> Sub-Sub-Folder 2 <ul> <li>Item 3</li> <li class="lastChild">Item 4</li> </ul> </li> </ul> </li> <li class="lastChild"> Sub-Folder 2 <ul> <li>Item 5</li> <li>Item 6</li> <li class="lastChild">Item 7</li> </ul> </li> </ul> </li> </ul> This list is based off a directory structure, but I have the code down for listing the actual structure. So all I need is how to use the for loop to keep track of everything and create the nested html lists. Below is my python script that I have so far: for item in lstItems: splitfile = os.path.split(item[0]) webpyPath = splitfile[0].replace("/srv/http/example/www", "") itemName = splitfile[1] if item[1] == 0: lstRemDir.append(itemName) intDirNum = len(lstRemDir) - 1 if item[1] == 0: if len(lstRemDir) == 1: print ''' <ul class="treeView"> <li>Collapsible lists <ul class="collapsibleList"> ''' elif len(lstRemDir) != 1: f.write(' </ul>\n</li>') f.write('<li><a href=\"' + webpyPath + "/" + itemName + '\" id=\"directory\" alt=\"' + itemName + '\" target=\"viewer\">' + itemName + '</a></li>\n') elif item[1] == 1: f.write('<li><a href=\"' + webpyPath + "/" + itemName + '\" id=\"file\" alt=\"' + itemName + '\" target=\"viewer\">' + itemName + '</a></li>\n') else: f.write('<li>An error happened in processing ' + itemName + '.') The reason I am asking is because I have been trying to get this figured out for days. I am not asking for someone to do it for me, just a good way to do it. I have tried using lists to store data but I felt like it got too confusing. Hopefully that clarifies what I am looking for. Thanks in advance! A: This might help to get you started on a simpler solution that uses a nested dictionary to represent your files instead of lists: dir = {} start = rootdir.rfind('/')+1 for path, dirs, files in os.walk(rootdir): folders = path[start:].split('/') subdir = dict.fromkeys(files) parent = reduce(dict.get, folders[:-1], dir) parent[folders[-1]] = subdir Here is an example of what dir might look like for a similar structure to the one in your example: { "root": { "folder2": { "item2": None, "item3": None, "item1": None }, "folder1": { "subfolder1": { "item2": None, "item1": None }, "subfolder2": { "item3": None, "item4": None } } } } Using this it shouldn't be too difficult to write a recursive function that accepts a dictionary and returns an html list. Here is a simple function that just prints the items out at the correct level, you should be able to modify this to add the html code: def html_list(nested_dict, indent=0): result = '' if nested_dict is not None: for item in sorted(nested_dict.keys()): result += ' '*indent + item + '\n' result += html_list(nested_dict[item], indent+4) return result >>> print html_list(dir) root folder1 subfolder1 item1 item2 subfolder2 item3 item4 folder2 item1 item2 item3
{ "language": "en", "url": "https://stackoverflow.com/questions/7561445", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I've seen one but... what exactly is a 10g Package? Scenario: I know nothing about packages except that they contain functions and procedures all wrapped into a nice little present. So today I was given this package (rather large) with the instructions of "here, this is broken please fix it". I finally cleaned it all up, which brings me to my questions. In the overall view of a package, that is going to be exported. 1) Other than a collection of everything does a package serve any other purpose? 2) To deploy this package do you need to set up the deployment space to already have all of the views/materialized views/ and tables that the package called? If not I am assuming the package will fail to execute. 3) Can you code the package to skip functions and procedures it fails to execute on without bombing out? 4) When taking a package that successfully compiled in one place to another place what other things should I be aware of? A: 1) Other than a collection of everything does a package serve any other purpose? Other than that, it reduces the need to recompile other procedures that are dependant on a specific procedure when the specific procedure is altered. Consider an (ordinary, not package wise) procedure XYZ(a in number) that is called by many other procedures. If this procedure is altered, all the other procedures need to be recompiled which might reduce the availablity of the system. On the other hand, if the procedure is declared in a package and defined in a package body and the procedure is changed in the body only, (almost) no recompiling takes place. 2) To deploy this package do you need to set up the deployment space to already have all of the views/materialized views/ and tables that the package called? If not I am assuming the package will fail to execute. No, you can install a package body without the dependant views or tables in place. The state of the package body will then be INVALID and no functionality of the package body can be used. 3) Can you code the package to skip functions and procedures it fails to execute on without bombing out? Not sure, what the question is exactly. If the state of the package body is INVALID, no code can be executed, hence no "bombing out" can happen. However, if the bombing out occurs for a logical reason (such as a division by zero for example) you can always resort to the exception when others then construct. 4) When taking a package that successfully compiled in one place to another place what other things should I be aware of? Again, not sure what you mean here. Could you elaborate what one place is? A schema? An instance? An installation, a company....? A: 1) Well you can almost think of a package as being analogous to a class. Its a logical grouping of related methods. It also allows you to encapsulate related "helper" methods that should not be used by anyone else. They can be included in the package and only accessible by member methods. 2) In order to successfully deploy a package, yes, you must have the necessary tables, views, etc. If they are not, its not a matter of the package not being able to execute any procedures or functions, it will not deploy properly. It will show up in the data dictionary as not compiled. 3) Define "bomb out". If the necessary objects exist to successful deploy the package, then everything else is a run time error - things that should be coded for. Think exception handling. 4) Again, the necessary schema objects referenced in your package must exist. If they do not, the package will not compile and will be marked as such in the data dictionary. A: In addition to the other helpful answers above. 1) Package headers can also hold variables whose scope is not just to a proc or function. 2) If you are moving the package tables/views may not have to be copied if they are in the same database and the new schema has permission to see the old tables. or if a database link can be used to the database that contains the data. In some database versions there may be limits on using lobs across a database link. Tables in another schema need to be referenced {schema-name}.{table-name}. A database link is specified by {table-name}@{database-link-name}. Granting permission to a table in another schema will need to be done explicitly not through a role - thats just how oracle is 3. If you add: "exception when others then null; " as the 2nd last line in a proc (immediately before "end") it may do what you are after. 4) Grants/permissions/roles/sequences and possibly synonyms and other dependent procs/functions packages may be needed for the package to run. Actually any object in the original schema may be referenced in the package and may be needed or a grant on it may be needed..
{ "language": "en", "url": "https://stackoverflow.com/questions/7561447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change text of a specific row in uitableview? Is it some how possible to update text of a specific row in uitableview. like for example I have 3 rows A B C . and now I would like to add another row to the table like row with D I know you can do it with reloading the table but that would take a lot of time (there is alot of data to be put in). so is it possible without reloading the entire table. thanks, Tushar Chutnai A: Try this method of UITableView class: - (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation; source A: Use either: insertRowsAtIndexPaths:withRowAnimation: OR insertSections:withRowAnimation: depending on your type of table. Read the Apple developer's documentation on UITableView class here and check out the Instance Methods section in that. Should solve your troubles.
{ "language": "en", "url": "https://stackoverflow.com/questions/7561448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }