Search Results

Search found 37183 results on 1488 pages for 'string conversion'.

Page 157/1488 | < Previous Page | 153 154 155 156 157 158 159 160 161 162 163 164  | Next Page >

  • ArrayList<String> NullPointerException

    - by Carlucho
    Am trying to solve a labyrinth by DFS, using adj List to represent the vertices and edges of the graph. In total there are 12 nodes (3 rows[A,B,C] * 4 cols[0,..,3]). My program starts by saving all the vertex labels (A0,..C3), so far so good, then checks the adjacent nodes, also no problems, if movement is possible, it proceeds to create the edge, here its where al goes wrong. adjList[i].add(vList[j].label); I used the debugger and found that vList[j].label is not null it contains a correct string (ie. "B1"). The only variables which show null are in adjList[i], which leads me to believe i have implemented it wrongly. this is how i did it. public class GraphList { private ArrayList<String>[] adjList; ... public GraphList(int vertexcount) { adjList = (ArrayList<String>[]) new ArrayList[vertexCount]; ... } ... public void addEdge(int i, int j) { adjList[i].add(vList[j].label); //NULLPOINTEREXCEPTION HERE } ... } I will really appreaciate if anyone can point me on the right track regrading to what its going wrong... Thanks!

    Read the article

  • std::string insert method has ambiguous overloads?

    - by sdg
    Environment: VS2005 C++ using STLPort 5.1.4. Compiling the following code snippet: std::string copied = "asdf"; char ch = 's'; copied.insert(0,1,ch); I receive an error: Error 1 error C2668: 'stlpx_std::basic_string<_CharT,_Traits,_Alloc>::insert' : ambiguous call to overloaded function It appears that the problem is the insert method call on the string object. The two defined overloads are void insert ( iterator p, size_t n, char c ); string& insert ( size_t pos1, size_t n, char c ); But given that STLPort uses a simple char* as its iterator, the literal zero in the insert method in my code is ambiguous. So while I can easily overcome the problem by hinting such as copied.insert(size_t(0),1,ch); My question is: is this overloading and possible ambiguity intentional in the specification? Or more likely an unintended side-effect of the specific STLPort implementation? (Note that the Microsoft-supplied STL does not have this problem as it has a class for the iterator, instead of a naked pointer)

    Read the article

  • SQL Server getdate() to a string like "2009-12-20"

    - by Adam Kane
    In Microsoft SQL Server 2005 and .NET 2.0, I want to convert the current date to a string of this format: "YYYY-MM-DD". For example, December 12th 2009 would become "2009-12-20". How do I do this in SQL. The context of this SQL statement in the table definiton. In other words, this is the default value. So when a new record is created the default value of the current date is stored as a string in the above format. I'm trying: SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD] But SQL server keeps converting that to: ('SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD]') so the result is just: 'SELECT CONVERT(VARCHAR(10), GETDATE(), 102) AS [YYYY.MM.DD]' Here's a screen shot of what the Visual Studio server explorer, table, table definition, properties shows: These wrapper bits are being adding automatically and converting it all to literal string: (N' ') Here's the reason I'm trying to use something other than the basic DATETIME I was using previously: This is the error I get when hooking everything to an ASP.NET GridView and try to do an update via the grid view: Server Error in '/' Application. The version of SQL Server in use does not support datatype 'date'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentException: The version of SQL Server in use does not support datatype 'date'. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [ArgumentException: The version of SQL Server in use does not support datatype 'date'.] Note: I've added a related question to try to get around the SQL Server in use does not support datatype 'date' error so that I can use a DATETIME as recommended.

    Read the article

  • Add less than integer variable to string search

    - by user1691832
    I'm scanning a text document for certain installed programs on a computer and looking for an easy way to include a greater or less than variable in the string I'm scanning for. Here is a very ugly and cumbersome example of what I'm using currently and while it works as a temporary fix, isn't practical or sustainable. If CheckBox2.Checked Then sReader.Close() If text.Contains("Adobe Flash Player 11 Plugin") And text.Contains("Adobe Flash Player 11 ActiveX") Then Else If text.Contains("Adobe Flash Player 12 Plugin") And text.Contains("Adobe Flash Player 12 ActiveX") Then Else If text.Contains("Adobe Flash Player 13 Plugin") And text.Contains("Adobe Flash Player 13 ActiveX") Then Else '(Goes ahead and does a silent install of the missing or outdated program) So far I've run into this problem with both Adobe Flash and Java RTE and am certain to run into it with future programs. Essentially I need to scan for "Adobe Flash Player (Any number less than 11) Plugin" , "Adobe Flash Player (Any number less than 11) ActiveX" , "Java (number less than 9) Update (any number)". I'm sure whatever solution is offered can likely be adapted to similar programs I'm likely to encounter later. Thanks ----- Edit ----- I've since tried the following code but it always returns the "Found" messagebox, even when no version of adobe flash is present in the file it is scanning. If CheckBox2.Checked Then sReader.Close() Dim options As RegexOptions = RegexOptions.None Dim regex As Regex = New Regex("Adobe Flash Player (?<version>\d+) (Plugin|ActiveX)", options) Dim input As String = "Adobe Flash Player 11 Plugin" ' Get match Dim match As Match = regex.Match(input) Dim version As String = match.Groups("version").Value If (match.Success) Then MessageBox.Show("Version 11 or higher found, skipping install") Else MessageBox.Show("Version 11 or higher not found, installing Version 11")

    Read the article

  • atol(), atof(), atoi() function behaviours, is there a stable way to convert from/to string/integer

    - by Berkay
    In these days i'm playing with the C functions of atol(), atof() and atoi(), from a blog post i find a tutorial and applied: here are my results: void main() char a[10],b[10]; puts("Enter the value of a"); gets(a); puts("Enter the value of b"); gets(b); printf("%s+%s=%ld and %s-%s=%ld",a,b,(atol(a)+atol(b)),a,b,(atol(a)-atol(b))); getch(); } there is atof() which returns the float value of the string and atoi() which returns integer value. now to see the difference between the 3 i checked this code: main() { char a[]={"2545.965"}; printf("atol=%ld\t atof=%f\t atoi=%d\t\n",atol(a),atof(a),atoi(a)); } the output will be atol=2545 atof=2545.965000 atoi=2545 char a[]={“heyyou”}; now when you run the program the following will be the output (why?, is there any solution to convert pure strings to integer?) atol=0 atof=0 atoi=0 the string should contain numeric value now modify this program as char a[]={“007hey”}; the output in this case(tested in Red hat) will be atol=7 atof=7.000000 atoi=7 so the functions has taken 007 only not the remaining part (why?) Now consider this char a[]={“hey007?}; the output of the program will be atol=0 atof=0.000000 atoi=0 So i just want to convert my strings to number and then again to same text, i played with these functions and as you see i'm getting really interesting results? why is that? any other functions to convert from/to string/integer and vice versa?

    Read the article

  • Why does first call to java.io.File.createTempFile(String,String,File) take 5 seconds on Citrix?

    - by Ben Roling
    While debugging slow startup of an Eclipse RCP app on a Citrix server, I came to find out that java.io.createTempFile(String,String,File) is taking 5 seconds. It does this only on the first execution and only for certain user accounts. Specifically, I am noticing it Citrix anonymous user accounts. I have not tried many other types of accounts, but this behavior is not exhibited with an administrator account. Also, it does not matter if the user has access to write to the given directory or not. If the user does not have access, the call will take 5 seconds to fail. If they do have access, the call with take 5 seconds to succeed. This is on a Windows 2003 Server. I've tried Sun's 1.6.0_16 and 1.6.0_19 JREs and see the same behavior. I googled a bit expecting this to be some sort of known issue, but didn't find anything. It seems like someone else would have had to have run into this before. The Eclipse Platform uses File.createTempFile() to test various directories to see if they are writeable during initialization and this issue adds 5 seconds to the startup time of our application. I imagine somebody has run into this before and might have some insight. Here is sample code I executed to see that it is indeed this call that is consuming the time. I also tried it with a second call to createTempFile and notice that subsequent calls return nearly instantaneously. public static void main(final String[] args) throws IOException { final File directory = new File(args[0]); final long startTime = System.currentTimeMillis(); File file = null; try { file = File.createTempFile("prefix", "suffix", directory); System.out.println(file.getAbsolutePath()); } finally { System.out.println(System.currentTimeMillis() - startTime); if (file != null) { file.delete(); } } } Sample output of this program is the following: C:\java.exe -jar filetest.jar C:/Temp C:\Temp\prefix8098550723198856667suffix 5093

    Read the article

  • Using a string inside the DocumentBuilder parse method (need it for parsing XML using XPath)

    - by dierre
    Hi guys! I'm trying to create a RESTful webservice using a Java Servlet. The problem is I have to pass via POST method to a webserver a request. The content of this request is not a parameter but the body itself. So I basically send from ruby something like this: url = URI.parse(@host) req = Net::HTTP::Post.new('/WebService/WebServiceServlet') req['Content-Type'] = "text/xml" # req.basic_auth 'account', 'password' req.body = data response = Net::HTTP.start(url.host, url.port){ |http| puts http.request(req).body } Then I have to retrieve the body of this request in my servlet. I use the classic readline, so I have a string. The problem is when I have to parse it as XML: private void useXML( final String soft, final PrintWriter out) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, FileNotFoundException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); // never forget this! DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(soft); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); XPathExpression expr = xpath.compile("//software/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { out.println(nodes.item(i).getNodeValue()); } } The problem is that builder.parse() accepts: parse(File f), parse(InputSource is), parse(InputStream is). Is there any way I can transform my xml string in an InputSource or something like that? I know it could be a dummy question but Java is not my thing, I'm forced to use it and I'm not very skilled.

    Read the article

  • Trouble with building up a string in Clojure

    - by Aki Iskandar
    Hi gang - [this may seem like my problem is with Compojure, but it isn't - it's with Clojure] I've been pulling my hair out on this seemingly simple issue - but am getting nowhere. I am playing with Compojure (a light web framework for Clojure) and I would just like to generate a web page showing showing my list of todos that are in a PostgreSQL database. The code snippets are below (left out the database connection, query, etc - but that part isn't needed because specific issue is that the resulting HTML shows nothing between the <body> and </body> tags). As a test, I tried hard-coding the string in the call to main-layout, like this: (html (main-layout "Aki's Todos" "Haircut<br>Study Clojure<br>Answer a question on Stackoverfolw")) - and it works fine. So the real issue is that I do not believe I know how to build up a string in Clojure. Not the idiomatic way, and not by calling out to Java's StringBuilder either - as I have attempted to do in the code below. A virtual beer, and a big upvote to whoever can solve it! Many thanks! ============================================================= ;The master template (a very simple POC for now, but can expand on it later) (defn main-layout "This is one of the html layouts for the pages assets - just like a master page" [title body] (html [:html [:head [:title title] (include-js "todos.js") (include-css "todos.css")] [:body body]])) (defn show-all-todos "This function will generate the todos HTML table and call the layout function" [] (let [rs (select-all-todos) sbHTML (new StringBuilder)] (for [rec rs] (.append sbHTML (str rec "<br><br>"))) (html (main-layout "Aki's Todos" (.toString sbHTML))))) ============================================================= Again, the result is a web page but with nothing between the body tags. If I replace the code in the for loop with println statements, and direct the code to the repl - forgetting about the web page stuff (ie. the call to main-layout), the resultset gets printed - BUT - the issue is with building up the string. Thanks again. ~Aki

    Read the article

  • Getting the data inside the C# web service from Jsonified string

    - by gnomixa
    In my JS I use Jquery's $ajax functions to call the web service and send the jsonified data to it. The data is in the following format: var countries = { "1A": { id: "1A", name: "Andorra" }, "2B": { id: 2B name: "Belgium" }, ..etc }; var jsonData = JSON.stringify({ data: data }); //then $ajax is called and it makes the call to the c# web service On the c# side the web service needs to unpack this data, currently it comes in as string[][] data type. How do I convert it to the format so I can refer to the properties such as .id and .name? Assuming I have a class called Sample with these properties? Thanks! EDIT: Here is my JS code: var jsonData = JSON.stringify(countries); $.ajax({ type: 'POST', url: 'http://localhost/MyService.asmx/Foo', contentType: 'application/json; charset=utf-8', data: jsonData, success: function (msg) { alert(msg.d); }, error: function (xhr, status) { switch (status) { case 404: alert('File not found'); break; case 500: alert('Server error'); break; case 0: alert('Request aborted'); break; default: alert('Unknown error ' + status); } } }); inside c# web service I have: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data; using System.Collections; using System.IO; using System.Web.Script.Services; [WebMethod] [ScriptMethod] public string Foo(IDictionary<string, Country> countries) { return "success"; }

    Read the article

  • How to decrypt a string encrypted with HMACSHA1?

    - by Bob
    I'm an encryption novice trying to pass some values back and forth between systems. I can encrypt the value, but can't seem to figure out how to decrypt on the other end. I've created a simple Windows Forms application using VB.NET. Trying to input a value and a key, encrypt and then decrypt to get the original value. Here's my code so far. Any help greatly appreciated. Thanks. Imports System Imports System.IO Imports System.Security.Cryptography Imports System.Text Public Class Form1 Private Sub btnEncode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEncode.Click Dim hmacsha1 As New HMACSHA1(Encoding.ASCII.GetBytes(txtKey.Text)) Dim hashValue As Byte() = hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(txtValue.Text)) txtResult.Text = BytesToHexString(hashValue) hmacsha1.Clear() End Sub Private Sub btnDecode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDecode.Click '??? End Sub Private Function BytesToHexString(ByVal bytes As Byte()) As String Dim output As String = String.Empty Dim i As Integer = 0 Do While i < bytes.Length output += bytes(i).ToString("X2") i += 1 Loop Return output End Function End Class

    Read the article

  • bool as object vs string as object testing equality

    - by Ray Pendergraph
    I am relatively new to C# and I noticed something interesting today that I guess I have never noticed or perhaps I am missing something. Here is an NUnit test to give an example: object boolean1 = false; object booloan2 = false; Assert.That(boolean1 == booloan2); This unit test fails, but this one passes: object string1 = "string"; object string2 = "string"; Assert.That(string1 == string2); I'm not that surprised in and of itself that the first one fails seeing as boolean1 and boolean2 are different references. But it is troubling to me that the first one fails and the second one passes. I read (on MSDN somewhere) that some magic was done to the String class to facilitate this. I think my question really is why wasn't this behavior replicated in bool? As a note... if the boolean1 and 2 are declared as "bool" then there is no problem. Does anyone know the reason for these differences or why it was implemented that way? Can anyone think of a situation where you would want to reference a bool object for anything except its value?

    Read the article

  • perl - converting a date into a string

    - by Jason
    I need to convert a date to a string, the date is entered as 07/04/2010 and should then read July 4th 2010. It should also be able to be entered using singe digits instead of double (7 instead of 07, and it needs to add the 20 to the year if the user enters only /10) This is what I have so far - #!/usr/bin/perl use CGI qw(:standard); use strict; #declare variables my ($date, $month, $day, $year); my @months = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); #assign input item to variable $date = param('Date'); #break date apart $date =~ /([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{2,2}|20[0-9]{2,2})/; $month = $1; $day = $2; $year = $3; unless($year =~ /20[0-9]{2,2}/){ $year = "20".$year; } $date = $months[int($1)]." ".$day.", ".$year; #display date print "<HTML><HEAD><TITLE>The Date</TITLE></HEAD>\n"; print "<BODY>\n"; print "The date is: $date\n"; print "</BODY></HTML>\n"; However I keep getting errors Use of uninitialized value in pattern match (m//) at c08ex6.cgi line 14. Use of uninitialized value in pattern match (m//) at c08ex6.cgi line 18. Use of uninitialized value in concatenation (.) or string at c08ex6.cgi line 19. Use of uninitialized value in int at c08ex6.cgi line 21. Use of uninitialized value in concatenation (.) or string at c08ex6.cgi line 21.

    Read the article

  • mod rewrite to remove facebook query string

    - by user905752
    I can't get my query string to work..please help... I have the following url: http://betatest.bracknell-forest.gov.uk/help?fb_action_ids=372043216205703&fb_action_types=og.likes&fb_source=aggregation&fb_aggregation_id=288381481237582 (sorry but the page will be unavailable as it is a test internal domain link) I want the following url: http://betatest.bracknell-forest.gov.uk/help I get a browser message saying 'The system cannot find the file specified.' I know it is because I already have a mod rewrite to remove the .htm from the page name to return clean urls but I don't know what I need to do to accept a clean url and return the page. Here is the mod rewrite code I have: RewriteRule ^/([\w]+)$ /$1.htm [I,L] #Any bare URL will get rewritten to a URL with .htm appended RedirectRule ^/(.+)\.(htm)$ http://betatest.bracknell-forest.gov.uk/$1 [R=301] RewriteCond %{QUERY_STRING} ^fb_action_ids=(.)$ #if the query string contains fb_action_ids RewriteCond %{QUERY_STRING} !="" #if there is a query string RewriteRule ^(.*) $1? [R=301,L] I think it is because I am using R=301 twice but do not know what I need to use as an alternative. If I append .htm from help?fb_action_ids.... to help.htm?fb_action_ids.... this returns the required page fine but I need to return the page name for the non appended url. Many thanks for any help in advance.

    Read the article

  • Count Occurence of Needle String in Haystack String, most optimally?

    - by Taranfx
    The Problem is simple Find "ABC" in "ABCDSGDABCSAGAABCCCCAAABAABC" Here is the solution I propose, I'm looking for any solutions that might be better than this one. public static void main(String[] args) { String haystack = "ABCDSGDABCSAGAABCCCCAAABAABC"; String needle = "ABC"; char [] needl = needle.toCharArray(); int needleLen = needle.length(); int found=0; char hay[] = haystack.toCharArray(); int index =0; int chMatched =0; for (int i=0; i<hay.length; i++){ if (index >= needleLen || chMatched==0) index=0; System.out.print("\nchar-->"+hay[i] + ", with->"+needl[index]); if(hay[i] == needl[index]){ chMatched++; System.out.println(", matched"); }else { chMatched=0; index=0; if(hay[i] == needl[index]){ chMatched++; System.out.print("\nchar->"+hay[i] + ", with->"+needl[index]); System.out.print(", matched"); }else continue; } if(chMatched == needleLen){ found++; System.out.println("found. Total ->"+found); } index++; } System.out.println("Result Found-->"+found); } It took me a while creating this one. Can someone suggest a better solution (if any) P.S. Drop the sysouts if they look messy to you.

    Read the article

  • Display HttpResponse (string from Handler) in new WebView

    - by datguywhowanders
    I have the following code in a form's submit button onClickListener: String action, user, pwd, user_field, pwd_field; action = "theURL"; user_field = "id"; pwd_field = "pw"; user = "username"; pwd = "password!!"; List<NameValuePair> myList = new ArrayList<NameValuePair>(); myList.add(new BasicNameValuePair(user_field, user)); myList.add(new BasicNameValuePair(pwd_field, pwd)); HttpParams params = new BasicHttpParams(); HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(action); HttpResponse end = null; String endResult = null; try { post.setEntity(new UrlEncodedFormEntity(myList)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { HttpResponse response = client.execute(post); end = response; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BasicResponseHandler myHandler = new BasicResponseHandler(); try { endResult = myHandler.handleResponse(end); } catch (HttpResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } How can I take the resulting string (endResult) and start a new activity using an intent that will open webview and load the html?

    Read the article

  • format an xml string in Ruby

    - by user1476512
    given an xml string like this : <some><nested><xml>value</xml></nested></some> what's the best option(using ruby) to format it readable like : <some> <nested> <xml>value</xml> </nested> </some> I've found an answer here: what's the best way to format an xml string in ruby?, which is really helpful. But it formats xml like: <some> <nested> <xml> value </xml> </nested> </some> As my xml string is a little big in length. So it is not readable in this format. Thanks in advance!

    Read the article

  • Retrieve class name hierarchy as string

    - by Jeff Wain
    Our system complexity has risen to the point that we need to make permission names tied to the client from the database more specific. In the client, permissions are referenced from a static class since a lot of client functionality is dependent on the permissions each user has and the roles have a ton of variety. I've referenced this post as an example, but I'm looking for a more specific use case. Take for instance this reference, where PermissionAlpha would be a const string: return HasPermission(PermissionNames.PermissionAlpha); Which is great, except now that things are growing more complex the classes are being structured like this: public static class PermissionNames { public static class PermissionAlpha { public const string SubPermission; } } I'm trying to find an easy way to reference PermissionAlpha in this new setup that will act similar to the first declaration above. Would the only way to do this be to resort to pulling the value of the class name like in the example below? I'm trying to keep all the names in one place that can be reference anywhere in the application. public static class PermissionAlpha { public static string Name { get { return typeof(PermissionAlpha).Name; } } }

    Read the article

  • open current page in new window including query string

    - by Hatch
    First of all, I am a total dud at all things related to web developement, so please bear with me here. I suspect this question is laughable for the web guys, but unfortunately I can't figure this out. Here goes: I have an application, that does some processing, writes some result files and then displays the results in an embedded IE browser control. This is done by navigating the browser control to a local html file together with a query string containing the generated result files to display it all. The link target would look something like: c:\SomeFolder\results.htm?results=file%201.xml;file%202.xml;file%203.xml So far, everything's fine. However, in the html page is a href that is suppossed to open up the exact same just in a normal browser window. What I thought would work is: <a href="#" target="_blank">Show in browser</a> Since it is a link in an html page displayed in an IE control, the link will open up in IE no matter what the default browser might be. This works for IE7 and 8, but not for IE6. With IE6 the query string gets cut off and the browser opens file://c:/results/results.htm# without the query string. I am sure there must be a much better way to do this without the # and which would work in all IEs. How would the pros solve this?

    Read the article

  • Using stringstream instead of `sscanf` to parse a fixed-format string

    - by John Dibling
    I would like to use the facilities provided by stringstream to extract values from a fixed-format string as a type-safe alternative to sscanf. How can I do this? Consider the following specific use case. I have a std::string in the following fixed format: YYYYMMDDHHMMSSmmm Where: YYYY = 4 digits representing the year MM = 2 digits representing the month ('0' padded to 2 characters) DD = 2 digits representing the day ('0' padded to 2 characters) HH = 2 digits representing the hour ('0' padded to 2 characters) MM = 2 digits representing the minute ('0' padded to 2 characters) SS = 2 digits representing the second ('0' padded to 2 characters) mmm = 3 digits representing the milliseconds ('0' padded to 3 characters) Previously I was doing something along these lines: string s = "20101220110651184"; unsigned year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0, milli = 0; sscanf(s.c_str(), "%4u%2u%2u%2u%2u%2u%3u", &year, &month, &day, &hour, &minute, &second, &milli ); The width values are magic numbers, and that's ok. I'd like to use streams to extract these values and convert them to unsigneds in the interest of type safety. But when I try this: stringstream ss; ss << "20101220110651184"; ss >> setw(4) >> year; year retains the value 0. It should be 2010. How do I do what I'm trying to do? I can't use Boost or any other 3rd party library, nor can I use C++0x.

    Read the article

  • Encrypt string with public key only

    - by vlahovic
    i'm currently working on a android project where i need to encrypt a string using 128 bit AES, padding PKCS7 and CBC. I don't want to use any salt for this. I've tried loads of different variations including PBEKey but i can't come up with working code. This is what i currently have: String plainText = "24124124123"; String pwd = "BobsPublicPassword"; byte[] key = pwd.getBytes(); key = cutArray(key, 16); byte[] input = plainText.getBytes(); byte[] output = null; SecretKeySpec keySpec = null; keySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); output = cipher.doFinal(input); private static byte[] cutArray(byte[] arr, int length){ byte[] resultArr = new byte[length]; for(int i = 0; i < length; i++ ){ resultArr[i] = arr[i]; } return resultArr; } Any help appreciated //Vlahovic

    Read the article

  • Extraction from string - Ruby

    - by Dantes
    I have a string. That string is a html code and it serves as a teaser for the blog posts I am creating. The whole html code (teaser) is stored in a field in the database. My goal: I'd like to make that when a user (facebook like social button) likes certain blog post, right data is displayed on his news feeds. In order to do that I need to extract from the teaser in the first occurrence of an image an image path inside src="i-m-a-g-e--p-a-t-h". I succeeded when a user puts only one image in teaser, but if he accidentally puts two images or more the whole thing craches. Furthermore, for description field I need to extract text inside the first occurrence inside <p> tag. The problem is also that a user can put an image inside the first tag. I would very much appreciate if an expert could help me resolve this what's been bugging me for days. Text string with a regular expression for extracting src can be found here: http://rubular.com/r/gajzivoBSf Thanks!

    Read the article

  • Adding a ActionPerformed Array to a String Array

    - by user267490
    Hey, Before you guys ask, yes I've searched online for the answer, but everything I found just leaves a lil confuse and nothing is recent so asking in those forums won't really help. My problems is this: I have an array that holds my name for a menu. String[] fontColor = new String[] {"Red", "Blue", "Green"}; for (int i = 0; i < fontColors.length; i++) { JMenuItem fontC = new JMenuItem(fontColors[i]); fontC.addActionListener(new fontColorAction()); changeFontColor.add(fontC); } Then I have an array that holds my color change in a class called fontColorAction in that class I have another array that does the same thing as my string array except all thats in the statement is textarea.setForeground(colorArr[i]); that will set the setForeground() in order, but now how do I successfully attact the action listner in my class to my menuItems? my class looks like this private class fontColorAction implements ActionListener { Color[] colorArr - new Color[] {"Color.RED","Color.BLUE","Color.GREEN"}; public void actionPerformed(ActionEvent e){ for(i = 0; i < collorArr.length; i++){ textarea.setForeground(colorArr[i]); } } }

    Read the article

  • Filtering string in Python

    - by Ecce_Homo
    I am making algorithm for checking the string (e-mail) - like "E-mail addres is valid" but their are rules. First part of e-mail has to be string that has 1-8 characters (can contain alphabet, numbers, underscore [ _ ]...all the parts that e-mail contains) and after @ the second part of e-mail has to have string that has 1-12 characters (also containing all legal expressions) and it has to end with top level domain .com EDIT email = raw_input ("Enter the e-mail address:") length = len (email) if length > 20 print "Address is too long" elif lenght < 5: print "Address is too short" if not email.endswith (".com"): print "Address doesn't contain correct domain ending" first_part = len (splitting[0]) second_part = len(splitting[1]) account = splitting[0] domain = splitting[1] for c in account: if c not in "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.": print "Invalid char", "->", c,"<-", "in account name of e-mail" for c in domain: if c not in "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_.": print "Invalid char", "->", c,"<-", "in domain of e-mail" if first_part == 0: print "You need at least 1 character before the @" elif first_part> 8: print "The first part is too long" if second_part == 4: print "You need at least 1 character after the @" elif second_part> 16: print "The second part is too long" else: # if everything is fine return this print "E-mail addres is valid" EDIT: After reproting what is wrong with our input, now I need to make Python recognize valid address and return ("E-mail adress is valid") This is the best i can do with my knowledge....and we cant use regular expressions, teacher said we are going to learn them later.

    Read the article

  • Windows Phone - failing to get a string from a website with login information

    - by jumantyn
    I am new to accessing web services with Windows Phone 7/8. I'm using a WebClient to get a string from a php-website. The site returns a JSON string but at the moment I'm just trying to put it into a TextBox as a normal string just to test if the connection works. The php-page requires an authentication and I think that's where my code is failing. Here's my code: WebClient client = new WebClient(); client.Credentials = new NetworkCredential("myUsername", "myPassword"); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); client.DownloadStringAsync(new Uri("https://www.mywebsite.com/ba/php/jsonstuff.php")); void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { try { string data = e.Result; this.jsonText.Text = data; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } This returns first a WebException and then a TargetInvocationException. If I replace the Uri with for example "http://www.google.com/index.html" the jsonText TextBox gets filled with html text from Google (oddly enough, this also works even when the WebClient credentials are still set). So is the problem in the setting of the credentials? I couldn't find any good results when searching for guides on how to access php-pages with credentials, only without them. Then I found a short mention somewhere to use the WebClient.Credentials property. But should it work some other way? Update: here's what I can get out of the WebException (sorry for the bad formatting): System.Net.WebException: The remote server returned an error: NotFound. ---System.Net.WebException: The remote server returned an error: NotFound. at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<c_DisplayClasse.b_d(Object sendState) at System.Net.Browser.AsyncHelper.<c_DisplayClass1.b_0(Object sendState) --- End of inner exception stack trace --- at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)

    Read the article

  • How to parse XML string value using jQuery ?

    - by Vijay
    Hi All, I am new to jquery. I am trying to parse xml string using jquery. I have found one sample code; $(function() { $.get('data.xml', function(d) { var data = ""; var startTag = "<table border='1' id='mainTable'><tbody><tr><td style=\"width: 120px\">Name</td><td style=\"width: 120px\">Link</td></tr>"; var endTag = "</tbody></table>"; $(d).find('url').each(function() { var $url = $(this); var link = $url.find('link').text(); var name = $url.find('name').text(); data += '<tr><td>' + name + '</td>'; data += '<td>' + link + '</td></tr>'; }) $("#content").html(startTag + data + endTag); ; }); }); In this case, I am able to parse and fetch the values from xml file. but now what I am looking for is instead of reading file from desk, I want to read the xml from string. Say, instead of data.xml I want to parse string which consists of well formed xml. does anyone have any idea about this ? Thanks in advance

    Read the article

< Previous Page | 153 154 155 156 157 158 159 160 161 162 163 164  | Next Page >