Search Results

Search found 13889 results on 556 pages for 'results'.

Page 154/556 | < Previous Page | 150 151 152 153 154 155 156 157 158 159 160 161  | Next Page >

  • reading excel using scriptom for groovy, producing xml

    - by john
    Dear friends, I got a program from http://kousenit.wordpress.com/2007/03/27/groovyness-with-excel-and-xml but I got some very strange results: 1) I can still print xml but two records are not readable. 2) I got exception suggesting some thing missing could some experts enlighten me about what might go wrong? I copied the program and result below. thanks! import org.codehaus.groovy.scriptom.ActiveXObject def addresses = new File('addresses1.xls').canonicalPath def xls = new ActiveXObject('Excel.Application') def workbooks = xls.Workbooks def workbook = workbooks.Open(addresses) // select the active sheet def sheet = workbook.ActiveSheet sheet.Visible = true // get the XML builder ready def builder = new groovy.xml.MarkupBuilder() builder.people { for (row in 2..1000) { def ID = sheet.Range("A${row}").Value.value if (!ID) break // use the builder to write out each person person (id: ID) { name { firstName sheet.Range("B${row}").Value.value lastName sheet.Range("C${row}").Value.value } address { street sheet.Range("D${row}").Value.value city sheet.Range("E${row}").Value.value state sheet.Range("F${row}").Value.value zip sheet.Range("G${row}").Value.value } } } } // close the workbook without asking for saving the file workbook.Close(false, null, false) // quits excel xls.Quit() xls.release() however, i got the following results: <people> <person id='1234.0'> <name> <firstName>[C@128a25</firstName> <lastName>[C@5e45</lastName> </name> <address> <street>[C@179ef7c</street> <city>[C@12f95de</city> <state>[C@138b554</state> <zip>12345.0</zip> </address> </person> </person> Exception thrown May 12, 2010 4:07:15 AM org.codehaus.groovy.runtime.StackTraceUtils sanitize WARNING: Sanitizing stacktrace: java.lang.NullPointerException at org.codehaus.groovy.runtime.callsite.GetEffectivePojoFieldSite.acceptGetProperty(GetEffectivePojoFieldSite.java:43) at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:237) at sriptom4_excel$_run_closure1.doCall(sriptom4_excel.groovy:18) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [1]: http://kousenit.wordpress.com/2007/03/27/groovyness-with-excel-and-xml/

    Read the article

  • How can I remove an "ALMOST" Duplicate using LINQ? ( OR SQL? )

    - by Atomiton
    This should be and easy one for the LINQ gurus out there. I'm doing a complex Query using UNIONS and CONTAINSTABLE in my database to return ranked results to my application. I'm getting duplicates in my returned data. This is expected. I'm using CONTAINSTABLE and CONTAINS to get all the results I need. CONTAINSTABLE is ranked by SQL and CONTAINS (which is run only on the Keywords field ) is hard-code-ranked by me. ( Sorry if that doesn't make sense ) Anyway, because the tuples aren't identical ( their rank is different ) a duplicate is returned. I figure the best way to deal with this is use LINQ. I know I'll be using the Distinct() extension method, but do I have to implement the IEqualityComparer interface? I'm a little fuzzy on how to do this. For argument's sake, say my resultset is structured like this class: class Content { ContentID int //KEY Rank int Description String } If I have a List<Content> how would I write the Distinct() method to exclude Rank? Ideally I'd like to keep the Content's highest Rank. SO, if one Content's RAnk is 112 and the other is 76. I'd like to keep the 112 rank. Hopefully I've given enough information.

    Read the article

  • Jquery ajaxStart doesnt get triggered

    - by gnomixa
    This code $("#loading").ajaxStart(function() { alert("start"); $(this).show(); }); in my mark-up <div style="text-align:center;"><img id="loading" src="../images/common/loading.gif" alt="" /></div> Here is the full ajax request: $.ajax({ type: "POST", url: "http://localhost/WebServices/Service.asmx/GetResults", data: jsonText, contentType: "application/json; charset=utf-8", dataType: "json", success: function(response) { var results = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d; PopulateTree(results); }, error: function(xhr, status, error) { var msg = JSON.parse(xhr.responseText); alert(msg.Message); } }); $("#loading").ajaxStart(function() { alert("start"); $(this).show(); }); $("#loading").ajaxStop(function() { alert("stop"); $(this).hide(); $("#st-tree-container").show(); }); never fires alert "start" even though the gif is shown to rotate. AjaxStop gets triggered as expected. Any ideas why?

    Read the article

  • Email as a view.

    - by Hal
    I've been in some discussion recently about where email (notifications, etc...) should be sent in an ASP.NET MVC application. My nemesis grin argues that it only makes sense that the email should be sent from the controller. I argue that an email is simply an alternate or augmented view through a different channel. Much like I would download a file as the payload of an ActionResult, the email is simply delivered through a different protocol. I've worked an extension method that allows me to do the following: <% Html.RenderEmail(model.FromAddress, model.ToAddress, model.Subject); %> which I actually include within my the view that is displayed on the screen. The beauty is that, based on convention, if I call RenderEmail from a parent view named MyView.ascx, I attempt to render the contents of a view named MyViewEmail.ascx, unless it is not found, in which case I simply email a copy of parent view. It certainly does make it testable (I still have an ISMTPService injected for testing), I wondered if anyone had any thoughts on whether or not this breaks from good practice. In use it has been extremely handy when we needed to easily send an email or modify the contents of the emailed results vs the browser rendered results. Thanks, Hal

    Read the article

  • ADO/SQL Server: What is the error code for "timeout expired"?

    - by Ian Boyd
    i'm trying to trap a "timeout expired" error from ADO. When a timeout happens, ADO returns: Number: 0x80040E31 (DB_E_ABORTLIMITREACHED in oledberr.h) SQLState: HYT00 NativeError: 0 The NativeError of zero makes sense, since the timeout is not a function of the database engine (i.e. SQL Server), but of ADO's internal timeout mechanism. The Number (i.e. the COM hresult) looks useful, but the definition of DB_E_ABORTLIMITREACHED in oledberr.h says: Execution stopped because a resource limit was reached. No results were returned. This error could apply to things besides "timeout expired" (some potentially server-side), such as a governor that limits: CPU usage I/O reads/writes network bandwidth and stops a query. The final useful piece is SQLState, which is a database-independent error code system. Unfortunately the only reference for SQLState error codes i can find have no mention of HYT00. What to do? What do do? Note: i can't trust 0x80040E31 (DB_E_ABORTLIMITREACHED) to mean "timeout expired", anymore than i could trust 0x80004005 (E_UNSPECIFIED_ERROR) to mean "Transaction was deadlocked on lock resources with another process and has been chosen as the deadlock victim". My pseudo-question becomes: does anyone have documentation on what the SQLState "HYT000" means? And my real question still remains: How can i specifically trap an ADO timeout expired exception thrown by ADO? Gotta love the questions where the developer is trying to "do the right thing", but nobody knows how to do the right thing. Also gotta love how googling for DB_E_ABORTLIMITREACHED and this question is #9, with MSDN nowhere to be found. Update 3 From the OLEdb ICommand.Execute reference: DB_E_ABORTLIMITREACHED Execution has been aborted because a resource limit has been reached. For example, a query timed out. No results have been returned. "For example", meaning not an exhaustive list.

    Read the article

  • Yahoo BOSS Question

    - by Fincha
    Hello everyone, I wonna to echo totalresults but somethink is wrong. // Get search results from Yahoo BOSS as an XML* $API = 'http://boss.yahooapis.com/ysearch/web/v1/'; $request = $API . $query .'?format=xml&appid='. APP_ID.'&start='.$start."0"; $ch = curl_init($request); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); $xml = simplexml_load_string(curl_exec($ch)); echo $xml->resultset_web->totalhits; // Display search results - Title, Date and URL. foreach ($xml->resultset_web->result as $result) { $ausgabe .= '<a href="'.$result->clickurl.'">'.$result->title.'</a><br />'; $ausgabe .= $result->abstract."<br>"; $ausgabe .= '<a href="'.$result->clickurl.'">'.$result->url."</a> - ".round(($result->size/1024), 2)." Kb<br><br>"; } Can someone help me

    Read the article

  • Continuous Integration with 64-bit Sharepoint and TFS 2008?

    - by Hirvox
    I've set up a 64-bit TFS 2008 build server with Sharepoint, continuous integration and out-of-the-box MSTest. Unit tests for plain business logic classes run just fine and test results are published into TFS. However, any test that uses Sharepoint's API fails horribly, SPFarm.Local returning null and so on. Is there a way to fix this? The tests run fine in an otherwise identical 32-bit development environment (Windows Server 2008 under Hyper-V, Sharepoint patched up to June 2009 cumulative update) from both Visual Studio and command line, so the problem is not about improper use of SPContext.Current or any other part of the API that needs to be run in a web server context. I've ruled out permissions issues, because the build agent account can deploy the solution and create site collections just fine with stsadm. The next culprit could be that the unit tests were being run with a 32-bit process, which couldn't access the 64-bit Sharepoint API properly. I tried a workaround, but it has the side effect of disabling TFS support in MSTest. Do I have to wait for 2010 versions of MS tools (and hope for the best) or is there a third-party test framework available that runs natively in 64 bit and can publish test results into TFS 2008?

    Read the article

  • How do I import and call unmanaged C dll with ansi string "char *" pointer string from VB.net?

    - by Warren P
    I have written my own function, which in C would be declared like this, using standard Win32 calling conventions: int Thing( char * command, char * buffer, int * BufSize); I have the following amount of VB figured out, which should import the dll and call this function, wrapping it up to make it easy to call Thing("CommandHere",GetDataBackHere): Imports Microsoft.VisualBasic Imports System.Runtime.InteropServices Imports System Imports System.Text Namespace dllInvocationSpace Public Class dllInvoker ' tried attributes but could not make it build: ' <DllImport("Thing1.dll", False, CallingConvention.Cdecl, CharSet.Ansi, "Baton", True, True, False, True)> Declare Ansi Function Thing Lib "Thing1.dll" (ByVal Command As String, ByRef Buffer As String, ByRef BufferLength As Integer) Shared Function dllCall(ByVal Command As String, ByRef Results As String) As Integer Dim Buffer As StringBuilder = New StringBuilder(65536) Dim retCode As Integer Dim bufsz As Integer bufsz = 65536 retCode = Thing(Command, Buffer, bufsz) Results = Buffer Return retCode End Function End Class End Namespace The current code doesn't build, because although I think I should be able to create a "buffer" that the C Dll can write data back into using a string builder, I haven't got it quite right. (Value of type System.Text.STringBuilder cannot be converted to 'String'). I have looked all over the newsgroups and forums and can not find an example where the C dll needs to pass between 1 and 64kbytes of data back (char *buffer, int bufferlen) to visual basic.net.

    Read the article

  • What is the fastest, most efficient way to get up to speed on a new technology?

    - by SLC
    My current job involves working with a huge number of technologies, most of which are very niche and unheard of. In some cases I have to write something about the technology, or with the technology, such as some lessons, examples, or tutorials, on behalf of the developer of that technology or someone that is backing it. When I get told to learn about a new technology, my first port of call is to check our internal library, and then look on amazon for a book on the subject. Failing that, or if the project is too small to warrant a purchase, I hit up google and youtube. However the results of randomly googling what I want to learn are hit and miss. Some days, I can find everything I want to know in a series of lessons or videos, and it's no problem. Other times, I can find almost nothing, and I really have to piece together things from sites. The result is that there are various resources out there, videos, interactive lessons, tutorials, books etc. but when I need to learn something fast, I often don't know the best way to go about it. It's not about fun, because I don't always have the luxury of working my way through a 600 page textbook named "A Complete Guide To Technology X", I have to deliver results quickly. One of the examples I'd like to use is ASP.NET MVC 2 which is something I have been told to learn. I grabbed a book on MVC 1 to refresh my knowledge, but googling it does't produce much useful information. I've seen a ton of ScottGu's tutorials on it, but they are mostly feature presentations, and some date back almost a year. The same applies to channel 9 and there are no books out yet on amazon. My question therefore has two parts, the first asks, "Where are the best places to look to get the information needed to learn a new technology?" and the second asks "What is the most efficient way to use such resources to learn a new technology?"

    Read the article

  • Debug NAudio MP3 reading difference?

    - by Conrad Albrecht
    My code using NAudio to read one particular MP3 gets different results than several other commercial apps. Specifically: My NAudio-based code finds ~1.4 sec of silence at the beginning of this MP3 before "audible audio" (a drum pickup) starts, whereas other apps (Windows Media Player, RealPlayer, WavePad) show ~2.5 sec of silence before that same drum pickup. The particular MP3 is "Like A Rolling Stone" downloaded from Amazon.com. Tested several other MP3s and none show any similar difference between my code and other apps. Most MP3s don't start with such a long silence so I suspect that's the source of the difference. Debugging problems: I can't actually find a way to even prove that the other apps are right and NAudio/me is wrong, i.e. to compare block-by-block my code's results to a "known good reference implementation"; therefore I can't even precisely define the "error" I need to debug. Since my code reads thousands of samples during those 1.4 sec with no obvious errors, I can't think how to narrow down where/when in the input stream to look for a bug. The heart of the NAudio code is a P/Invoke call to acmStreamConvert(), which is a Windows "black box" call which I can't think how to error-check. Can anyone think of any tricks/techniques to debug this?

    Read the article

  • Messaging pattern question

    - by Al Bundy
    Process A is calculating values for objects a1, a2, a3 etc. and is sending results to the middleware queue (RabbitMQ). Consumers read the queue and process these results further. Periodically process A has to send a snapshot of these values, so consumers could do some other calculations. Values for these objects might change independently. The queue might look like this a1, a1, a2, a1, a2, a2, a3... Consumers process each item in the queue. The snapshot has to contain all objects and consumers will process this message for all objects in one go. So the requirement is to have a queue like this: a1, a1, a3, a2, a2, [snapshot, a1, a2, a3], a3, a1 ... The problem is that these items are of different types: one type for objects like a1, a2 and other for a snapshot. This means that they should be processed in a diferent queues, but in that case there is a race condition: consumers might process objects before processing a snapshot. Is there any pattern to solve this (quite common) problem? We are using RabbitMQ for message queueing.

    Read the article

  • VS2010 express beta2 - no add reference dialog, no open file/project dialogs

    - by David
    Just installed VS2010 express for Windows Phone last night. Install went smoothly. It creates a project, compiles, and deploys the app to the emulator. Here's the problem: When I try to "Add Reference" through the Project menu, I do not get the Add Reference dialog box. Same thing if I right click References in the solution explorer and click Add Reference. That's not all. "File...Open" and "File...Open Project" also fail to throw up an open file dialog box. When attempting any of these actions, the IDE quickly loses and regains focus. Even pressing a keyboard shortcut (Ctrl+O) causes the IDE to quickly lose and regain focus, but no open file dialog box appears. This is what I have tried, not particularly in this order: 1. Turned off UAC 2. Monitored file and registry access using Process Monitor during a File...Open operation. File activity showed mostly "SUCCESS" with a few "FAST IO DISALLOWED" and a few "INVALID DEVICE REQUEST" results. Registry activity showed mostly "SUCCESS" with some "NAME NOT FOUND" and a few "BUFFER OVERFLOW" results. 3. Created a new, clean Windows account to run the IDE from 4. Forced a test project to add a reference to "System.Xml.Linq" by editing the ".csproj" project file. Project failed to load in the IDE. I don't have these problems at all on 2 other Windows 7 computers with VS2010 C# express beta 2 installed. One machine is 32bit and the other 64bit, both Home Premium edition. My system: Windows 7 Home Premium, 64bit Other Visual Studio products installed: VS2008 C# express, VS2008 C++ express One other thing to note: Several months ago I installed the non-phone distribution of VS2010 C# express beta 2, and I had the same exact problems. Back then I chalked it up to being beta and went back to VS2008 C# express, where I do not have these issues.

    Read the article

  • Pattern for limiting number of simultaneous asynchronous calls

    - by hitch
    I need to retrieve multiple objects from an external system. The external system supports multiple simultaneous requests (i.e. threads), but it is possible to flood the external system - therefore I want to be able to retrieve multiple objects asynchronously, but I want to be able to throttle the number of simultaneous async requests. i.e. I need to retrieve 100 items, but don't want to be retrieving more than 25 of them at once. When each request of the 25 completes, I want to trigger another retrieval, and once they are all complete I want to return all of the results in the order they were requested (i.e. there is no point returning the results until the entire call is returned). Are there any recommended patterns for this sort of thing? Would something like this be appropriate (pseudocode, obviously)? private List<externalSystemObjects> returnedObjects = new List<externalSystemObjects>; public List<externalSystemObjects> GetObjects(List<string> ids) { int callCount = 0; int maxCallCount = 25; WaitHandle[] handles; foreach(id in itemIds to get) { if(callCount < maxCallCount) { WaitHandle handle = executeCall(id, callback); addWaitHandleToWaitArray(handle) } else { int returnedCallId = WaitHandle.WaitAny(handles); removeReturnedCallFromWaitHandles(handles); } } WaitHandle.WaitAll(handles); return returnedObjects; } public void callback(object result) { returnedObjects.Add(result); }

    Read the article

  • Switch statement usage - C

    - by Jamie Keeling
    Hello, I have a thread function on Process B that contains a switch to perform certain operations based on the results of an event sent from Process A, these are stored as two elements in an array. I set the first element to the event which signals when Process A has data to send and I have the second element set to the event which indicates when Process A has closed. I have began to implement the functionality for the switch statement but I'm not getting the results as I expect. Consider the following: // //Thread function DWORD WINAPI ThreadFunc(LPVOID passedHandle) { for(i = 0; i < 2; i++) { ghEvents[i] = OpenEvent(EVENT_ALL_ACCESS, FALSE, TEXT("Global\\ProducerEvents")); if(ghEvents[i] == NULL) { getlasterror = GetLastError(); } } dwProducerEventResult = WaitForMultipleObjects( 2, ghEvents, FALSE, INFINITE); switch (dwProducerEventResult) { case WAIT_OBJECT_0 + 0: { //Producer sent data //unpackedHandle = *((HWND*)passedHandle); MessageBox(NULL,L"Test",L"Test",MB_OK); break; } case WAIT_OBJECT_0 + 1: { //Producer closed ExitProcess(1); break; } default: return; } } As you can see if the event in the first array is signalled Process B should display a simple message box, if the second array is signalled the application should close. When I actually close Process A, Process B displays the message box instead. If I leave the first case blank (Do nothing) both applications close as they should. Furthermore Process B sends data an error is thrown (When I comment out the unpacking): Have I implemented my switch statement incorrectly? I though I handled the unpacking of the HWND correctly too, any suggestions? Thanks for your time.

    Read the article

  • deepcopy and python - tips to avoid using it?

    - by blackkettle
    Hi, I have a very simple python routine that involves cycling through a list of roughly 20,000 latitude,longitude coordinates and calculating the distance of each point to a reference point. def compute_nearest_points( lat, lon, nPoints=5 ): """Find the nearest N points, given the input coordinates.""" points = session.query(PointIndex).all() oldNearest = [] newNearest = [] for n in xrange(nPoints): oldNearest.append(PointDistance(None,None,None,99999.0,99999.0)) newNearest.append(obj2) #This is almost certainly an inappropriate use of deepcopy # but how SHOULD I be doing this?!?! for point in points: distance = compute_spherical_law_of_cosines( lat, lon, point.avg_lat, point.avg_lon ) k = 0 for p in oldNearest: if distance < p.distance: newNearest[k] = PointDistance( point.point, point.kana, point.english, point.avg_lat, point.avg_lon, distance=distance ) break else: newNearest[k] = deepcopy(oldNearest[k]) k += 1 for j in range(k,nPoints-1): newNearest[j+1] = deepcopy(oldNearest[j]) oldNearest = deepcopy(newNearest) #We're done, now print the result for point in oldNearest: print point.station, point.english, point.distance return I initially wrote this in C, using the exact same approach, and it works fine there, and is basically instantaneous for nPoints<=100. So I decided to port it to python because I wanted to use SqlAlchemy to do some other stuff. I first ported it without the deepcopy statements that now pepper the method, and this caused the results to be 'odd', or partially incorrect, because some of the points were just getting copied as references(I guess? I think?) -- but it was still pretty nearly as fast as the C version. Now with the deepcopy calls added, the routine does it's job correctly, but it has incurred an extreme performance penalty, and now takes several seconds to do the same job. This seems like a pretty common job, but I'm clearly not doing it the pythonic way. How should I be doing this so that I still get the correct results but don't have to include deepcopy everywhere?

    Read the article

  • How to call Twiter's Streaming/Filter Feed with urllib2/httplib?

    - by Simon
    Update: I switched this back from answered as I tried the solution posed in cogent Nick's answer and switched to Google's urlfetch: logging.debug("starting urlfetch for http://%s%s" % (self.host, self.url)) result = urlfetch.fetch("http://%s%s" % (self.host, self.url), payload=self.body, method="POST", headers=self.headers, allow_truncated=True, deadline=5) logging.debug("finished urlfetch") but unfortunately finished urlfetch is never printed - I see the timeout happen in the logs (it returns 200 after 5 seconds), but execution doesn't seem tor return. Hi All- I'm attempting to play around with Twitter's Streaming (aka firehose) API with Google App Engine (I'm aware this probably isn't a great long term play as you can't keep the connection perpetually open with GAE), but so far I haven't had any luck getting my program to actually parse the results returned by Twitter. Some code: logging.debug("firing up urllib2") req = urllib2.Request(url="http://%s%s" % (self.host, self.url), data=self.body, headers=self.headers) logging.debug("called urlopen for %s %s, about to call urlopen" % (self.host, self.url)) fobj = urllib2.urlopen(req) logging.debug("called urlopen") When this executes, unfortunately, my debug output never shows the called urlopen line printed. I suspect what's happening is that Twitter keeps the connection open and urllib2 doesn't return because the server doesn't terminate the connection. Wireshark shows the request being sent properly and a response returned with results. I tried adding Connection: close to my request header, but that didn't yield a successful result. Any ideas on how to get this to work? thanks -Simon

    Read the article

  • Will rel=canonical break site: queries ?

    - by Justin Grant
    Our company publishes our software product's documentation using a custom-built content management system using a dynamic URL namespace like this: http://ourproduct.com/documentation/version/pageid Where "version" is the version number to which the documentation applies, and "pageid" is a unique string which identifies that page in our back-end content management system. For example, if content (e.g. a page about configuration best practices) is unchanged from version 3.0 and 4.0 of our product, it'd be reachable by two different URLs: http://ourproduct.com/documentation/3.0/configuration-best-practices http://ourproduct.com/documentation/4.0/configuration-best-practices This URL scheme allows us to scope Google search results to see only documentaiton for a particular product version, like this: configuration site:ourproduct.com/documentation/4.0 But when the user is searching across all versions, we don't want Google to arbitrarily choose one of the URLs to show in results. Instead, we always want the latest version to show up. Hence our planned use of rel=canonical so we can proscriptively tell Google which URL we want to show up if multiple versions are being searched. (Users who do oddball things like searching 2 versions but not all of them are a corner case, so we don't care which version(s) show up in that case-- the primary use-cases we care about is searching one version or searching all versions) But what will happen to scoped searches if we do this? If my rel=canonical URL points to version 4.0, but my search is scoped to 3.0, will Google return a result? Even if you don't know the answer offhand, do you know a site which uses rel=canonical to redirect across folders in a URL namespace. If so, I could run a few Google searches and figure out the answer.

    Read the article

  • Maven Mojo & SCM Plugin: Check for a valid working directory

    - by Patrick Bergner
    Hi there. I'm using maven-scm-plugin from within a Mojo and am trying to figure out how to determine if a directory D is a valid working directory of an SCM URL U (i.e. a checkout of U to D already happened). The context is that I want to do a checkout of U if D is a working set or do an update if it isn't. The plan is to check out U to D if D does not exist, update D if D is a valid working directory of U, display an error if D exists and is not a valid working directory of U. What I tried is to call ScmManager.status(), ScmManager.list() and ScmManager.changelog() and try to guess something from their results. But that didn't work. The results from status and changelog always return something positive (isSuccess() = true, getChangedFiles() = valid List, no exceptions to catch), whereas list throws an exception in any case. ScmRepository and ScmFileSet don't seem to provide suitable methods as well. An option would be to always do an update if D exists but then I cannot tell if it is a working directory of U or any SCM working directory at all. The ideal solution would be independent of the actual SCM system and a specific ScmVersion. Thanks for your help! Patrick

    Read the article

  • How to update the user profile through tokenid when a particular user logs in using his username and password

    - by Rani
    i have an application in which when the user enters his username and password in the login form , his username and password are submitted to the server database for validation and if he is a valid user a tokenid is generated for him through JSON response and he is allowed to log in.this is the JSON response that i get in the console when a valid user log in through the log in form : {"TokenID":"kaenn43otO","isError":false,"ErrorMessage":"","Result":[{"UserId":"164","FirstName":"Indu","LastName":"nair","Email":"[email protected]","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"22"}],"ErrorCode":900} 2011-06-24 11:56:57.639 Journey[5526:207] this is token id:kaenn43otO so when the same user wants to update his profile by clicking on the update tab using the tokenid So that if he want he can his firstname,lastname,password,email.etc.i i have done the following code to update the user profile using tokenid but it does not work.i get tokenid when the user log in and this tokenid i have to pass to other class: this is my code to update user profile: -(void)sendRequest { //this is the class in which i get the tokenid and i am passing it to this class apicontroller *apitest = [[apicontroller alloc]init]; NSString *tokentest = apitest.tokenapi; NSString *post = [NSString stringWithFormat:@"Token=%@&firstname=%@&lastname=%@&Username=%@&Password=%@&Email=%@",tokentest,txtfirstName.text,txtlast.text,txtUserName.text,txtPassword.text,txtEmail.text]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSLog(@"%@",postLength); NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:@"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Register&Command=SET"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (theConnection) { webData = [[NSMutableData data] retain]; NSLog(@"%@",webData); [theConnection start]; } else { } } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [webData setLength: 0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [webData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [connection release]; [webData release]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; NSLog(@"%@",loginStatus); [loginStatus release]; [connection release]; [webData release]; } -(IBAction)click:(id)sender { [self sendRequest]; } this is my apicontroller.m file in which i am creating login form so that user login and in this page tokenid is generated -(void)sendRequest { UIDevice *device = [UIDevice currentDevice]; NSString *udid = [device uniqueIdentifier]; //NSString *sysname = [device systemName]; NSString *sysver = [device systemVersion]; NSString *model = [device model]; NSLog(@"idis:%@",[device uniqueIdentifier]); NSLog(@"system nameis :%@",[device systemName]); NSLog(@"System version is:%@",[device systemVersion]); NSLog(@"System model is:%@",[device model]); NSLog(@"device orientation is:%d",[device orientation]); NSString *post = [NSString stringWithFormat:@"Loginkey=%@&Password=%@&DeviceCode=%@&Firmware=%@&IMEI=%@",txtUserName.text,txtPassword.text,model,sysver,udid]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSLog(@"%@",postLength); NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; [request setURL:[NSURL URLWithString:@"http://192.168.0.1:96/JourneyMapperAPI?RequestType=Login"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; if (theConnection) { webData = [[NSMutableData data] retain]; NSLog(@"%@",webData); } else { } } //to select username and password from database. -(void)check { //app.journeyList = [[NSMutableArray alloc]init]; [self createEditableCopyOfDatabaseIfNeeded]; NSString *filePath = [self getWritableDBPath]; sqlite3 *database; if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { const char *sqlStatement = "SELECT Username,Password FROM UserInformation where Username=? and Password=?"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { sqlite3_bind_text(compiledStatement, 1, [txtUserName.text UTF8String], -1, SQLITE_TRANSIENT); sqlite3_bind_text(compiledStatement, 2, [txtPassword.text UTF8String], -1, SQLITE_TRANSIENT); //NSString *loginname= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]; // NSString *loginPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)]; } if(sqlite3_step(compiledStatement) != SQLITE_ROW ) { NSLog( @"Save Error: %s", sqlite3_errmsg(database) ); UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"User is not valid" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; alert = nil; } else { isUserValid = YES; if (isUserValid) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Valid User" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; } } sqlite3_finalize(compiledStatement); } sqlite3_close(database); } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [webData setLength: 0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [webData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { [connection release]; [webData release]; } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]; NSLog(@"%@",loginStatus); //this is to perfrom insert opertion on the userinformation table NSString *json_string = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding]; NSDictionary *result = [json_string JSONValue]; //here i am storing the tokenid tokenapi = [result objectForKey:@"TokenID"]; NSLog(@"this is token id:%@",tokenapi); // BOOL errortest = [[result objectForKey:@"isError"] boolValue]; if(errortest == FALSE) { values = [result objectForKey:@"Result"]; NSLog(@"Valid User"); } else { NSLog(@"Invalid User"); } NSMutableArray *results = [[NSMutableArray alloc] init]; for (int index = 0; index<[values count]; index++) { NSMutableDictionary * value = [values objectAtIndex:index]; Result * result = [[Result alloc] init]; //through this i get the userid result.UserID = [value objectForKey:@"UserId"]; result.FirstName = [value objectForKey:@"FirstName"]; result.Username =[value objectForKey:@"Username"]; result.Email =[value objectForKey:@"Email"]; result.ProfileImage =[value objectForKey:@"ProfileImage"]; result.ThumbnailImage =[value objectForKey:@"ThumbnailImage"]; result.DeviceInfoId =[value objectForKey:@"DeviceInfoId"]; NSLog(@"%@",result.UserID); [results addObject:result]; [result release]; } for (int index = 0; index<[results count]; index++) { Result * result = [results objectAtIndex:index]; //save the object variables to database here [self createEditableCopyOfDatabaseIfNeeded]; NSString *filePath = [self getWritableDBPath]; sqlite3 *database; if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) { const char *sqlStatement = "insert into UserInformation(UserID,DeviceId,Username,Password,FirstName,Email) VALUES (?,?,?,?,?,?)"; sqlite3_stmt *compiledStatement; if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) { //sqlite3_bind_text( compiledStatement, 1, [journeyid UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text( compiledStatement, 1, [result.UserID UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text(compiledStatement, 2, [result.DeviceInfoId UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text(compiledStatement, 3, [txtUserName.text UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text(compiledStatement, 4, [txtPassword.text UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text (compiledStatement, 5, [result.FirstName UTF8String],-1,SQLITE_TRANSIENT); sqlite3_bind_text (compiledStatement, 6, [result.Email UTF8String],-1,SQLITE_TRANSIENT); } if(sqlite3_step(compiledStatement) != SQLITE_DONE ) { NSLog( @"Save Error: %s", sqlite3_errmsg(database) ); } else { UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"UIAlertView" message:@"Record added" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; alert = nil; } sqlite3_finalize(compiledStatement); } sqlite3_close(database); } [loginStatus release]; [connection release]; [webData release]; } -(IBAction)click:(id)sender { [self sendRequest]; //this is to select username and password from database. [self check]; } for a particular user who logs in only his profile must be update by using tokenid and userid.Please help me in solving this problem.Thanks

    Read the article

  • How to test a struts 2.1.x developer?

    - by Jason Pyeron
    We employ test to filter out those who can't. The tests are designed to be very low effort for those who can and too much effort for those who can't. Here is an example for java web application developer on an Oracle project: We only work with contractors who can use the tools we use, to determine if you can use the tools we have devised some very simple tests. Instructions If you are prepared and knowledgeable this will take you about 2-5 minutes. Suggested knowledge and tools: * subversion 1.6 see http://subversion.tigris.org/ or http://cygwin.com/setup.exe * java 1.6 see http://java.sun.com/javase/downloads/index.jsp * oracle >=10g see http://www.oracle.com/technology/software/products/jdev/index.html * j2ee server see http://tomcat.apache.org/download-55.cgi or http://www.jboss.org/jbossas/downloads/ Steps 1. check out svn://statics32.pdinc.us/home/subversion/guest 2. deploy the war file found at trunk/test.war 3. browse to the web application you installed from the war file and answer the one SQL question: How many rows are in the table 'testdata' where column 'value' ends with either an 'A' or an 'a'? The login credentials are in trunk/doc/oracle.txt 4. make a RESULTS HASH by submitting your answer to the form. 5. create a file in tmp/YourUserName.txt and put the RESULTS HASH in it, not the answer. 6. check in your file (don't forget to add the file first). 7. message me with the revision number of your check in. As such I am looking for ideas on how to test for someone to be a struts 2.1 w/ annotations.

    Read the article

  • Criteria API - How to get records based on collection count?

    - by Cosmo
    Hello Guys! I have a Question class in ActiveRecord with following fields: [ActiveRecord("`Question`")] public class Question : ObcykaniDb<Question> { private long id; private IList<Question> relatedQuestions; [PrimaryKey("`Id`")] private long Id { get { return this.id; } set { this.id = value; } } [HasAndBelongsToMany(typeof(Question), ColumnRef = "ChildId", ColumnKey = "ParentId", Table = "RelatedQuestion")] private IList<Question> RelatedQuestions { get { return this.relatedQuestions; } set { this.relatedQuestions = value; } } } How do I write a DetachedCriteria query to get all Questions that have at least 5 related questions (count) in the RelatedQuestions collection? For now this gives me strange results: DetachedCriteria dCriteria = DetachedCriteria.For<Question>() .CreateCriteria("RelatedQuestions") .SetProjection(Projections.Count("Id")) .Add(Restrictions.EqProperty(Projections.Id(), "alias.Id")); DetachedCriteria dc = DetachedCriteria.For<Question>("alias").Add(Subqueries.Le(5, dCriteria)); IList<Question> results = Question.FindAll(dc); Any ideas what I'm doing wrong?

    Read the article

  • gridview commandargument on buttonfield pagination used

    - by ClareBear
    Hello all, I am using c#.net I have a gridview which needs to contain a 'Use' button (appointmentId set as the commandargument). Source Code <asp:GridView ID="resultsReturned" runat="server" AllowPaging="True" AutoGenerateColumns="False" EnableSortingAndPagingCallbacks="True" OnPageIndexChanged="resultsReturned_PageIndexChanged" onrowcommand="resultsReturned_RowCommand"> <Columns> <asp:BoundField DataField="UserAppointmentId" HeaderText="App ID" /> <asp:BoundField DataField="UserBookingName" HeaderText="Booking Name" /> <asp:TemplateField> <ItemTemplate> <asp:Button runat="server" ID="UseButton" Text="Use" CommandName="Use" CommandArgument="UserAppointmentId" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> Code-Behind protected void resultsReturned_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Use") { correctAppointmentID.Value = (e.CommandArgument.ToString()); } } This is used for the pagination: private void BindAppointments() { var results = appointmentRepos.GetBookingIdBySearchCriteria(catgoryid, resultsReturned.PageIndex * resultsReturned.PageSize, -1); resultsReturned.DataSource = results; resultsReturned.DataBind(); } I am binding the appointments to the gridview within the PageLoad/search_Click This is the error I am receiving: Callbacks are not supported on TemplateField because some controls cannot update properly in a callback. Turn callbacks off on 'resultsReturned'. Thanks in advance for any help Clare

    Read the article

  • SQL Server 2005, wide indexes, computed columns, and sargable queries

    - by luksan
    In my database, assume we have a table defined as follows: CREATE TABLE [Chemical]( [ChemicalId] int NOT NULL IDENTITY(1,1) PRIMARY KEY, [Name] nvarchar(max) NOT NULL, [Description] nvarchar(max) NULL ) The value for Name can be very large, so we must use nvarchar(max). Unfortunately, we want to create an index on this column, but nvarchar(max) is not supported inside an index. So we create the following computed column and associated index based upon it: ALTER TABLE [Chemical] ADD [Name_Indexable] AS LEFT([Name], 20) CREATE INDEX [IX_Name] ON [Chemical]([Name_Indexable]) INCLUDE([Name]) The index will not be unique but we can enforce uniqueness via a trigger. If we perform the following query, the execution plan results in a index scan, which is not what we want: SELECT [ChemicalId], [Name], [Description] FROM [Chemical] WHERE [Name]='[1,1''-Bicyclohexyl]-2-carboxylic acid, 4'',5-dihydroxy-2'',3-dimethyl-5'',6-bis[(1-oxo-2-propen-1-yl)oxy]-, methyl ester' However, if we modify the query to make it "sargable," then the execution plan results in an index seek, which is what we want: SELECT [ChemicalId], [Name], [Description] FROM [Chemical] WHERE [Indexable_Name]='[1,1''-Bicyclohexyl]-' AND [Name]='[1,1''-Bicyclohexyl]-2-carboxylic acid, 4'',5-dihydroxy-2'',3-dimethyl-5'',6-bis[(1-oxo-2-propen-1-yl)oxy]-, methyl ester' Is this a good solution if we control the format of all queries executed against the database via our middle tier? Is there a better way? Is this a major kludge? Should we be using full-text indexing?

    Read the article

  • How to include frameset under CGI.pm

    - by neversaint
    I want to have a cgi-script that does two things. Take the input from a form. Generate results base on the input values on a frame. Primarily I want the frame exist only after the results is generated/printed. Below is the simplified code of what I want to do. But somehow it doesn't work. What's the right way to do it? #!/usr/local/bin/perl use CGI ':standard'; print header; print start_html('A Simple Example'), h1('A Simple Example'), start_form, "What's your name? ",textfield('name'), p, "What's the combination?", p, checkbox_group(-name=>'words', -values=>['eenie','meenie','minie','moe'], -defaults=>['eenie','minie']), p, "What's your favorite color? ", popup_menu(-name=>'color', -values=>['red','green','blue','chartreuse']), p, submit, end_form, hr; if (param()) { # begin create the frame print <<EOF; <html><head><title>$TITLE</title></head> <frameset rows="10,90"> <frame src="$script_name/query" name="query"> <frame src="$script_name/response" name="response"> </frameset> EOF # Finish creating frame print "Your name is: ",em(param('name')), p, "The keywords are: ",em(join(", ",param('words'))), p, "Your favorite color is: ",em(param('color')), hr; } print end_html;

    Read the article

  • Is there any other efficient way to use table variable instead of using temporary table

    - by varta shrimali
    we are writing script to display banners on a web page where we are using temporary table in mysql procedure. Is there any other efficient way to use table variable instead of using temporary table we are using following code: -- banner location CURSOR -- DECLARE banner_location_cursor CURSOR FOR select bm.id as masterId, bm.section as masterName, bs.id as locationId, bs.sectionName as locationName from banner_master as bm inner join banner_section as bs on bm.id=bs.masterId where bm.section=sCode ; -- DECLARE banner CURSORS DECLARE banner_cursor CURSOR FOR SELECT bd.id as bannerId, bd.sectionId, bd.bannerName, bd.websiteURL, bd.paymentType, bd.status, bd.startDate, bd.endDate, bd.bannerDisplayed, bs.id, bs.sectionName from banner_detail as bd inner join banner_section as bs on bs.id=bd.sectionId where bs.id= location_id and bd.status='A' and (dates between cast(bd.startDate as DATE) and cast(bd.endDate as DATE)) order by rand(), bd.bannerDisplayed asc limit 1 ; DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_rows = 1; SET dates = (select curdate()); -- RESULTS TABLE WHICH WILL BE RETURNED -- CREATE temporary TABLE test ( b_id INT, s_id INT, b_name varchar(128), w_url varchar(128), p_type varchar(128), st char(1), s_date datetime, e_date datetime, b_display int, sec_id int, s_name varchar(128) ); -- OPEN banner location CURSOR OPEN banner_location_cursor; the_loop: LOOP FETCH banner_location_cursor INTO master_id, master_name, location_id, location_name; IF no_more_rows THEN CLOSE banner_location_cursor; leave the_loop; END IF; OPEN banner_cursor; -- select FOUND_ROWS(); the_loop2: LOOP FETCH banner_cursor INTO banner_id, section_id, banner_name, website_url, payment, status, start_date, end_date, banner_displayed, sec_id, section_name; IF no_more_rows THEN set no_more_rows = 0; CLOSE banner_cursor; leave the_loop2; END IF; INSERT INTO test ( b_id, s_id, b_name , w_url, p_type, st, s_date, e_date, b_display, sec_id, s_name ) VALUES ( banner_id, section_id, banner_name, website_url, payment, status, start_date, end_date, banner_displayed, sec_id, section_name ); UPDATE banner_detail set bannerDisplayed = (banner_displayed+1) where id = banner_id; END LOOP the_loop2; END LOOP the_loop; -- RETURN result SELECT * FROM test; -- DROP RESULTS TABLE DROP TABLE test; END

    Read the article

< Previous Page | 150 151 152 153 154 155 156 157 158 159 160 161  | Next Page >