Search Results

Search found 35302 results on 1413 pages for 'string literals'.

Page 119/1413 | < Previous Page | 115 116 117 118 119 120 121 122 123 124 125 126  | Next Page >

  • 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

  • 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

  • Java string to double conversion.

    - by wretrOvian
    Hi, I've been reading up on the net about the issues with handling float and double types in java. Unfortunately, the image is still not clear. Hence, i'm asking here direct. :( My MySQL table has various DECIMAL(m,d) columns. The m may range from 5 to 30. d stays a constant at 2. Question 1. What equivalent data-type should i be using in Java to work (i.e store, retrieve, and process) with the size of the values in my table? (I've settled with double - hence this post). Question 2. While trying to parse a double from a string, i'm getting errors Double dpu = new Double(dpuField.getText()); for example - "1" -> java.lang.NumberFormatException: empty String "10" -> 1.0 "101" -> 10.0 "101." -> 101.0 "101.1" -> 101.0 "101.19" -> 101.1 What am i doing wrong? What is the correct way to convert a string to a double value? And what measures should i take to perform operations on such values?

    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

  • Converting string to a simple type

    - by zespri
    .Net framework contains a great class named Convert that allows conversion between simple types, DateTime type and String type. Also the class support conversion of the types implementing IConvertible interface. The class has been implemented in the very first version of .Net framework. There were a few things in the first .Net framework that were not done quite right. For example .Parse methods on simple types would throw an exception if the string couldn't be parsed and there would be no way to check if exception is going to be thrown in advance. A future version of .Net Framework removed this deficiency by introducing the TryParse method that resolved this problem. The Convert class dates back to time of the old Parse method, so the ChangeType method on this class in implemented old style - if conversion can't be performed an exception is thrown. Take a look at the following code: public static T ConvertString<T>(string s, T @default) { try { return (T)Convert.ChangeType(s, typeof(T), CultureInfo.InvariantCulture); } catch (Exception) { return @default; } } This code basically does what I want. However I would pretty much like to avoid the ugly try/catch here. I'm sure, that similar to TryParse, there is a modern method of rewriting this code without the catch-all. Could you suggest one?

    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

  • 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

  • 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

  • Connection string problems on shared hosting with sql server 2005 express

    - by dagogo
    hi i have problem connecting to my db on a shared hosting, my host provider says they deployed sql 2005 express on their database and i prepared my connection string as follows to take advantage of sql express. \ the data source nae i used originally was ./SQLExpress but my host provider asked that i change it to local host, although with the former it didnt connect, but still with the change as indicated above the error still comes up on access to my default page. the error is as follows; Server Error in '/' Application. Invalid value for key 'attachdbfilename'. 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: Invalid value for key 'attachdbfilename'. Source Error: Line 120: Public Function GetID(ByVal sLgaName As String) As Integer Line 121: Dim q As String = "Select PLID " & "From LGA " & "Where LGAName = " & "'" & sLgaName & "'" Line 122: Dim cn As New SqlConnection(Me.ConnectionString) Line 123: Dim cmd As New SqlCommand(q, cn) Line 124: ive read up a lot on the web and googled ma fingers numb on this, i have a deadline to deliver this project and having successfully built the app it frustrating for this to happen. pls help me.

    Read the article

  • Indy client receive string

    - by Eszee
    Im writing an Indy chat app, and am wondering if there is a way for the server component to tell the client that there is a string waiting, or even a way for the client to have an "OnExecute" like event. This is what i have now: server: procedure TServer.ServerExecute(AContext: TIdContext); var sResponse: string; I: Integer; list: Tlist; begin List := Server.Contexts.LockList; sResponse:= AContext.Connection.Socket.ReadLn; try for I := 0 to List.Count-1 do begin try TIdContext(List[I]).Connection.IOHandler.WriteLn(sResponse); except end; end; finally Server.Contexts.UnlockList; end; end; Client: procedure TForm1.Button1Click(Sender: TObject); var sMsg : string; begin Client.Socket.WriteLn(edit1.Text); sMsg := Client.Socket.ReadLn; Memo1.Lines.Add(sMsg); end; The problem is when i have 2 or more clients running the messages keep stacking because the button only processes 1 message a time. I'd like a way for the client to wait for messages and when it is triggered it processes those messages, like it does now under the button procedure. I've tried to put the "readln" part under a timer, but that causes some major problems. Im Using Delphi 2010 and Indy 10

    Read the article

  • android populating gridivew from a url string

    - by user1685991
    I am building an android application in which i am trying to read data from a url and want to display the data in a gridview. But i have some problem or dont understand to how to display the array list on grdiview. Here is my code for reading data from php url ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //http post try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://sml.com.pk/a/smldb.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection"+e.toString()); } //convert response to string try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line="0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); }catch(Exception e){ Log.e("log_tag", "Error converting result "+e.toString()); } //paring data double des; double value; try{ jArray = new JSONArray(result); JSONObject json_data=null; for(int i=0;i<jArray.length();i++){ json_data = jArray.getJSONObject(i); LAT=json_data.getDouble("TITLE"); LANG=json_data.getDouble("A"); } } catch(JSONException e1){ Toast.makeText(getBaseContext(), "No Vehicles Found" ,Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } Here TITLE and A are my two columns of DB Table and i want to display them on gridview please any one help me to do this according to my current code. Here is my live url for data string http://sml.com.pk/a/smldb.php

    Read the article

  • HiddenField.Value is an empty string upon postback inside my custom control

    - by Matthew Cox
    I have a custom control that has a hidden field. Upon postback I want to obtain the value stored in it, but it's always an empty string. any thoughts? I am performing client-side manipulation of the hidden field values and have verified in firebug that the fields are correct before issue a post back Here is the setup: public class DualListPanel : SWebControl, INamingContainer { protected IList<DlpItem> UnassignedList { get; set; } protected IList<DlpItem> AssignedList { get; set; } private HiddenField assignedItemsField, unassignedItemsField; public DualListPanel() { CssClass = "DualListPanel"; EnableViewState = true; } #region ViewState protected override void LoadViewState(object savedState) { var state = savedState as object[]; UnassignedList = state[0] as List<DlpItem>; AssignedList = state[1] as List<DlpItem>; base.LoadViewState(state[2]); } protected override object SaveViewState() { object[] state = new object[3]; state[0] = UnassignedList; state[1] = AssignedList; state[2] = base.SaveViewState(); return state; } #endregion #region WebControl Overrides protected override void CreateChildControls() { assignedItemsField = new HiddenField(); assignedItemsField.ID = "HiddenAssignedItems"; assignedItemsField.EnableViewState = true; unassignedItemsField = new HiddenField(); unassignedItemsField.ID = "HiddenUnassignedItems"; unassignedItemsField.EnableViewState = true; Controls.Add(assignedItemsField); Controls.Add(unassignedItemsField); base.CreateChildControls(); } #endregion #region Item Lists Retrieval public string GetCommaDelimUnassignedItems() { return unassignedItemsField.Value; } public string GetCommaDelimAssignedItems() { return assignedItemsField.Value; } #endregion }

    Read the article

  • Matching a String and then incrementing a number within HTML elements

    - by Abs
    Hello all, I have tags in a html list, here is an example of two tags. <div class="tags"> <ul> <li> <a onclick="tag_search('tag1');" href="#">tag1 <span class="num-active">1</span></a> </li> <li> <a onclick="tag_search('tag2');" href="#">tag2 <span class="num-active">1</span></a> </li> </ul> </div> I would like to write a function that I can pass a string to, that will match the strings in the a hyperlink i.e. "tag1" or "tag2", if there is a match then increment the number in the span, if not then add a new li. The bit I am having trouble with is how do I search for a string in the div with class tags and then when I find a match identifying the element. I can't even do the first bit as I am use to using an ID or a Class. I appreciate any help on this using JQuery Thanks all Code so far function change_tag_count(item){ alert(item);//alerts the string test $.fn.searchString = function(str) { return this.filter('*:contains("' + item + '")'); }; if($('body').searchString(item).length){ var n = $('a').searchString(item).children().text(); n = parseInt(n) + 1; $('a').searchString(item).children().text(n); }else{ alert('here');//does not alert this when no li contains the word test $("#all_tags ul").append('<a onclick="tag_search(\''+item+'\');" href="#">'+item+'<span class="num-active">1</span></a>'); } }

    Read the article

  • PHP: cannot matching string "<br />

    - by Patrick
    hi, I'm having problems with string matching in PHP. I've 2 html elements in my page, I've copy pasted here the content with Firebug <div class="field-item odd"> <div class="field-label-inline-first"> Year:</div> 2009 </div> <div class="field-item odd"> <div class="field-label-inline-first"> Synopsis:</div> &lt;br /&gt; </div> This php line works perfectly (the element with 2009 is detected) <?php if ($items[0]['view'] == '2009') : echo "ok"; ?> However I'm not able to match the string containing element: <?php if ($items[0]['view'] == '<br />') : echo "ok"; ?> //doesn't work <?php if ($items[0]['view'] == '&lt;br /&gt;') : echo "ok"; ?> //again doesn't work any tip ? To give you some context: The strings are produced by CKEditor, an editor I'm using in my Drupal back-end. When I leave empty this editor, the tag is displayed on the string as plain text (because I set "plain text" as formatting option in the back-end) Thanks

    Read the article

  • How can I provide property-level string formatting?

    - by jhubsharp
    Not sure if the question wording is accurate, but here's what I want to do: I want to databind a class with some strings in it: class MyClass { public string MyProperty { get; set; } public string MyProperty2 { get; set; } } When databinding, everything behaves normally. On the back end, I'm writing to a file and I want MyProperty2 to always be encrypted using some encryption algorithm. I want my back-end code to write each string without needing to know that encryption is required (I want the class to know it should be encrypted, not the consumer). Can I do this with a type converter, or something similar? EDIT: There are other scenarios as well. Some booleans I want to format as "Y" or "N", other booleans I want formatted as "Enabled" / "Disabled", etc. I can write (and have written) helper methods and let the file writer call the helper methods as appropriate, I'm just wondering if there's a way to do this without the file writer needing to know which objects need which kind of formatting and let the objects tell that to the file writer.

    Read the article

  • Program that edits string and prints each word individually with C

    - by Michael_19
    I keep getting the error segmentation fault (core dumped) when I run my progam. #include<stdio.h> #include<stdlib.h> int nextword(char *str); int main(void) { char str[] = "Hello! Today is a beautiful day!!\t\n"; int i = nextword(str); while(i != -1) { printf("%s\n",&(str[i])); i = nextword(NULL); } return 0; } int nextword(char *str) { // create two static variables - these stay around across calls static char *s; static int nextindex; int thisindex; // reset the static variables if (str != NULL) { s = str; thisindex = 0; // TODO: advance this index past any leading spaces while (s[thisindex]=='\n' || s[thisindex]=='\t' || s[thisindex]==' ' ) thisindex++; } else { // set the return value to be the nextindex thisindex = nextindex; } // if we aren't done with the string... if (thisindex != -1) { nextindex = thisindex; // TODO: two things // 1: place a '\0' after the current word // 2: advance nextindex to the beginning // of the next word while (s[nextindex] != ' ' && s[nextindex] != '\0') nextindex++; str[nextindex] = '\0'; nextindex++; } return thisindex; } The goal of the program is to print each word in the string str[] to the console on a new line. I am a beginning programmer and this is an assignment so I must use this type of format (no string library allowed). I just would like to know where I went wrong and how I can fix it.

    Read the article

  • How to convert strings into integers in python?

    - by elfuego1
    Hello there, I have a tuple of tuples from MySQL query like this: T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16')) I'd like to convert all the string elements into integers and put it back nicely to list of lists this time: T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]] I tried to achieve it with "eval" but didn't get any decent result yet.

    Read the article

  • Java Anagram Solver

    - by Alex
    I can work out how to create anagrams of a string but I don't know how I can compare them to a dictionary of real words to check if the anagram is a real word. Is there a class in the Java API that contains the entire English dictionary?

    Read the article

  • Very simple regex not working

    - by Thomas Wanner
    I have read that to match a word inside of a string using Regular expressions (in .NET), I can use the word boundary specifier (\b) within the regex. However, none of these calls result in any matches Regex.Match("INSERT INTO TEST(Col1,Col2) VALUES(@p1,@p2)", "\b@p1\b"); Regex.Match("INSERT INTO TEST(Col1,Col2) VALUES(@p1,@p2)", "\bINSERT\b"); Is there anything I am doing wrong ?

    Read the article

  • Regex one-to-one mapping pattern replace

    - by polygenelubricants
    How would you use regex to write a function that replaces all lowercase letters with uppercase and vice versa? Note: this is NOT a homework question. See also my previous explorations of regex: Regex split into overlapping strings (Alan Moore's answer is especially instructive) Can you use zero-width matching regex in String split? (my solution exploits a known Java regex bug with regards to non-obvious length lookbehind!)

    Read the article

  • Ruby concatenate strings and add spaces

    - by David Oneill
    I have 4 string variables name, quest, favorite_color, speed that might be empty. I want to concatenate them all together, putting spaces between those that aren't empty. So: name = 'Tim' quest = 'destroy' favorite_color = 'red' speed = 'fast' becomes 'Tim destroy red fast' and name = 'Steve' quest = '' favorite_color = '' speed = 'slow' becomes: 'Steve slow' (Notice: there is only 1 space between 'Steve' and 'slow') How do I do that (preferably in 1 line).

    Read the article

< Previous Page | 115 116 117 118 119 120 121 122 123 124 125 126  | Next Page >