Search Results

Search found 2136 results on 86 pages for 'dominik str'.

Page 11/86 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • threading.Event wait function not signaled when subclassing Process class

    - by user1313404
    For following code never gets past the wait function in run. I'm certain I'm doing something ridiculously stupid, but since I'm not smart enough to figure out what, I'm asking. Any help is appreciated. Here is the code: import threading import multiprocessing from multiprocessing import Process class SomeClass(Process): def __init__(self): Process.__init__(self) self.event = threading.Event() self.event.clear() def continueExec(self): print multiprocessing.current_process().name print self print "Set:" + str(self.event.is_set()) self.event.set() print "Set:" + str(self.event.is_set()) def run(self): print "I'm running with it" print multiprocessing.current_process().name self.event.wait() print "I'm further than I was" print multiprocessing.current_process().name self.event.clear() def main(): s_list = [] for t in range(3): s = SomeClass() print "s:" + str(s) s_list.append(s) s.start() raw_input("Press enter to send signal") for t in range(3): print "s_list["+str(t)+"]:" + str(s_list[t]) s_list[t].continueExec() raw_input("Press enter to send signal") for t in range(3): s_list[t].join() print "All Done" if __name__ == "__main__": main()

    Read the article

  • String vectors not working as expected with newline and iterators? (C++)

    - by kevin
    I have a text file made of 3 lines: Line 1 Line 3 (Line 1, a blank line, and Line 3) vector<string> text; vector<string>::iterator it; ifstream file("test.txt"); string str; while (getline(file, str)) { if (str.length() == 0) str = "\n"; // since getline discards the newline character, replacing blank strings with newline text.push_back(str); } // while for (it=text.begin(); it < text.end(); it++) cout << (*it); Prints out: Line 1 Line 3 I'm not sure why the string with only a newline was not printed out. Any help would be appreciated. Thanks.

    Read the article

  • AppEngine GeoPt Data Upload

    - by Eric Landry
    I'm writing a GAE app in Java and only using Python for the data upload. I'm trying to import a CSV file that looks like this: POSTAL_CODE_ID,PostalCode,City,Province,ProvinceCode,CityType,Latitude,Longitude 1,A0E2Z0,Monkstown,Newfoundland,NL,D,47.150300000000001,-55.299500000000002 I was able to import this file in my datastore if I import Latitude and Longitude as floats, but I'm having trouble figuring out how to import lat and lng as a GeoPt. Here is my loader.py file: import datetime from google.appengine.ext import db from google.appengine.tools import bulkloader class PostalCode(db.Model): id = db.IntegerProperty() postal_code = db.PostalAddressProperty() city = db.StringProperty() province = db.StringProperty() province_code = db.StringProperty() city_type = db.StringProperty() lat = db.FloatProperty() lng = db.FloatProperty() class PostalCodeLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'PostalCode', [('id', int), ('postal_code', str), ('city', str), ('province', str), ('province_code', str), ('city_type', str), ('lat', float), ('lng', float) ]) loaders = [PostalCodeLoader] I think that the two db.FloatProperty() lines should be replaced with a db.GeoPtProperty(), but that's where my trail ends. I'm very new to Python so any help would be greatly appreciated.

    Read the article

  • php foreach looping twice

    - by Jack
    Hi, I am trying to loop through some data from my database but it is outputting it twice. $fields = 'field1, field2, field3, field4'; $idFields = 'id_field1, id_field2, id_field3, id_field4'; $tables = 'table1, table2, table3, table4'; $table = explode(', ', $tables); $field = explode(', ', $fields); $id = explode(', ', $idFields); $str = 'Egg'; $i=1; while ($i<4) { $f = $field[$i]; $idd = $id[$i]; $sql = $writeConn->select()->from($table[$i], array($f, $idd))->where($f . " LIKE ?", '%' . $str . '%'); $string = '<a title="' . $str . '" href="' . $currentProductUrl . '">' . $str . '</a>'; $result = $writeConn->fetchAssoc($sql); foreach ($result as $row) { echo 'Success! Found ' . $str . ' in ' . $f . '. ID: ' . $row[$idd] . '.<br>'; } $i++; } Outputting: Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: 5. Could someone please explain why it is looping through both the indexed and associative values? UPDATE I did some more playing around and tried the following. $fields = 'field1, field2, field3, field4'; $idFields = 'id_field1, id_field2, id_field3, id_field4'; $tables = 'table1, table2, table3, table4'; $table = explode(', ', $tables); $field = explode(', ', $fields); $id = explode(', ', $idFields); $str = 'Egg'; $i=1; while ($i<4) { $f = $field[$i]; $idd = $id[$i]; $sql = $writeConn->select()->from($table[$i], array($f, $idd))->where($f . " LIKE ?", '%' . $str . '%'); $string = '<a title="' . $str . '" href="' . $currentProductUrl . '">' . $str . '</a>'; $sth = $writeConn->prepare($sql); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); foreach ($result as $row) { echo 'Success! Found ' . $str . ' in ' . $f . '. ID: ' . $row[$idd] . '.<br>'; } $i++; } The interesting thing is that this outputs the below: Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: 5. I have also tried adding $i to the output and this outputs 2 as expected. If I change fetch(PDO::FETCH_BOTH) to fetch(PDO::FETCH_ASSOC) the output is as follows: Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: E. Success! Found Egg in field3. ID: 5. Success! Found Egg in field3. ID: 5. This has been bugging me for too long, so if anyone could help I would be very appreciative!

    Read the article

  • Problem generating GET url

    - by Bruce
    I am working on Java. I am calling a GET url on my own machine using Java. Here is the url string with the arguments. listen.executeUrl("http://localhost/post_message.php?query_string="+str); I am taking str as user input. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter query: "); str = br.readLine(); How do I encode str into GET argument. For eg. str -> test query url -> http://localhost/post_message.php?query_string=test%20query

    Read the article

  • Convert hex to decimal keeping fractional part in Lua

    - by Zack Mulgrew
    Lua's tonumber function is nice but can only convert unsigned integers unless they are base 10. I have a situation where I have numbers like 01.4C that I would like to convert to decimal. I have a crummy solution: function split(str, pat) local t = {} local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) table.insert(t, cap) end return t end -- taken from http://lua-users.org/wiki/SplitJoin function hex2dec(hexnum) local parts = split(hexnum, "[\.]") local sigpart = parts[1] local decpart = parts[2] sigpart = tonumber(sigpart, 16) decpart = tonumber(decpart, 16) / 256 return sigpart + decpart end print(hex2dec("01.4C")) -- output: 1.296875 I'd be interested in a better solution for this if there is one.

    Read the article

  • In Python, how do I search a flat file for the closest match to a particular numeric value?

    - by kaushik
    have file data of format 3.343445 1 3.54564 1 4.345535 1 2.453454 1 and so on upto 1000 lines and i have number given such as a=2.44443 for the given file i need to find the row number of the numbers in file which is most close to the given number "a" how can i do this i am presently doing by loading whole file into list and comparing each element and finding the closest one any other better faster method? my code:i need to ru this for different file each time around 20000 times so want a fast method p=os.path.join("c:/begpython/wavnk/",str(str(str(save_a[1]).replace('phone','text'))+'.pm')) x=open(p , 'r') for i in range(6): x.readline() j=0 o=[] for line in x: oj=str(str(line).rstrip('\n')).split(' ') o=o+[oj] j=j+1 temp=long(1232332) end_time=save_a[4] for i in range((j-1)): diff=float(o[i][0])-float(end_time) if diff<0: diff=diff*(-1) if temp>diff: temp=diff pm_row=i

    Read the article

  • C# performance of static string[] contains() (slooooow) vs. == operator

    - by Andrew White
    Hiya, Just a quick query: I had a piece of code which compared a string against a long list of values, e.g. if(str == "string1" || str = "string2" || str == "string3" || str = "string4". DoSomething(); And the interest of code clarity and maintainability I changed it to public static string[] strValues = { "String1", "String2", "String3", "String4"}; ... if(strValues.Contains(str) DoSomething(); Only to find the code execution time went from 2.5secs to 6.8secs (executed ca. 200,000 times). I certainly understand a slight performance trade off, but 300%? Anyway I could define the static strings differently to enhance performance? Cheers.

    Read the article

  • Replace carriage returns and line feeds in out.println?

    - by Mike
    I am a novice coder and I am using the following code to outprint a set of Image keywords and input a "|" between them. <% Set allKeywords = new HashSet(); for (AlbumObject ao : currentObjects) { XmpManager mgr = ao.getXmpManager(); if (mgr != null) { allKeywords.addAll(mgr.getKeywordSet()); } } //get the Iterator Iterator itr = allKeywords.iterator(); while(itr.hasNext()){ String str = itr.next(); out.println(str +"|"); } %> I want the output to be like this: red|blue|green|yellow but it prints out: red| blue| green| yellow which breaks my code. I've tried this: str.replaceAll("\n", ""); str.replaceAll("\r", ""); and str.replaceAll("(?:\\n|\\r)", ""); No luck. I'd really appreciate some help!

    Read the article

  • Python Continue Loop

    - by Rob B.
    I am using the following code from this tutorial (http://jeriwieringa.com/blog/2012/11/04/beautiful-soup-tutorial-part-1/). from bs4 import BeautifulSoup soup = BeautifulSoup (open("43rd-congress.html")) final_link = soup.p.a final_link.decompose() trs = soup.find_all('tr') for tr in trs: for link in tr.find_all('a'): fulllink = link.get ('href') print fulllink #print in terminal to verify results tds = tr.find_all("td") try: #we are using "try" because the table is not well formatted. This allows the program to continue after encountering an error. names = str(tds[0].get_text()) # This structure isolate the item by its column in the table and converts it into a string. years = str(tds[1].get_text()) positions = str(tds[2].get_text()) parties = str(tds[3].get_text()) states = str(tds[4].get_text()) congress = tds[5].get_text() except: print "bad tr string" continue #This tells the computer to move on to the next item after it encounters an error print names, years, positions, parties, states, congress However, I get an error saying that 'continue' is not properly in the loop on line 27. I am using notepad++ and windows powershell. How do I make this code work?

    Read the article

  • How to add values accordingly of the first indices of a dictionary of tuples of a list of strings? Python 3x

    - by TheStruggler
    I'm stuck on how to formulate this problem properly and the following is: What if we had the following values: {('A','B','C','D'):3, ('A','C','B','D'):2, ('B','D','C','A'):4, ('D','C','B','A'):3, ('C','B','A','D'):1, ('C','D','A','B'):1} When we sum up the first place values: [5,4,2,3] (5 people picked for A first, 4 people picked for B first, and so on like A = 5, B = 4, C = 2, D = 3) The maximum values for any alphabet is 5, which isn't a majority (5/14 is less than half), where 14 is the sum of total values. So we remove the alphabet with the fewest first place picks. Which in this case is C. I want to return a dictionary where {'A':5, 'B':4, 'C':2, 'D':3} without importing anything. This is my work: def popular(letter): '''(dict of {tuple of (str, str, str, str): int}) -> dict of {str:int} ''' my_dictionary = {} counter = 0 for (alphabet, picks) in letter.items(): if (alphabet[0]): my_dictionary[alphabet[0]] = picks else: my_dictionary[alphabet[0]] = counter return my_dictionary This returns duplicate of keys which I cannot get rid of. Thanks.

    Read the article

  • Add linux user with restricted access

    - by Dominik Str
    I need to create a user on linux with access rights only to one folder. Background: I have installed git on my virtual server (Debian). I also created a user for the repository. There is a lot of private data on the server. But all folders have read-access for others, because it's needed for the applications which run on the server. So the git-user can see all the data. I would like to restrict the git user only to the folder where the repository is installed. I also tried ACL, but it didn't work. Is there a better way to do this? Thanks in advance!

    Read the article

  • How to use Parcel in Android?

    - by Mike
    I'm trying to use Parcel to write and then read back a Parcelable. For some reason, when I read the object back from the file, it's coming back as null. public void testFoo() { final Foo orig = new Foo("blah blah"); // Wrote orig to a parcel and then byte array final Parcel p1 = Parcel.obtain(); p1.writeValue(orig); final byte[] bytes = p1.marshall(); // Check to make sure that the byte array seems to contain a Parcelable assertEquals(4, bytes[0]); // Parcel.VAL_PARCELABLE // Unmarshall a Foo from that byte array final Parcel p2 = Parcel.obtain(); p2.unmarshall(bytes, 0, bytes.length); final Foo result = (Foo) p2.readValue(Foo.class.getClassLoader()); assertNotNull(result); // FAIL assertEquals( orig.str, result.str ); } protected static class Foo implements Parcelable { protected static final Parcelable.Creator<Foo> CREATOR = new Parcelable.Creator<Foo>() { public Foo createFromParcel(Parcel source) { final Foo f = new Foo(); f.str = (String) source.readValue(Foo.class.getClassLoader()); return f; } public Foo[] newArray(int size) { throw new UnsupportedOperationException(); } }; public String str; public Foo() { } public Foo( String s ) { str = s; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int ignored) { dest.writeValue(str); } } What am I missing? UPDATE: To simplify the test I've removed the reading and writing of files in my original example.

    Read the article

  • Reading text out of textbox in Radgrid

    - by Christophe
    I have a Radgrid with 2 Textboxes and 2 DatePickers. The idea is that I have a grid with a Property name, value, valid from and until. I'm filling the first Textbox myself, the user has to fill in the value, from and until. Filling in the propertynames: (In the pageload) foreach (String s in testProperties) { DataRow dr = dt.NewRow(); dr[0] = s; dr[1] = ""; dr[2] = ""; dr[3] = ""; dt.Rows.Add(dr); } When the user hit "Save" I have to read out all the data he filled in. (In the btnSave click) foreach (GridDataItem dataItem in RadGrid1.Items) { String[] str = new String[3]; str[0] = ((TextBox)dataItem["col2"].FindControl("TextBox2")).Text; str[1] = ((RadDatePicker)dataItem["col3"].FindControl("RadDatePicker1")).SelectedDate.ToString(); str[2] = ((RadDatePicker)dataItem["col4"].FindControl("RadDatePicker2")).SelectedDate.ToString(); properties.Add(((TextBox)dataItem["col1"].FindControl("TextBox1")).Text, str); } Now this is where I have the problem. When i read out the data all my 'str' have the value "" instead the data that the user fills in. Question is, how comes my values in the texboxes remain ""? Or is their a better way to read out the data?

    Read the article

  • sscanf wrapping function to advance string pointer in C

    - by Dusty
    I have a function that makes a series of calls to sscanf() and then, after each, updates the string pointer to point to the first character not consumed by sscanf() like so: if(sscanf(str, "%d%n", &fooInt, &length) != 1) { // error handling } str+=length; In order to clean it up and avoid duplicating this several times over, i'd like to encapsulate this into a nice utility function that looks something like the following: int newSscanf ( char ** str, const char * format, ...) { int rv; int length; char buf[MAX_LENGTH]; va_list args; strcpy(buf, format); strcat(buf, "%n"); va_start(args, format); rv = vsscanf(*str, buf, args, &length); va_end(args); *str += length; return rv; } Then I could simply the calls as below to remove the additional parameter/bookkeeping: if(newSscanf(&str, "%d", &fooInt) != 1) { // error handling } Unfortunately, I can't find a way to append the &length parameter onto the end of the arg list directly or otherwise inside newSscanf(). Is there some way to work around this, or am I just as well off handling the bookkeeping by hand at each call?

    Read the article

  • fill combobox value in datagridview based on other combobox in datagridview

    - by Purohit Raghu
    I m creating Web Application..in C# I have One Data grid view In that i Have 2 Combo box i m trying 2 bind second combo box based on first combo-box. in First Combo-box I have value Shirt,T shirt so i want if shirt is selected than second combo-box should have value Slim,Regular..and if T shirt Is selected than second Combo-box should have V neck and rounded color. i have different table for thirst and shirt type... I work fine for first time but when i goes on second row and change the combo box value than it will also change value of second combo box value of previous row as well .. Where i need to change to prevent change in upper row i have following code private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { if (dataGridView1.CurrentCell.ColumnIndex == 0) { ComboBox cbx = e.Control as ComboBox; cbx.SelectionChangeCommitted -= new EventHandler(cbx_SelectionChangeCommitted); cbx.SelectionChangeCommitted += new EventHandler(cbx_SelectionChangeCommitted); } } private void cbx_SelectionChangeCommitted(object sender, EventArgs e) { int selectedIndex = ((ComboBox)sender).SelectedIndex; if (selectedIndex == 1) //this condition is true if i have selected shirt from combobox1 { ShirtType(); } if (selectedIndex == 2) { Tshirtype(); } } void ShirtType() { try { string str; str = "select ShirtType_name,ShirtType_Id from ShirtType_master"; ds = new DataSet(); ds = cn.readdata(str); Type.DataSource = ds.Tables[0];//Type is Combobox name of Second Combobox Type.DisplayMember = ds.Tables[0].Columns[0].ToString(); ; Type.ValueMember = ds.Tables[0].Columns[1].ToString(); ; } catch (Exception ee) { } } void Tshirtype() { try { string str; str = "select TShirtType_name,TshirtType_Id from TshirtType_Master"; ds = new DataSet(); ds = cn.readdata(str); Type.DataSource = ds.Tables[0]; Type.DisplayMember = ds.Tables[0].Columns[0].ToString(); ; Type.ValueMember = ds.Tables[0].Columns[1].ToString(); ; }

    Read the article

  • python lists error

    - by mekasperasky
    #defining the magic constants p=0xb7e15163 q=0x9e3779b9 pt=list() pt1=list() ct=list() pt2=list() #pt[0]=0pt1[0]=ct[0]=pt1[1]=ct[1]=0 s=[] l=[] b=8 key=[0,0,0,0,0,0,0,0,0] w=8 t=16 def enc(c,d): for i in range(1,r): A=A+s[0] B=B+s[1] A=A^B A=str(A) B=str(B) A=A[len(B):]+A[:len(B)] B=B^A A=str(A) B=str(B) B=B[len(A):]+B[:len(B)] A=A+s[2*i] B=B+s[2*i+1] ct.append(A) ct.append(B) def denc(): for i in range(r,1): A=ct[0] B=ct[1] B=B-s[2*i+1] B=B[len(c):] + B[:len(c)] B=B^A A=A-s[2*i] A=A[:len(B)]+c[len(B):] A=A^B pt1[1]=B-S[1] pt1[0]=A-S[0] def setup(k): u=w/8 for i in range(b-1,0): l.append(l[i/u:8]+l[8:i/u]+k[i]) s.append(p) for i in range(1,t-1): s.append(s[i-1] + q) i=j=0 A=B=0 for i in range(0,3*t): A=s.append(s[i]+A+B) B=s.append(s[:3]+s[3:]) #B=l.append((l[j]+A+B)) ll=len(str(A))+len(str(B)) B=l.append(l[:ll]+l[ll:]) i=(i+1)%t j=(j+1)%t def pri(g): for k in range(0,w): print g & 0xFF #for i in range(0,b): #key[i]=ct[0]%(255-j) pt1=[raw_input()] pt1=[raw_input()] setup(key) enc(pt1,ct) denc(ct,pt2) print("key") print(key) print("plaintext") printword(pt1[0]),printword(pt1[1]) printword(ct[0]),printword(ct[1]) the list l is always going out of index though it should not . I am not able to take the length of the string A even though it is a string .Once i convert it to string i am not able to add it in s[j]+A+B. How to get around such errors and make the code more hygenic .. This is an rc5 cipher.

    Read the article

  • Why does Clojure hang after hacing performed my calculations?

    - by Thomas
    Hi all, I'm experimenting with filtering through elements in parallel. For each element, I need to perform a distance calculation to see if it is close enough to a target point. Never mind that data structures already exist for doing this, I'm just doing initial experiments for now. Anyway, I wanted to run some very basic experiments where I generate random vectors and filter them. Here's my implementation that does all of this (defn pfilter [pred coll] (map second (filter first (pmap (fn [item] [(pred item) item]) coll)))) (defn random-n-vector [n] (take n (repeatedly rand))) (defn distance [u v] (Math/sqrt (reduce + (map #(Math/pow (- %1 %2) 2) u v)))) (defn -main [& args] (let [[n-str vectors-str threshold-str] args n (Integer/parseInt n-str) vectors (Integer/parseInt vectors-str) threshold (Double/parseDouble threshold-str) random-vector (partial random-n-vector n) u (random-vector)] (time (println n vectors (count (pfilter (fn [v] (< (distance u v) threshold)) (take vectors (repeatedly random-vector)))))))) The code executes and returns what I expect, that is the parameter n (length of vectors), vectors (the number of vectors) and the number of vectors that are closer than a threshold to the target vector. What I don't understand is why the programs hangs for an additional minute before terminating. Here is the output of a run which demonstrates the error $ time lein run 10 100000 1.0 [null] 10 100000 12283 [null] "Elapsed time: 3300.856 msecs" real 1m6.336s user 0m7.204s sys 0m1.495s Any comments on how to filter in parallel in general are also more than welcome, as I haven't yet confirmed that pfilter actually works.

    Read the article

  • Parsing some results returned by nokogiri in ruby, getting an error message

    - by Khat
    The following code returns an error: require 'nokogiri' require 'open-uri' @doc = Nokogiri::HTML(open("http://www.amt.qc.ca/train/deux-montagnes/deux-montagnes.aspx")) #@doc = Nokogiri::HTML(File.open("deux-montagnes.html")) stations = @doc.xpath("//area") stations.each { |station| str = station reg = /href="(.*)" title="(.*)"/ href = reg.match(str)[1] title = reg.match(str)[2] page = /.*\/(.*).aspx$/.match(href)[1] puts href puts title puts page base_url = "http://www.amt.qc.ca" complete_url = base_url + href puts complete_url } ERROR: station_names_from_map.rb:9:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError) from /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/node_set.rb:213:in `block in each' from /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/node_set.rb:212:in `upto' from /opt/local/lib/ruby1.9/gems/1.9.1/gems/nokogiri-1.4.1/lib/nokogiri/xml/node_set.rb:212:in `each' from station_names_from_map.rb:7:in `<main>' shell returned 1 While this code works: str = '<area shape="poly" alt="Deux-Montagnes" coords="59,108,61,106,65,106,67,108,67,113,65,115,61,115,59,113" href="/train/deux-montagnes/deux-montagnes.aspx" title="Deux-Montagnes">' reg = /href="(.*)" title="(.*)"/ href = reg.match(str)[1] title = reg.match(str)[2] page = /.*\/(.*).aspx$/.match(href)[1] puts href puts title puts page base_url = "http://www.amt.qc.ca" complete_url = base_url + href puts complete_url Any reason why?

    Read the article

  • "Ambigous type variable" error when defining custom "read" function

    - by Tener
    While trying to compile the following code, which is enhanced version of read build on readMay from Safe package. readI :: (Typeable a, Read a) => String -> a readI str = case readMay str of Just x -> x Nothing -> error ("Prelude.read failed, expected type: " ++ (show (typeOf > (undefined :: a))) ++ "String was: " ++ str) I get an error from GHC: WavefrontSimple.hs:54:81: Ambiguous type variable `a' in the constraint: `Typeable a' arising from a use of `typeOf' at src/WavefrontSimple.hs:54:81-103 Probable fix: add a type signature that fixes these type variable(s)` I don't understand why. What should be fixed to get what I meant? EDIT: Ok, so the solution to use ScopedTypeVariables and forall a in type signature works. But why the following produces very similar error to the one above? The compiler should infer the right type since there is asTypeOf :: a -> a -> a used. readI :: (Typeable a, Read a) => String -> a readI str = let xx = undefined in case readMay str of Just x -> x `asTypeOf` xx Nothing -> error ("Prelude.read failed, expected type: " ++ (show (typeOf xx)) ++ "String was: " ++ str)

    Read the article

  • Colour manipulation of custom tags in niceEdit HTML editor ( JS / DOM )

    - by Chris
    Hi, I would like to be able to highlight, during typing and in real time, certain custom tags in the format #tag_name# within the text of a nicEdit instance ( http://nicedit.com/ ). My current attempt to implement as close to this as possible revolves around using the blur event of the editor to highlight the tags once the editor loses focus. I then use the following logic to wrap the tags in a span with a highlight class.. htmlEditor.addEvent( "blur", function( ) { str = nicEditors.findEditor( "html_content" ).getContent( ); // Remove existing spans first, leaving just the tag ( this could mess up if the html has been edited directly ) str = str.replace( /(<span class=\"highlight\">)(.[^<]+)(<\/span>)/gi, "$2" ); // Then wrap all instances of a particular tag with the highlight span str = str.replace( /#tag_name#/gi, "<span class='highlight'>#tag_name#</span>" ); nicEditors.findEditor( "html_content" ).setContent( str ); }); This is not ideal as my actual text now contains unwanted spans ( I only want the highlighting for the user's input experience, not to be saved to the database ). Obviously I could remove the spans before saving the text but the whole system is currently open to errors ( If the html is directly edited then other text may get highlighted etc ). What I would like to know is.. Is there any way to directly change the colour of the tags in the editor or DOM without using a mechanism such as this? Perhaps a way of colouring the text in memory rather than changing the HTML ? Any ideas ? Regards Chris P

    Read the article

  • Algorithm to detect how many words typed, also multi sentence support (Java)

    - by Alex Cheng
    Hello all. Problem: I have to design an algorithm, which does the following for me: Say that I have a line (e.g.) alert tcp 192.168.1.1 (caret is currently here) The algorithm should process this line, and return a value of 4. I coded something for it, I know it's sloppy, but it works, partly. private int counter = 0; public void determineRuleActionRegion(String str, int index) { if (str.length() == 0 || str.indexOf(" ") == -1) { triggerSuggestionList(1); return; } //remove duplicate space, spaces in front and back before searching int num = str.trim().replaceAll(" +", " ").indexOf(" ", index); //Check for occurances of spaces, recursively if (num == -1) { //if there is no space //no need to check if it's 0 times it will assign to 1 triggerSuggestionList(counter + 1); counter = 0; return; //set to rule action } else { //there is a space counter++; determineRuleActionRegion(str, num + 1); } } //end of determineactionRegion() So basically I find for the space and determine the region (number of words typed). However, I want it to change upon the user pressing space bar <space character>. How may I go around with the current code? Or better yet, how would one suggest me to do it the correct way? I'm figuring out on BreakIterator for this case... To add to that, I believe my algorithm won't work for multi sentences. How should I address this problem as well. -- The source of String str is acquired from textPane.getText(0, pos + 1);, the JTextPane. Thanks in advance. Do let me know if my question is still not specific enough.

    Read the article

  • Replace textfields with dropdown select fields

    - by 47
    I have three model classes that look as below: class Model(models.Model): model = models.CharField(max_length=20, blank=False) manufacturer = models.ForeignKey(Manufacturer) date_added = models.DateField(default=datetime.today) def __unicode__(self): name = ''+str(self.manufacturer)+" "+str(self.model) return name class Series(models.Model): series = models.CharField(max_length=20, blank=True, null=True) model = models.ForeignKey(Model) date_added = models.DateField(default=datetime.today) def __unicode__(self): name = str(self.model)+" "+str(self.series) return name class Manufacturer(models.Model): MANUFACTURER_POPULARITY_CHOICES = ( ('1', 'Primary'), ('2', 'Secondary'), ('3', 'Tertiary'), ) manufacturer = models.CharField(max_length=15, blank=False) date_added = models.DateField(default=datetime.today) manufacturer_popularity = models.CharField(max_length=1, choices=MANUFACTURER_POPULARITY_CHOICES) def __unicode__(self): return self.manufacturer I want to have the fields for model series and manufacturer represented as dropdowns instead of text fields. I have customized the model forms as below: class SeriesForm(ModelForm): series = forms.ModelChoiceField(queryset=Series.objects.all()) class Meta: model = Series exclude = ('model', 'date_added',) class ModelForm(ModelForm): model = forms.ModelChoiceField(queryset=Model.objects.all()) class Meta: model = Model exclude = ('manufacturer', 'date_added',) class ManufacturerForm(ModelForm): manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) class Meta: model = Manufacturer exclude = ('date_added',) However, the dropdowns are populated with the unicode in the respective class...how can I further customize this to get the end result I want? Also, how can I populate the forms with the correct data for editing? Currently only SeriesForm is populated. The starting point of all this is from another class whose declaration is as below: class CommonVehicle(models.Model): year = models.ForeignKey(Year) series = models.ForeignKey(Series) .... def __unicode__(self): name = ''+str(self.year)+" "+str(self.series) return name

    Read the article

  • In asp.Net, writing code in the control tag generates compile error

    - by Nour Sabouny
    Hi this is really strange !! But look at the following asp code: <div runat="server" id="MainDiv"> <%foreach (string str in new string[]{"First#", "Second#"}) { %> <div id="<%=str.Replace("#","div") %>"> </div> <%} %> </div> now if you put this code inside any web page (and don't worry about the moral of this code, I made it just to show the idea) you'll get this error : Compiler Error Message: CS1518: Expected class, delegate, enum, interface, or struct Of course the error has nothing to do with the real problem, I searched for the code that was generated by asp.net and figured out the following : private void @__RenderMainDiv(System.Web.UI.HtmlTextWriter @__w, System.Web.UI.Control parameterContainer) { @__w.Write("\r\n "); #line 20 "blabla\blabla\Default.aspx" foreach (string str in new string[] { "First#", "Second#" }) { #line default #line hidden @__w.Write("\r\n <div id=\""); #line 22 "blabla\blabla\Default.aspx" @__w.Write(str.Replace("#", "div")); #line default #line hidden @__w.Write("\">\r\n "); } This is the code that was generated from the asp page and this is the method that is meant to render our div (MainDiv), I found out that there is a missing bracket "}" that closes the method or the (for loop). now the problem has three parts: 1- first you should have a server control (in our situation is the MainDiv) and I'm not sure if it is only the div tag. 2- HTML control inside the server control and a code inside it using the double quotation mark ( for example <div id="<%=str instead of <div id='<%=str. 3-Any keyword which has block brackets e.g.:for{},while{},using{}...etc. now removing any part, will solve the problem !!! how is this happening ?? any ideas ? BTW: please help me to make the question more obvious, because I couldn't find the best words to describe the problem.

    Read the article

  • Combine regular expressions for splitting camelCase string into words

    - by stou
    I managed to implement a function that converts camel case to words, by using the solution suggested by @ridgerunner in this question: Split camelCase word into words with php preg_match (Regular Expression) However, I want to also handle embedded abreviations like this: 'hasABREVIATIONEmbedded' translates to 'Has ABREVIATION Embedded' I came up with this solution: <?php function camelCaseToWords($camelCaseStr) { // Convert: "TestASAPTestMore" to "TestASAP TestMore" $abreviationsPattern = '/' . // Match position between UPPERCASE "words" '(?<=[A-Z])' . // Position is after group of uppercase, '(?=[A-Z][a-z])' . // and before group of lowercase letters, except the last upper case letter in the group. '/x'; $arr = preg_split($abreviationsPattern, $camelCaseStr); $str = implode(' ', $arr); // Convert "TestASAP TestMore" to "Test ASAP Test More" $camelCasePattern = '/' . // Match position between camelCase "words". '(?<=[a-z])' . // Position is after a lowercase, '(?=[A-Z])' . // and before an uppercase letter. '/x'; $arr = preg_split($camelCasePattern, $str); $str = implode(' ', $arr); $str = ucfirst(trim($str)); return $str; } $inputs = array( 'oneTwoThreeFour', 'StartsWithCap', 'hasConsecutiveCAPS', 'ALLCAPS', 'ALL_CAPS_AND_UNDERSCORES', 'hasABREVIATIONEmbedded', ); echo "INPUT"; foreach($inputs as $val) { echo "'" . $val . "' translates to '" . camelCaseToWords($val). "'\n"; } The output is: INPUT'oneTwoThreeFour' translates to 'One Two Three Four' 'StartsWithCap' translates to 'Starts With Cap' 'hasConsecutiveCAPS' translates to 'Has Consecutive CAPS' 'ALLCAPS' translates to 'ALLCAPS' 'ALL_CAPS_AND_UNDERSCORES' translates to 'ALL_CAPS_AND_UNDERSCORES' 'hasABREVIATIONEmbedded' translates to 'Has ABREVIATION Embedded' It works as intended. My question is: Can I combine the 2 regular expressions $abreviationsPattern and camelCasePattern so i can avoid running the preg_split() function twice?

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >