text
stringlengths
8
267k
meta
dict
Q: Validate values for decimal and integers I need to validate that a TextBox contains only numbers, with allowances for commas and/or decimal points. Here are a few examples of valid entries: * *12.7 *19.245,7 *11,123.326.7 *16,7 *0.19 *0,5 And here are some examples of invalid entries: * *12.00 --> 12 *19.000,7 --> 19000,7 *.125 --> 0.125 *000.000 --> 0 I'm using this regex, both it doesn't work: @"^[0-9]([\.\,][0-9]{1,3})?$" How can I do this? A: If you are using asp.net. You can use the comparevalidator and set the Operator to DataTypeCheck and set Type to Double (or currency)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 2.3.14: How to serialise an ActionController::Request object? I need to write some methods that Do Things based on the kind of request object received by a Rails 2.3.14 controller. However, I don't want to fire up the entire application, nor even a controller; I'd like to have just a marshalled copy of such an object that I can work with outside of the Rails environment. Unfortunately, the ActionController::Request objects passed to controllers include, deep in their bowels, Proc objects which are inherently unserialisable. Does anyone know of a way to serialise one of these objects such that I can store it away in a data file and re-create it in another script? I would prefer not to monkey-patch the Proc class to provide a #marshal_dump method.. Thanks! A: The trick is to replace/delete not serializable objects (especially in the env-hash). I implemented parts of it in this SO answer. I slightly updated my approach using a rails 3.2.13 request object. ## # build a serializable hash out of the given request object def make_request_serializable(request) request_hash = { :env => request.env.clone, :filtered_parameters => request.filtered_parameters.clone, :fullpath => request.fullpath, :method => request.method, :request_method => request.request_method } #clean up the env-hash, as it contains not serializable objects request_hash[:env].tap do |env| env.delete "action_dispatch.routes" env.delete "action_dispatch.logger" env.delete "action_controller.instance" env.delete "rack.errors" env["action_dispatch.remote_ip"] = env["action_dispatch.remote_ip"].to_s end request_hash end # later in the controller puts make_request_serializable(request).to_json #=> {"env":{"SERVER_SOFTWARE":"thin 1.5.1 codename Straight Razor","SERVER_NAME":"localhost","rack.input":[],"rack.version":[1,0], ... (shortened, as it's a lot of output) Update: owww, I've just seen that you are asking vor Rails 2.3.14. My visual filter let me see 3.2.14 instead. So this only works for a current rails version, sorry.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Overloading I/O operator C++ I'm trying to overload the << operator. I'm expecting the output to be InitializingHello WorldOut but it is just outputting Hello World. I can't figure out what is wrong with my code. Thanks for your help. #include <iostream> using namespace std; ostream &operator << (ostream &out, const char* &s) { out << "Initializing" << s << "Out"; return out; } void main() { cout << "Hello World" << endl; system("Pause"); } A: "Hello World" is actually of type const char[12], which can decay into an r-value (temporary) of type const char *, but your function takes a reference to a const char*, and as you may know, you cannot bind a reference to a non-const r-value. So your operator is not called, but instead the standard ostream &operator << (ostream &out, const char* s) is. PS. Please do not write void main(). It should be int main() unless you are in an embedded system (not likely). A: There already is an overload for << with the exact same prototype. The compiler cannot decide which to use... A: There is already a operator<< for const char* defined in the standard library, which is used in the output. Your overload is not used because the temporary string literal cannot be bound to the non-const reference in the operators second parameter. If you remove the reference or make it const, then your operator is called. It doesn't even conflict with the one in your standard library, since that one is implemented as a function template. Yours is not, and non-templated functions are preferred by the compiler. If it is then called, it leads to a stack overflow because out << "Initializing" immediately calls the same operator again recursively. A: I think that since the left hand side is in the std namespace, it's using the function ostream& std::operator << (ostream &out, const char* s) that's defined in the std namespace instead of yours in the global namespace. If you were to try to put yours into the std namespace, you'd get a linker error. Your only real hope is to change the types of one side or the other, probably by making a wrapper around them. struct charptr { const char* ptr; charptr(const char* p) :ptr(p) {} }; ostream &operator << (ostream &out, const charptr &s) { out << "Initializing" << s.ptr << "Out"; return out; } int main() { //int main, not void cout << charptr("Hello World") << endl; system("Pause"); } A: rodrigo pointed out that the type of a string literal is const char[x], and I had an evil idea: #include <iostream> using namespace std; template<int len> ostream &operator << (ostream &out, const char (&s)[len]) { out << ((const char*)"Initializing") << ((const char*)s) << ((const char*)"Out"); return out; } int main() { cout << "Hello World" << endl; } http://ideone.com/7wCNy
{ "language": "en", "url": "https://stackoverflow.com/questions/7604154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Oracle: Similar to sysdate but returning only time and only date I understand that Oracle sysdate returns the current date AND time. That's great for timestamp or datetime columns. Now let's say I have a DATE only column. What keywords should I use on my insert query? insert into myTable1(myDateOnlyColumn) values(???) And let's say I have a TIME only column. What keywords should I use on my insert query? insert into myTable2(myTimeOnlyColumn) values(???) Thanks! A: There is no such thing as a DATE only column in Oracle. The DATE datatype stores date and time. If you only care about the date, you can: INSERT INTO tbl (dtCol) VALUES (TO_DATE('20110929','YYYYMMDD'); This leaves the time component at 00:00:00. You don't have to display it though. If you're only interested in the time component, you still have a date stored in the column. You'll just have to handle that on output. For example: SQL> CREATE TABLE dt (d DATE); SQL> INSERT INTO dt VALUES (TO_DATE('1:164800','J:HH24MISS')); 1 row inserted Showing the actual contents of the column reveals a date was inserted: SQL> SELECT * FROM dt; D -------------------- 0/0/0000 4:48:00 PM Selecting only the time component from the column gives you the output you want: SQL> SELECT TO_CHAR(d, 'HH24:MI:SS') d FROM dt; D -------- 16:48:00 SQL> If you think you need only a time column, you'll want to make sure you always insert the same date component. A: To remove time from sysdate you can just write TRUNC(sysdate). For example: SELECT TRUNC(SYSDATE) "TODAY" FROM DUAL; will give you: TODAY ------------------------- '2012-10-02 00:00:00' A: select sysdate, to_date(to_char(sysdate, 'dd/mm/yyyy'),'dd/mm/yyyy') d from dual A: For whoever is looking for a simple solution for returning only date without time, I found this: to_date(SYSDATE,'dd/mm/yyyy') Works like a charm. ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: XML to string in velocity I have XML files that have nodes with formatted HTML. I am trying to print out the html contents to the page but velocity is stripping out the HTML tags. How do you I print html content stored in an XML file using velocity? XML File <?xml version="1.0" encoding="utf-8"?> <system-data-structure> <heading>This is a Title</heading> <main> <content> <h1>this is formatted html</h1> <p>content I want <b>to</b> <em>show</em> on my page </p> </content> </main> </system-data-structure> Velocity Code #set ($html = $contentRoot.getChild('main').getChild('content')) <h1>$contentRoot.getChild('heading').value</h1> <div>$html.value</div> note: this is my first time ever using the velocity engine A: Velocity doesn't strip anything out. If you have the right event handlers configured you could have Velocity escape html output (which i don't think you want). But there is no support in Velocity for stripping anything out. What output are you actually getting? Are you using a framework or CMS that is configuring Velocity for you? Maybe it is something else that is "stripping out the html tags".
{ "language": "en", "url": "https://stackoverflow.com/questions/7604168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Selecting arrays in nicely printed format in SQL I'm trying to select for a two dimensional array of integers, and directing the output to a file. Is there any way that I can write a postgresql statement that would make the output of the select statement nicely formatted. As in each array of integers that is an element of the 2D array is on its own line. Right now I just get this output: SELECT array FROM table LIMIT 1; {{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3} ,{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3} ,{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3}} And I would like to get something more like this: {0,0,0} {1,1,1} {2,2,2} ... I can do this after the query returns with some parsing, but if its possible to do it in Postgres itself that would be ideal. A: There are several ways. One way is to cast the array to text and split it up with regexp_split_to_table(). This function is present in PostgreSQL 8.3 or later. SELECT regexp_split_to_table(trim(my_2d_intarr::text, '{}'), '},{'); Output: 0,0,0 1,1,1 2,2,2 If you want the enclosing brackets (maybe you don't?), add them back like this: SELECT '{' || regexp_split_to_table(trim(my_2d_intarr::text, '{}'), '},{') || '}'; Ourtput: {0,0,0} {1,1,1} {2,2,2} Alternative: This should also work with PostgreSQL 8.2 or maybe even earlier, but I did not test that. SELECT my_2d_int_arr_var[x:x][1:3] FROM (SELECT generate_series(1, array_upper(my_2d_intarr, 1), 1)::int4 AS x)) x Output: {{0,0,0}} {{1,1,1}} {{2,2,2}} (You may want to strip some curly brackets ..) Else, I would write a plpgsql function that loops through the array. Fairly easy. There is also the related unnest() function, but it returns a row per base element (integer in this case), so it's no use here. One (fast!) way to output the result: COPY.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: .htaccess image to web page redirect? Is there a .htaccess script I can use to redirect the url of an image to an actual web page? What can I do to make it so when someone accesses an image via their address bar by typing in: http://www.sitename.com/images/1.jpg It will instead redirect the user to the web page: http://www.sitename.com/view/1.html I want to still be able to place the images in image tags though. A: RewriteCond %{HTTP_REFERER} !^https?:\\www\.yourdomain\.com RewriteCond %{REQUEST_URI} (.*)\.jpg$ RewriteRule images/(\d+)\.jpg http://www.yourdomain.com/view/$1.html [L,R=301] by using this you can put images in img tag and it will work but If you try to access them directly , it will redirect to html file. Note: If you want others have permission to use your images use this: RewriteCond %{HTTP_REFERER} ^$
{ "language": "en", "url": "https://stackoverflow.com/questions/7604181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hibernate calling INSERT on POST, but some data not there when I GET I am trying to use Hibernate to store two objects, Users (which have ID, name, and ImageURL) and Players (which have a User, Points, and FriendIDList). For some reason, hibernate is correctly storing Users, and saying it is performing an INSERT into PLAYER, but when I try to retrieve the Player I just persisted (or any player) the collection is always empty. Users come back correctly. Tried em.flush() which didn't help, and tried creating a new Player with default constructor and doing em.persist on that but got same results. Please help. I really can't figure out what's wrong here. This should be pretty basic. Here is my WebService code for the POST on Players @Path("/webService") @RequestScoped @Consumes({ "application/json" }) @Produces({ "application/json" }) public class MyWebService { @PersistenceContext(type = PersistenceContextType.EXTENDED) private EntityManager em; @POST @Path("/PlayerRequest/{id}/{name}/{imageURL}") @Consumes("application/json") public Player playerPOSTRequest( @PathParam("id") long id, @PathParam("name") String name, @PathParam("imageURL") String imageURL, ArrayList<String> JsonInput) { System.out.println("POST on a PlayerRequest for Player id: ["+ id + "]"); User foundUser = null; foundUser = getUserByid(em, id); if(null == foundUser){ User user = new User(id, name, imageURL); em.persist(user); foundUser = user; } Player foundPlayer = null; foundPlayer = getPlayerByid(em, id); if (null == foundPlayer) { Player player = new Player(foundUser); em.persist(player); em.flush(); //Try Flushing to see if that helps foundPlayer = player; Player newPlayer = new Player(); //See if default constructor is any different em.persist(newPlayer); //Try default constructor just to see } else { // RETURNING PLAYER System.out.println("Welcome back. You are a current player."); } //Use JsonInput for stuff here System.out.println("Returning Player: " + foundPlayer); return foundPlayer; }// playerPOSTRequest }//myWebService Here is my Player class (less the get/setters) @XmlRootElement @Entity @Table(name = "PLAYER") public class Player implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id private @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, nullable = false) Long id = null; @Version private @Column(name = "version") int version = 0; public Player(){ } public Player(User user) { this.PlayerInfo = user; this.Points = 100; //New users get 100 points to start with this.FriendList = new ArrayList<Long>(); } @OneToOne @JoinColumn(name="id") private User PlayerInfo; @Column private long Points; @Column private ArrayList<Long> FriendList; @Override public String toString() { return "Player [PlayerInfo_FBID=" + PlayerInfo.getFacebookID() + ", PlayerInfo_Name=" + PlayerInfo.getName() + "Points=" + Points + "]"; } } Here is my User class less get/setters: @XmlRootElement @Entity @Table(name = "USER") public class User implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id private @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id", updatable = false, nullable = false) Long id = null; @Version private @Column(name = "version") int version = 0; public User(){ } public User(long id, String name, String imageURL){ this.id = id; this.Name = name; this.ImageURL = imageURL; } @Column(name = "myId", unique = true) private long myId; @Column private String Name; @Column private String ImageURL; @Override public String toString() { return "User [id=" + myId + ", Name=" + Name + "ImageURL=" + ImageURL + "]"; } } When I run through this, here's the output I'm getting in the console, note the two INSER into PLAYER statements Hibernate is making (one is for the default constructor Player), but in the retrieves, I am able to get the user, but there are no existing players: POST on a PlayerRequest for Player ID: [36985] Hibernate: select user0_.id as id12_, user0_.myID as myID12_, user0_.ImageURL as ImageURL12_, user0_.Name as Name12_, user0_.version as version12_ from USER user0_ where user0_.myID=? New User for PlayerInfo for Player request. Adding User to the system. Hibernate: call next value for hibernate_sequence Hibernate: insert into USER (myID, ImageURL, Name, version, id) values (?, ?, ?, ?, ?) Hibernate: select player0_.id as id13_, player0_.FriendList as FriendList13_, player0_.Points as Points13_, player0_.version as version13_ from PLAYER player0_ cross join USER user1_ where player0_.id=user1_.id and user1_.myID=? New Player request. Adding Player to the system. Hibernate: call next value for hibernate_sequence Hibernate: insert into PLAYER (FriendList, Points, version, id) values (?, ?, ?, ?) Hibernate: call next value for hibernate_sequence Hibernate: insert into PLAYER (FriendList, Points, version, id) values (?, ?, ?, ?) Returning Player: Player [PlayerInfo_ID=36985, PlayerInfo_Name=Joe Smith Points=100] GET on specific Player for User ID: [36985] Hibernate: select player0_.id as id13_, player0_.FriendList as FriendList13_, player0_.Points as Points13_, player0_.version as version13_ from PLAYER player0_ cross join USER user1_ where player0_.id=user1_.id and user1_.myID=? Returning Player: null GET on All Players Hibernate: select player0_.id as id13_, player0_.FriendList as FriendList13_, player0_.Points as Points13_, player0_.version as version13_ from PLAYER player0_ cross join USER user1_ where player0_.id=user1_.id and user1_.myID>? Returning List: [] GET on specific User for User ID: [36985] Hibernate: select user0_.id as id12_, user0_.myID as myID12_, user0_.ImageURL as ImageURL12_, user0_.Name as Name12_, user0_.version as version12_ from USER user0_ where user0_.myID=? Returning User: User [ID=36985, Name=Bob Smith ImageURL=www.myImage.com] A: The problem seems to be in the Player's mapping annotations. @OneToOne @JoinColumn(name="id") The name given to the JoinColumn is the same given to the id (PK). Thus, Hibernate is generating a wrong sql query, making a incorrect join between the two tables.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculate time to decelerate using initial speed and decay I'm trying to calculate the time it will take a movieclip in Flash to decelerate to zero. The starting speed will vary, but for purpose of example lets say: Frames Per Second: 30 Speed: 50 Decay: .8 * current speed each frame onEnterFrame(event:Event):void { movieClip.x += speed; speed *= .8; } How would I figure out the time in seconds or in total frames it would take to decelerate to zero? Thanks! A: First of all, what you call acceleration is in fact speed/velocity in pixels per frame. Starting from the very first frame (i-th) when you start adjusting velocity by a factor of 0.8 you can express the velocity as: v(i) = v(i-1) * 0.8 and v(0) = 50 You can reexpress v(i) using v(0) as: v(i) = v(0) * 0.8i I can think of 2 different stop conditions: 1. v(i) < 1 (meaning: velocity drops below 1 px/frame) 2. v(i) - v(i+1) < 0.1 (meaning: velocity changes by less than 0.1 px between frames) For the first you get: v(0) * 0.8i < 1 0.8i < 1 / v(0) i > log0.8(1 / v(0)) changing the logarithm base using logb(x) = loga(x) / loga(b): i > ln(1 / v(0)) / ln(0.8) i > ln(1 / 50) / ln(0.8) i > 17.531 For the second you get: v(0)*0.8i - v(0)*0.8i+1 < 0.1 v(0)*0.8i - v(0)*0.8i * 0.8 < 0.1 v(0)*0.8i * (1 - 0.8) < 0.1 0.8i < 0.1 / (v(0) * (1 - 0.8)) i > log0.8(0.1 / (v(0) * (1 - 0.8))) i > ln(0.1 / (v(0) * (1 - 0.8))) / ln(0.8) i > ln(0.1 / (50 * (1 - 0.8))) / ln(0.8) i > 20.638 So, with these numbers you get about 20 frames worth of time till the movement stops. Tweak the numbers as you see fit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do I need to initialize the values of a structure before I use them? I need to create a dynamic array of a struct wordStruct that holds a string and the number of times it occurs in a text file: typedef struct wordStruct{ char word[50]; int count = 0; }wordStruct; I will get the number I need from reading the number of words in the file, let's call it wordCount. struct wordStruct *wordList; wordList = (wordStruct *)malloc(wordCount * sizeof(wordStruct)); Is this the correct way to allocate the memory for struct array? Would calloc() be a better option? int wordListIndex = 0; char[50] inWord; // No word will be more than 49 characters + null terminator for (i = 0; i < wordCount; i++){ fscanf(data, "%s", inWord); for (j = 0; j < wordCount; j++){ if (strcmp(wordList[j].word, inWord) == 0){ wordList[j].count++; break; } } if (j == wordCount){ strcpy(wordList[wordListIndex].word, inWord) wordListIndex++; } I know that this probably isn't the most efficient code, but do I have the right idea? Can I use the strcmp() method even though there may not be any data in those array locations? I'm new to structs and I'm not sure what I can and cannot do. Thanks. A: If you use malloc, you need to initialize the array (e.g., using memset). If you use calloc, the array is initialized to 0 for you. Once the array is initialized, you can use strcmp on it, because setting it to 0 makes all the words be zero-length (empty) strings. Before initializing it, you must not use strcmp. (I'm assuming the weird char[50] varname instead of char varname[50] are typos in your SO question, else this wouldn't compile. I'm also ignoring the buffer overflow in fscanf and strcpy… well, technically, I guess I'm not. And the lack of error handling.) A: The nested for loop should use wordListIndex for the boundary condition and the last if block should be taken out of the inner for loop. The condition should should be if (j == wordListIndex){ strcpy(wordList[wordListIndex].word, inWord) wordListIndex++; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: objected oriented and parsing csv i have to parse csv file which has customers and product they have ordered . customers can repeat for different product . i have to get all the unique customers and products they have ordered. Then print out each customer and there product . i have been asked to do in a object oriented way so 1) should i create a customer objects and have a product as there attribute 2) just write a program using foreach and loop through and store customer and product in a hash and print it out . what throws me off is i have been asked to do it in a object oriented way. if do it by creating objects how can i store a custom object in memory ? so that if i come across a customer second time i have to add the product and at the end i have to loop through all the objects and print it out . sorry i have bad English thanks reading a long question and for the help. A: How can you store a custom object in memory? By creating the object and keeping it in a list, hash, or whatever seems appropriate. (Probably a hash, with the key being whatever unique value you have in your CSV, and the value would be a collection of products.) Being asked to do it in "an object-oriented way" is a little arbitrary, though. A: If you are using FasterCSV or Ruby 1.9 you can extend the parser allowing you to map each CSV row to a custom object. # http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-c-load # http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-c-dump # https://github.com/JEG2/faster_csv/blob/master/test/tc_serialization.rb require 'csv' class Person attr_accessor :id, :name, :email def self.csv_load(meta, headers, row) person = Person.new headers.each.with_index { |h,i| person.send "#{h}=", row[i] } person end def self.parse(csv) meta = "class,#{self.to_s}\n" CSV.load("#{meta}#{csv}") end def dump self.class.dump([self]) end def self.dump(people, io='', options={}) CSV.dump(people, io, options).strip end def self.csv_meta [] end def csv_headers %w(id name email) end def csv_dump(headers) headers.map { |h| self.instance_variable_get "@#{h}" } end end CSV_DUMP = <<-CSV class,Person id=,name=,email= 1,"First Dude",dude@company.com 2,"Second Dude",2nddude@company.com 3,"Third Dude",3rddude@company.com CSV CSV_INPUT = <<-CSV id,name,email 1,"First Dude",dude@company.com 2,"Second Dude",2nddude@company.com 3,"Third Dude",3rddude@company.com CSV CSV_DUMP2 = <<-CSV class,Person #{CSV_INPUT} CSV people = Person.parse(CSV_INPUT) puts people.inspect dumped = Person.dump(people) puts dumped puts "----" puts Person.parse(dumped).inspect
{ "language": "en", "url": "https://stackoverflow.com/questions/7604200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scripted main in OCaml? How can I emulate this Python idiom in OCaml? if __name__=="__main__": main() See RosettaCode for examples in other programming languages. A: There is no notion of main module in Ocaml. All the modules in a program are equal. So you can't directly translate this Python idiom. The usual way in Ocaml is to have a separate file containing the call to main, as well as other stuff like command line parsing that only make sense in a standalone executable. Don't include that source file when linking your code as a library. There is a way to get at the name of the module, but it's rather hackish, as it is intended for debugging only. It violates the usual assumption that you can rename a module without changing its behavior. If you rely on it, other programmers reading your code will curse you. This method is provided for entertainment purposes only and should not be used in real life. let name_of_this_compilation_unit = try assert false with Assert_failure (filename, _, _) -> filename You can compare the name of the compilation unit with Sys.executable_name or Sys.argv.(0). Note that this is not really the same thing as the Python idiom, which does not rely on the toplevel script having a particular name. A: $ ocamlc -o scriptedmain -linkall str.cma scriptedmain.ml $ ./scriptedmain Main: The meaning of life is 42 $ ocamlc -o test -linkall str.cma scriptedmain.ml test.ml $ ./test Test: The meaning of life is 42 scriptedmain.ml: let meaning_of_life : int = 42 let main () = print_endline ("Main: The meaning of life is " ^ string_of_int meaning_of_life) let _ = let program = Sys.argv.(0) and re = Str.regexp "scriptedmain" in try let _ = Str.search_forward re program 0 in main () with Not_found -> () test.ml: let main () = print_endline ("Test: The meaning of life is " ^ string_of_int Scriptedmain.meaning_of_life) let _ = let program = Sys.argv.(0) and re = Str.regexp "test" in try let _ = Str.search_forward re program 0 in main () with Not_found -> () Posted on RosettaCode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to rotate an element around a line other than X=0,Y=0 and Z=0 using CSS3? I created this page for better understanding the question. As you can see using CSS3 we can rotate an element around the X,Y or Z axis using transform: rotate[XYZ](M deg/rad). But I'm looking for a function to rotate the element on any given line. For example, rotating the element on x=y line. or even more complex y=2x+3. If you don't understand it please hold a paper in hand and flip it from its two far corners (for y=x or y=-x). or look at this picture. I'm guessing it would be combination of two rotations, but I don't know how to calculate the rotations. Update: I didn't know there is a rotate3d function for CSS transform. this function accepts four arguments rx, ry, rz and deg. I feel that would be very helpful for this problem. Other thing is when we change translate[X,Y,Z] it actually changing the origin of rotation. That mean if you want to rotate around Y=10px you should change the translateZ to 10px Update2: My Actual goal is creating a tool to apply CSS transform property using a GUI. as you can see in my jsbin file. I want to extend it to whatever transform possible you can do. One of them is rotation. I'm sure it's possible to rotate an element around other lines than x=0... but I don't know how can I do the calculation. For example rotation 45deg around Y and 45deg around Z is same as rotating 45 deg around x=y. I need a solution for all lines in the space. A: I suggest reading the introduction to the article Rotation About an Arbitrary Axis in 3 Dimensions . The basics are: (1) Translate space so that the rotation axis passes through the origin. (2) Rotate space about the z axis so that the rotation axis lies in the xz plane. (3) Rotate space about the y axis so that the rotation axis lies along the z axis. (4) Perform the desired rotation by θ about the z axis. (5) Apply the inverse of step (3). (6) Apply the inverse of step (2). (7) Apply the inverse of step (1). A: Solution for question I'm asking is css transform function, rotate3d. Using this function we could rotate DOM elements around any line in 3D space. This function accepts four arguments that three first are x, y and z and last one is rotation. As I understand how this function work you can translate your line linear algebra function into rotate3d like this: If you have a line function like 1x + 2y + 3z = 0 and want to rotate your element 30 degree then you should apply this css property to element; transform: rotate3d(1, 2, 3, 30deg);. I've created this little app to demonstrate how rotate3d works. A: I beleive I understand what you mean. So, if you know Photoshop, when you rotate an image, you can choose an anchor point. This is the same idea. So you add the code rotation-point: 50% 50% to the class. Only issue is, rotation point isn't accepted in any browser yet, but soon will be. I thought you should know that this will eventually be a possibility. here for more
{ "language": "en", "url": "https://stackoverflow.com/questions/7604202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Gwt, CellTable, how can I know which column user clicks for sorting? Writing GWT application. I have CellTable and a code that i'v got from google-example code-site. I need to implement server-side sorting by clicking on table's columns. My code for that is: AsyncDataProvider<MYOBJECT> dataProvider = new AsyncDataProvider<MYOBJECT>() { @Override protected void onRangeChanged(HasData<MYOBJECT> display) { final Range range = display.getVisibleRange(); ... int sortingColumnIndex = 0; boolean isAscending = sortList.get(sortingColumnIndex).isAscending(); // some server-side call here } So, how can I know which column an user clicks on ? I.e. Real index of column of header of column or anything for identifying that column user clicked? I have only HasData display as an event, but it seems is not enough to determinate the column. A: Sorting a CellTable server-side The magic number 0, is the index of the sort column in the sort list, and not the column index from the cell table. So sortList.get(0).getColumn() gets you the column that the user clicked on. You have to worry about the other columns in the sortList only if you plan to implement sorting on multiple columns. A: ColumnSortList sortList = dataTable.getColumnSortList(); Column<?, ?> column = sortList.get(0).getColumn(); Above will give you the required column.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django admin post-save method - how to do? I've got an admin form with a couple of inlines for displaying m2m fields, like so: class ArticleAdmin(admin.ModelAdmin): form = ArticleCustomAdminForm inlines = (SpecificGemInline, SuiteInline,) Base class looks something like that: class Article(models.Model): article_code = models.CharField(max_length=15) gems = models.ManyToManyField(Gem, through='SpecificGem') Model has a special field article_code that should aggregate some data from m2m fields represented in both inlines, so I've written a function create_code(instance) that does so by accessing model instance fields directly, something like that: def create_code(instance): article_code_part1 = SpecificGem.objects.filter(article=instance) article_code_part2 = instance.suite_set.all() instance.article_code = #do something with both parts The problem is, when I call this function from overriden ModelAdmin's save_model() or model's save() functions, following instance m2m fields produces outdated results. Even retarded example below wouldn't help: class ArticleAdmin(admin.ModelAdmin): #... def save_model(self, request, obj, form, change): obj.save() create_code(obj) obj.save() When I get into InlineFormset's clean() method, I have access to its forms' data so I could figure out a part of article_code even without actual saving... but I have two inlines. So how do I find the topmost save method, so I could call my aggregation function after all models are validated and saved to db? A: In order to catch changes to a ManyToManyField, you need to hook up the m2m_changed signal. You might want to have a look at the documentation for signals in general and the m2m_changed signal in particular.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: OSGi DS & deactivating a component manually Is it valid to deactivate a component in OSGi manually if I am using Declarative Services? For example, let's say I have a component, with the implementation: //component class Overseer(){ List<ServiceReference> serviceRefs = ...//populate private void doStuff(){ serviceRef = serviceRefs[i]; if(dontNeedThisAnymore){ serviceRefs.remove(serviceRef); serviceRef.getBundle().stop(); } } A: The best way to do this is from another component in the same bundle, using the ComponentContext API. You can write a component so that it takes ComponentContext as a param to its activate method. That interface has enableComponent and disableComponent methods that can be used to enable/disable other components in the same bundle. I call this a "gatekeeper" component because it can be used to setup resources needed by the other components before enabling them. For example, you may have multiple components that need a database to be started up before they can do their job... the gatekeeper would take care of starting the database and then call enableComponent(null) to enable the other components. Similarly if the gatekeeper could detect that the database has shutdown and at that point disable the other components. In order for this to work, all components in the bundle except for the gatekeeper need to be set initially to enabled="false".
{ "language": "en", "url": "https://stackoverflow.com/questions/7604219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Activity onResume: strange behaviour For demonstrating the activity life cycle, I have added TextToSpeech messages mTts.speak ("<some text>", TextToSpeech.QUEUE_ADD, null); to hear when I am going through onCreate, onResume, and onPause. Findings: In onCreate, you don't hear the text to be spoken (obviously because the activity has not yet resumed?). In onPause, the text spoken was mutilated (obviously because of leaving the activity while the text is spoken?). Building a loop while(mTts.isSpeaking()){} assured the text was completely spoken. Much more strange is the behaviour in onResume: * *Starting the activity the text in onResume is not spoken. *Pressing the HW Home button and opening the app again the text in onResume is spoken. Of course onResume is executed in both cases. For the matter of fact I assigned a string * *in onResume: speakOnResume = "on resume" *in onCreate: speakOnCreate = "on create" and added an event callback to the activity where I called mTts.speak (speakOnResume + " " + speakOnCreate, TextToSpeech.QUEUE_ADD, null); and of course the lady spoke as expected Now the question: Any idea, why onResume behaves differently when starting the activity from scratch v.s. when (in the word's sense) resuming it after it was paused without stopping/destroying?
{ "language": "en", "url": "https://stackoverflow.com/questions/7604221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't get JQuery working on my site? I can't get any JQuery code to work on my website, in particular, slidebox. By the JQuery is not working, I mean, in this case, that when I click on a link, a tag, nothing happens, when really a lightbox should be appearing. Please can you tell me where I am going wrong? <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4 /jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="shadowbox.css"> <script type="text/javascript" src="shadowbox.js"></script> <script type="text/javascript"> Shadowbox.init(); </script> </head> <body> <div class="wrapper"> <header> <a class="logo" href="..."></a> <h1><strong>...</strong>iOS Developer</h1> </header> <section class="portfolio"> <a href="img/image.png" rel="shadowbox" title="SocialPic - Coming fall 2011"><img src="img/image2.png" /></a> <a title="SocialPic - Coming fall 2011" href="img/SocialPic-iPhone.png"><img src="img/image2.png" /></a> <a title="SocialPic - Coming fall 2011" href="img/SocialPic-iPhone.png"><img src="img/image2.png" /></a> <a title="SocialPic - Coming fall 2011" href="img/SocialPic-iPhone.png"><img src="img/image2.png" /></a> </section> A: I suspect it isn't working because there is a space in the path to jQuery. Remove the space and try again. :) http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js
{ "language": "en", "url": "https://stackoverflow.com/questions/7604222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS compatibility check for multiple browsers? Is there an online tool that would take a CSS file and tell me which parts are incompatible with which browser? Ex: property-a -> ff 3.0+, ie7+, etc property-b-> ff 2.0, ie5...
{ "language": "en", "url": "https://stackoverflow.com/questions/7604229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: http basic authentication from java webstart how do I use basic authentication from java webstart? if I simply require authentication on a directory, jws requires login for every jar included in the jar. A: There's probably nothing you can do about that in itself. If you desperately want to protect your code from something, you should probably write a small, unprotected "bootstrapper" that uses JNLP's ExtensionLoaderService to load the rest of the code, doing authentication manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jersey has written my mysql timestamp as 2011-09-28T21:48:25Z how do I format it in Java? I have a mysql backend that has a timestamp field that is auto set as currenttimestamp like so (date_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP). After reading the value as Date, Jersey sends out an xml where the timestamp shows as <timestamp>2011-09-28T21:48:25Z</timestamp> Please don't make too much of the backstory: I can't change what I get from Jersey. Now my question is this: how do I parse the 2011-09-28T21:48:25Z from xml as a date that Java understands? Thanks. A: tl;dr Instant.parse( "2011-09-28T21:48:25Z" ) ISO 8601 Your input string is in standard ISO 8601 format. Jersey is irrelevant, except that its designers wisely chose to use ISO 8601 formats for serializing date-time values as strings. java.time The java.time classes built into Java use ISO 8601 formats by default when parsing/generating Strings. So no need to specify a formatting pattern. UTC The Z on the end is short for Zulu and means UTC (GMT). Instant The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. Instant instant = Instant.parse( "2011-09-28T21:48:25Z" ); Time Zone Adjust that Instant into any time zone you desire. Specify a proper time zone name. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). ZoneId z = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata" etc. ZonedDateTime zdt = instant.atZone( z ); Strings Do not conflate date-time values with Strings that represent such values. You can ask the java.time objects to generate a String in any format you desire. But generally best to let the DateTimeFormatter automatically localize for you. Locale l = Locale.CANADA_FRENCH; // Or Locale.US, Locale.ITALY, etc. DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l ); String output = zdt.format( f ); A: First, DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") ; df.setTimeZone(TimeZone.getTimeZone("Zulu")) ; Date dd = df.parse("2011-09-28T21:48:25Z") ; ...then, optionally, Timestamp ts = new Timestamp(dd.getTime()) ;
{ "language": "en", "url": "https://stackoverflow.com/questions/7604237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: GC in Workstation mode in ASP.NET app I'm looking at dumps and I see mscorwks!WKS::GCHeap::GarbageCollectGeneration+0x1a9. If I understand it is GC doing GarbageCollection in Workstation Mode? I see other threads are waiting on mscorwks!WKS::GCHeap::WaitUntilGCComplete+0x34. Does that mean I run with workstation concurent=false mode of GC? I know that this server is one processor with one core. Should I change to concurent=true for ASP.NET App? If I add another processor will GC automatically run in Server mode? A: Concurrent GC is meant for interactive (UI) applications. For server applications such as ASP.NET, non-concurrent GC should be preferred. As per MSDN documentation, ASP.NET choose what is the best as per system config and you don't have alter this settings. Go through garbage collection documentation on MSDN for more information. As to answer, your last part of question - generally, CLR Host can override configured GC mode value. As per MSDN doc, ASP.NET will choose server GC for multi-processor machines. So yes, if you add one more processor, you should see your ASP.NET app using server mode GC. On side note, probably reliable way to find out the GC mode is using GCSettings.IsServerGC property. Similarly, GCSettings.LatencyMode will tell you if its concurrent GC or not. For example, in workstation mode, Interactive value indicates concurrent GC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Playing an MP3 through Ruby on Rails in chrome I'm writing a Ruby on Rails application which allows a user to upload an mp3 file, then play it back. I have it working to the point where a user can do those things, BUT there is an issue when seeking through the song. If a user seeks ahead (or lets it play) to a spot in the song, usually about 2/3 or 3/4 the way through the song, then attempts to seek back to the beginning (for example 0:20), the play timer will go to 0:20, like it should but the actual audio will start over again as if the user seeked to 0:00. Right now I'm simply attempting to get the song to play in chrome's basic html5 mp3 player that it uses when passed an mp3 file. This is the code I'm using to serve up the file, hopefully with all the correct headers: file_begin = 0 file_size = @media.file_file_size file_end = file_size - 1 if !request.headers["Range"] status_code = "200 OK" else status_code = "206 Partial Content" match = request.headers['range'].match(/bytes=(\d+)-(\d*)/) if match file_begin = match[1] file_end = match[1] if match[2] && !match[2].empty? end response.header["Content-Range"] = "bytes " + file_begin.to_s + "-" + file_end.to_s + "/" + file_size.to_s end response.header["Content-Length"] = (file_end.to_i - file_begin.to_i + 1).to_s response.header["Last-Modified"] = @media.file_updated_at.to_s response.header["Cache-Control"] = "public, must-revalidate, max-age=0" response.header["Pragma"] = "no-cache" response.header["Accept-Ranges"]= "bytes" response.header["Content-Transfer-Encoding"] = "binary" send_file(DataAccess.getUserMusicDirectory(current_user.public_token) + @media.sub_path, :filename => @media.file_file_name, :type => @media.file_content_type, :disposition => "inline", :status => status_code, :stream => 'true', :buffer_size => 4096) I'd appreciate any insight into this problem. I feel like I'm so close because it pretty much all works, except for seeking near the beginning causing a new request. Thanks! A: Is re-invention of the wheel a requirement? The reason I ask is you could have simply allowed the user to upload the MP3 file and used html5's feature as you're targeting Chrome. Paperclip could have taken care of the upload, to somewhere preferable in the public directory, and you just hand off that path to the tag. Crazy ideas removed from my comments (below) to prevent confusing other SO readers. See my last comment for a solution but Amazon S3 is pretty much the best solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Building an xml document from functions that return DOMNodes My question is a rather simple one for anyone familiar with the DOM* classes in PHP. Basically i have different classes that i want to return to me something that I can append in my xml document Following pseudo-code should demonstrate better Class ChildObject{ function exportToXML( return a DOMNode ? ) } Class ContainerObject{ function exportToXML(){ $domSomething = new DOM*SOMETHING*; foreach($children as $child) $domSomething->appendChild($child->exportToXML); return $domSomething ; } } Now i want to create the entire DOMDocument $xml = new DOMDocument(); $root = $xml->createElement('root'); foreach($containers as $container) $root->appendChild($container->exportToXML()); I tried sending the DOMDocument object as a reference, did not work. I tried creating DOMNodes but didn't work as well....so i'm looking at a simple answer: what datatypes do i need to return in order for me to achieve the above functionality? <?php $xml = new DOMDocument(); $h = $xml->createElement('hello'); $node1 = new DOMNode('aaa'); $node1->appendChild(new DOMText('new text content')); //node1 is being returned by a function $node2 = new DOMNode('bbb'); $node2->appendChild(new DOMText('new text content')); //node2 is being returned by some other function $h->appendChild($node1);//append to this element the returned node1 $h->appendChild($node2);//append to this element the returned node2 $xml->appendChild($h);//append to the document the root node $content = $xml->saveXML(); file_put_contents('xml.xml', $content);//output to an xml file ?> The above code should do the following: consider that i want to build the following xml <hello> <node1>aaa</node1> <node2>bbb</node2> </hello> node1 could be again a node that has multiple children so node1 could be as well as something like this: <node1> <child1>text</child1> <child2>text</child2> <child3> <subchild1>text</subchild1> </child3> </node1> Basically when i call exportToXML() something should be returned, call it $x that i can append in my document using $xml->appendChild($x); I want to create the above structure and return the object that can be appended in the DOMDocument A: The following code: <?php $xml = new DOMDocument(); $h = $xml->appendChild($xml->createElement('hello')); $node1 = $h->appendChild($xml->createElement('aaa')); $node1->appendChild($xml->createTextNode('new text content')); $node2 = $h->appendChild($xml->createElement('bbb')); $node2->appendChild($xml->createTextNode('new text content')); $xml->save("xml.xml"); ?> will produce: <?xml version="1.0"?> <hello> <aaa>new text content</aaa> <bbb>new text content</bbb> </hello> Your example XML showed <node1>aaa</node1> but I think your various code snippet examples went out of sync when you were editing =) In case you need that output, try: <?php $xml = new DOMDocument(); $h = $xml->appendChild($xml->createElement('hello')); $node1 = $h->appendChild($xml->createElement('node1')); $node1->appendChild($xml->createTextNode('aaa')); $node2 = $h->appendChild($xml->createElement('node2')); $node2->appendChild($xml->createTextNode('bbb')); $xml->save("xml.xml"); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7604245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to get UISwitch in UITableViewCell with text both sides? How would one get UISwitch in UITableViewCell with text both sides? Background - I currently have a UITableViewController and when it creates the UITableViewCell I place the UISwitch => accessoryView, and the text (only on left) => textLabel. So what I want to do is have a UITableViewCell with text on both sides of the UISwitch, to use it for a setting: METERS <==> FEET A: The best way to achieve what you want is to add the UISwitch and 2 UILabels to the cell's contentView. But I would recommend using a UISegmentedControl for this type of setting instead. A: Or you might try RCSwitch library's custom wide switch. Have a UILabel on the left of the UITableViewCell saying for eg. "Unit" and the wide version of the RCSwitch on the right toggling between the texts Meters and Feet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: webmethod with optional C# arguments appear to be required when invoked as a RESTful URI - gives InvalidOperationException: Missing parameter I have a webmethod which works and I've added some optional parameters (because I don't want to burden all callers with providing these values; they are primarily for my development needs since my webmethod constructs a diagnostic EventLog.WriteEntry): [WebMethod(Description = "DownloadFile method for ASP.Net clients")] public void DownloadFileCF(string trimURL, string TrimRecordNumber , string CallerPC = "not specified" , string RequestorID = "not specified") I can also call the above method with a RESTful URI like this: http://localhost/sdkTrimFileServiceASMX/FileService.asmx/DownloadFileCF?trimURL=60~GROUPER~1137&TrimRecordNumber=5 but then I get this: System.InvalidOperationException: Missing parameter: CallerPC. at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection) at System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest request) at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters() at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest() Yet when I test the webmethods of the webservice on localhost and supply values for only the first 2 textboxes and click INVOKE button, then the arguments are treated as optional. I am VERY brand new to REST rules. Can someone straighten me out on this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7604254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to do perfect KVO for NSManagedObject? Perfect KVO here includes two parts: add observer correctly and remove observer correctly. The story: * *I use one UITableViewCell(cell) to display one NSManagedObject(object). *Each object has some dynamic properties that need observing by its cell. *Not all objects have the same set of observed properties. I add key path observers selectively like this: if (object.thumbnail_pic_url) [object addObserver:cell forKeyPath:@"thumbnail_picture" options:0 context:NULL]; *Object could be deleted. I must remove observers when object is deleted. The database is very large and complex so I definitely don't want to register all cells to receive moc notifications like NSManagedObjectContextObjectsDidChangeNotification. But I can accept to add a cell ivar in object if I have to, even though it goes agains good Modle-View-Controller design pattern. The problem: How can I correctly remove the observer(cell) for all the registered key paths from an object when it is deleted? In fact, it is a big problem that can be divided into two small problems: * *Where is the best place to put the observer removing code? *How do I determine which key paths to unregister? I can't query its properties after an object is deleted — it will cause unfulfillable faults, so I can't write code like this: if (object.thumbnail_pic_url) [object removeObserver:cell forKeyPath:@"thumbnail_picture"]; and I can't either blindly remove observer for unregistered key path — exceptions(Cannot remove an observer for the key path "thumbnail_picture" from because it is not registered as an observer.) will be thrown up. A: an0, There is an NSManagedObject method just for doing deletion timed functions: -prepareForDeletion. Its documentation claims: "You can implement this method to perform any operations required before the object is deleted, such as custom propagation before relationships are torn down, or reconfiguration of objects using key-value observing." You could also look at using: -willTurnIntoFault and -didTurnIntoFault. But I think you'll be happier using -prepareForDeletion. Andrew P.S. This method is documented in the class reference. I respectfully suggest that you save time by reading the documentation. A: The main problem implementing KVO here is that you don't know when the object is getting deleted , at least not outside the NSManagedObject subclass, What you could really do is create a generic delegate on a subclass of NSManagedObject and override its didChangeValueForKey: method // DataObservingManagedObject.h #import <Foundation/Foundation.h> #import <MMRecord/MMRecord.h> @protocol DataObservingDelegate <NSObject> -(void)valueChangedForKey:(NSString*)key andValue:(id)value; @end @interface DataObservingManagedObject : NSManagedObject @property(nonatomic,weak)id<UserStatusDelegate> changeDelegate; @end //DateObservingManagedObject.m #import "DateObservingManagedObject.h" @implementation DateObservingManagedObject @synthesize changeDelegate=_changeDelegate; -(void)didChangeValueForKey:(NSString *)key{ [self.changeDelegate valueChangedForKey:key andValue:[self valueForKey:key]]; } @end A: I believe the mistake is in step 1. Cells should be designed to display different objects. Cells are simply views with labels that can show anything. Tables are optimised to reuse the same cells for different data objects. In your VC create a configureCellWithEvent, configureCellWithVenue methods etc. then you can dequeue a cell of generic identifier and pass it to these methods. Then you likely won’t even have the issue of when to add remove observers because cells shouldn't have object observers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Asterisk AGI: How to get or set the value of a global variable? I'm using Asterisk 1.8 with PHP for AGI scripting. EDIT: I'm struggling with setting and obtaining the values of global variables from within an AGI PHP script. I can set channel variables but not global variables. Using PHPAGI lib. Tried: Set({$varname}={$value},g) Set({$varname}=\"{$value}\",g) Set(GLOBAL({$varname})={$value}) That does not seem to work at all, when getting the value from within the dial plan, it is empty. Does anyone have a working example of setting and getting global variables in an AGI script? A: I found a workaround to make it work. First, the global variable must not be declared in the dial plan under the [globals] section. And, it seems you cannot set a global variable from within an AGI script. However, you can set a channel variable (local to the current channel). So to set a global variable from an AGI script, you first set the value to a channel variable and when you return from the script into the dial plan, you retrieve the value of the channel variable and assign it to a global variable. Basically, it seems you can only assign global variables from within the dial plan, not from within an AGI script. sample code: //in dial plan exten => _XXXX,n,AGI(myagiscript.php) exten => _XXXX,n,Set(GLOBAL(someGlobalVariable)=${myLocalVar}) // in myagiscript.php $agi->set_variable("myLocalVar", "value"); A: Asterisk wiki info about AGI says different things about global variables: ... Global variables are not passed to the AGI script in this manner. You must get them using the "get variable" AGI command... and in other part: ...GET VARIABLE: Does not work with global variables. Does not work with some variables that are generated by modules.... For setting global value you can execute: EXEC SetGlobalVar <var_name>=<value> For getting I thing that get_variable should work but there was bug in Asterisk: https://issues.asterisk.org/view.php?id=7609 This bug was in Asterisk 1.2.20, what version of Asterisk do you use?
{ "language": "en", "url": "https://stackoverflow.com/questions/7604257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: CListCtrl: How to maintain scroll position? I have a CListCtrl (report style) where I clear the list and repopulate it at certain times. I'd like to maintain the vertical scroll position when doing this. I see there are a couple methods that look promising: EnsureVisible() GetScrollPos() SetScrollPos() GetScrollInfo() GetTopIndex() Scroll() I'm trying GetScrollPos() and then SetScrollPos() but it doesn't appear to be working. What is the simple correct way to save a scroll position and then later restore it? UPDATE Actually it seems I can get to save the scroll position GetScrollPos() and then SetScrollPos() to restore it, however it literally just seems to set the scroll bar position and does not actually scroll the items of my CListCtrl. UPDATE 2 The Scroll() method seems to correctly scroll the scrollbars and the contents. However it takes a CSize object as it's argument. So the question would be how to translate between the CSize and the output of either GetTopIndex or GetScrollInfo/Pos. A: I've done that in the past. IIRC, the trick consisted in: int topIndex= m_List.GetTopIndex(); RenewContents(); m_List.EnsureVisible(m_List.GetItemCount() - 1); // Scroll down to the bottom m_List.EnsureVisible(topIndex);// scroll back up just enough to show said item on top A: Another way to do it is like so: CRect r; m_lcList.GetItemRect(0, r, LVIR_BOUNDS); int scrollPos = m_lcList.GetTopIndex() * r.Height(); RenewContents(); m_lcList.Scroll(CSize(0, scrollPos));
{ "language": "en", "url": "https://stackoverflow.com/questions/7604267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: RAD (eclipse Based) shows a compiler error even after solving it I am working on a J2EE web application. The servlet I am modifying had a method in it that took two parameters. I added a third parameter to the method and adjusted the method calls accordingly. As each call was adjusted the red markings indicating an error disappeared. All except one. The red markings would not disappear and when they did finally disappear after changing the parameter types, the error won't disappear in my problems view. When trying to call the servlet from the browser the error prevents proper running. The error in the problems view says: "The method writeHeader(PrintWriter, String, boolean) in the type ExportPro__Servlet is not applicable for the arguments (PrintWriter, String) This what the call to the method is: writeHeader(out, status, booleanVariable); This is the method header: public void writeHeader(PrintWriter out, String status, boolean bV) When I ctrl+click on the call it takes me to the method, so we know its calling the write method. There are no other similar methods in the class. Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/7604269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I retain my private level variable in my ASP.NET control after an async postback? I am using C# and .NET 4.0. I have an ascx control which contains two drop down lists. ddList1 is parent to ddList2 (think Car Make - Car Model). I have a constructor that populates a private variable in this control with a reference back to the original invoking object. When I do an async postback on the control (caused by changing ddList1), the private variable which was populated originally by the constructor is now null. How do I retain the reference to the original calling object? Thanks! A: Store the value of the variable in your ViewState, and retrieve it during the postback. The Web is stateless: you have to work around that fact, even in WebForms. A: Use any of the state management techniques...like sessions or hiddenfields for storing the reference between postbacks
{ "language": "en", "url": "https://stackoverflow.com/questions/7604271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to select some urls with BeautifulSoup? I want to scrape the following information except the last row and "class="Region" row: ... <td>7</td> <td bgcolor="" align="left" style=" width:496px"><a class="xnternal" href="http://www.whitecase.com">White and Case</a></td> <td bgcolor="" align="left">New York</td> <td bgcolor="" align="left" class="Region">N/A</td> <td bgcolor="" align="left">1,863</td> <td bgcolor="" align="left">565</td> <td bgcolor="" align="left">1,133</td> <td bgcolor="" align="left">$160,000</td> <td bgcolor="" align="center"><a class="xnternal" href="/nlj250/firmDetail/7"> View Profile </a></td></tr><tr class="small" bgcolor="#FFFFFF"> ... I tested with this handler: class TestUrlOpen(webapp.RequestHandler): def get(self): soup = BeautifulSoup(urllib.urlopen("http://www.ilrg.com/nlj250/")) link_list = [] for a in soup.findAll('a',href=True): link_list.append(a["href"]) self.response.out.write("""<p>link_list: %s</p>""" % link_list) This works but it also get the "View Profile" link which I don't want: link_list: [u'http://www.ilrg.com/', u'http://www.ilrg.com/', u'http://www.ilrg.com/nations/', u'http://www.ilrg.com/gov.html', ......] I can easily remove the "u'http://www.ilrg.com/'" after scraping the site but it would be nice to have a list without it. What is the best way to do this? Thanks. A: I think this may be what you are looking for. The attrs argument can be helpful for isolating the sections you want. from BeautifulSoup import BeautifulSoup import urllib soup = BeautifulSoup(urllib.urlopen("http://www.ilrg.com/nlj250/")) rows = soup.findAll(name='tr',attrs={'class':'small'}) for row in rows: number = row.find('td').text tds = row.findAll(name='td',attrs={'align':'left'}) link = tds[0].find('a')['href'] firm = tds[0].text office = tds[1].text attorneys = tds[3].text partners = tds[4].text associates = tds[5].text salary = tds[6].text print number, firm, office, attorneys, partners, associates, salary A: I would get each tr, in the table with the class=listings. Your search is obviously too broad for the information you want. Because HTML has a structure you can easily get just the table data. This is easier in the long run then getting all hrefs and filtering the ones that you don't want out. BeautifulSoup has plent of documentation on how to do this. http://www.crummy.com/software/BeautifulSoup/documentation.html not exact code: for tr in soup.findAll('tr'): data_list = tr.children() data_list[0].content # 7 data_list[1].content # New York data_list[2].content # Region <-- ignore this # etc
{ "language": "en", "url": "https://stackoverflow.com/questions/7604272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: simple jQuery "toggler" plugin - works like a charm, except in Opera I've written this jQuery plugin, but it just won't work in Opera (I'm using 11.51). It works fine in all other browsers, even IE7, so this has really got me stumped. Any help much appreciated, thanks. (function($) { $.fn.toggleBox = function(options) { var opts = $.extend({}, $.fn.toggleBox.defaults, options); return this.each(function() { var $this = $(this); var target; $this.click(function(ev) { ev.preventDefault(); $(target).stop(1,1).slideToggle(opts.speed, 'swing', function() { $(target).animate({'opacity': 1}); }); }).hover( function(){ $(target).stop(1,1).animate({'opacity': 0.4}); }, function(){ $(target).stop(1,1).animate({'opacity': 1}); } ) .each(function(){ $(this).css('cursor', 'pointer'); target = $(this).attr('data-toggler'); target = $('[data-toggle-content=' + target + ']'); if ( $(this).attr('data-toggler-state') == 'open') { $(target).show(); } else { $(target).hide(); } }); }); }; // Default settings for the plugin $.fn.toggleBox.defaults = { speed: 500 }; })(jQuery); $('[data-toggler]').toggleBox(); // end toggler Following is the html markup used for a toggler and it's content: <div data-toggler="togglerID"> Click to toggle content</div> <div data-toggle-content="togglerID"> Toggler content </div> =========== EDIT =========== Well that figures... as soon as I post the question, I figure it out. I needed to change the last line where I call the plugin to run at domReady: jQuery(function ($) { $('[data-toggler]').toggleBox(); }); Works fine in Opera now. A: I guess you came across the bug that made me break the BBC iPlayer, namely that a dynamically inserted script in Opera doesn't get to "see" content after the script that added it? (Unless you use jQuery's $(document).ready() or similar).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to expand UIWebView on click I'm working on an Ad SDK for iOS and I have a narrow banner-size UIWebView that displays a complex HTML that I receive from an ad server. I don't know anything about structure of that HTML (i.e. it may change). At some point user taps on that UIWebView, which causes the content of that ad to become full-screen, so I need to expand my UIWebView and show it in the modal view (via presentModalViewController). Is there a way to either take my existing UIWebView and reattach it to my new modal view while keeping its state (whatever user clicked on)? Or alternatively how can I simulate touch on UIWebView, since I could create new UIWebView in my modal view and load the same HTML, but then I need to re-create its state after initial tap by somehow sending a tap event programmatically. A: Use UITapGestureRecognizer, make that WebView full-screen and move to the front layer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to go about preferences I have a list view displaying data like: 2010 Singapore 2009 India 2011 Sweden 2010 Germany Now when I click menu button, I have two items in it which let me sort this list according to year or by country. The sorting is working fine. What I want to do now is, when I click any of two option items it should along with sorting the list accordingly should now also save the way how it was sorted in preferences. So the next time when I open the app, it should be sorted exactly as stored in preferences. What is the approach I should follow here. I mean how can I store that value how I sorted last time in my preferences. I tried looking into some tutorials but didnt get the idea completely Actually I just want to save last sorting order in the preferences. Next time when user starts the application, the countries list should be sorted in the same way as it was sorted when user closed app last time. @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, SORT_BY_YEAR, Menu.NONE, "Sort by Year") .setAlphabeticShortcut('y'); menu.add(Menu.NONE, SORT_BY_COUNTRY, Menu.NONE, "Sort by Country") .setAlphabeticShortcut('c'); return(super.onCreateOptionsMenu(menu)); } /* (non-Javadoc) * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem) */ @Override public boolean onOptionsItemSelected(MenuItem item) { String[] from = new String[] { "year", "country" }; int[] to = new int[] { R.id.year, R.id.country }; switch (item.getItemId()) { case SORT_BY_YEAR: Cursor cYear = getContentResolver().query(CONTENT_URI, null, null, null, "year"); SimpleCursorAdapter scaYear = new SimpleCursorAdapter(this, R.layout.country_row,cYear, from, to); setListAdapter(scaYear); sortOrder = "year"; return(true); case SORT_BY_COUNTRY: Cursor cCountry = getContentResolver().query(CONTENT_URI, null, null, null, "country"); SimpleCursorAdapter scaCountry = new SimpleCursorAdapter(this, R.layout.country_row,cCountry, from, to); setListAdapter(scaCountry); sortOrder = "country"; return(true); } return(super.onOptionsItemSelected(item)); } A: Have you looked into using SharedPreferences to store the preferred sort order? When the user selects a sort order you store that in a shared preference, for example SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); prefs.edit().putInt("sort_pref", 1).commit(); // 1 = sort on year Next time when you open the app you can read the preference value SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); int sort = prefs.getInt("sort_pref", -1); // -1 will be the result if no preference was set before if(sort == 1) ///sort on year else if (sort == 2) ///sort on country A: look at getSharedPreferences() in your Activity to get hold of a copy of SharedPreferences. You can set values into it onClose() and then pick it back up again when your app restarts in onCreate()
{ "language": "en", "url": "https://stackoverflow.com/questions/7604279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Validation plugin duplicating errors on submit when invalid Ive tried for hours to figure this problem out. Im using the jQuery validation plugin (v1.7) on my form. The validation appears to be working correctly except for one problem. If a form field is invalid, itll show its error upon clicking submit. And if I click submit again, the original error stays and it adds another error right below it. Effectively, I clicked submit 10 times and I had the same error message for that field 10 times on the page. Its like the script isnt working onkeyup or like it only monitors validation on submit. My goal would be to have onkeyup check validation rules. Anyways, I appreciate any help and heres my current code; <script type="text/javascript" src="scripts/jquery/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="scripts/jquery/jquery-ui-1.8.9.custom.min.js"></script> <script type="text/javascript" src="scripts/jquery/jquery.validate.min-1.7.js" charset="ISO-8859-1" /></script> <script type="text/javascript" src="scripts/jquery/jquery.validate.additional-methods-1.7.js" /></script> <script type="text/javascript"> $(function() { $("#jerseyForm").validate({ debug: true, rules: { name: "required", address: "required", city: "required", state: "required", zip: { required: true, digits: true }, email: { required: true, email: true, onkeyup: true }, phone: { required: true, phoneUS: true, onkeyup: true, } }, messages: { name: "Please enter your name", address: "Please enter your address", city: "Please enter your city", state: "Please enter your state", zip: "Please enter your zip code", email: "Please enter a valid email address", phone: "Please enter a valid phone number" } }); }); </script> <form id="jerseyForm" action="<?php echo $postURL;?>" method="post"> <input type="hidden" name="subAction" value="send" /> <div id="customerDetails"> <label for="name"><span class="required">*</span> Name</label> <input type="text" id="name" name="name" size="25" /> <label for="address"><span class="required">*</span> Address</label> <input type="text" id="address" name="address" value="" size="25" /> <br style="clear:both;" /> <div style="float:left;"> <label for="city"><span class="required">*</span> City</label> <input type="text" id="city" name="city" value="" size="15" /> </div> <div style="float:left; margin-left:5px;"> <label for="state"><span class="required">*</span> State</label> <input type="text" id="state" name="state" value="" size="5" /> </div> <div style="float:left; margin-left:5px;"> <label for="zip"><span class="required">*</span> Zip</label> <input type="text" id="zip" name="zip" value="" size="7" /> </div> <br style="clear:both;" /> <label for="phone"><span class="required">*</span> Phone</label> <input type="text" id="phone" name="phone" value="" size="25" /> <label for="email"><span class="required">*</span> Email</label> <input type="text" id="email" name="email" value="" size="25" /> </div> </div> <br style="clear:both;" /> </div> <p><input type="submit" class="submit" name="send" value="Place Order" /> <input type="reset" class="reset" value="Start Over" /></p> </form> A: I've tested your exact code is Chrome, FireFox 3.x and MSIE 6 (via IETester). I used jQuery 1.6.2 and jQuery Validate 1.8.1, but I didn't get the error you're seeing. However I did get this one error related to the parsing of your JSON (in IE6 only): phone: { required: true, phoneUS: true, onkeyup: true, // <--- this may be the culprit } I know I've seen this issue happen for multiple coworkers. I think the extra comma might be a problem on some earlier versions of the plug-in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiline shebang in OCaml? In short, I'd like to abstract this shebang so I can literally copy and paste it into other .ML files without having to specify the filename each time: #!/usr/bin/env ocamlscript -o hello print_endline "Hello World!" I realize I could just drop the -o hello bit, but I'd like all the binaries to have UNIX names (hello), instead of Windows names (hello.ml.exe). You need a complex shebang to do this. A Clojure example that has the desired behavior: ":";exec clj -m `basename $0 .clj` $0 ${1+"$@"} ":";exit Clojure is Java-based, which is why clj needs the basename of the file (something, not something.clj). In order to get the basename, you need a multiline shebang, because a single line shebang can only handle a single, simple, static command line argument. In order to do multiline shebangs, you need a syntax which simultaneously: * *Sends shell commands to the shell *Hides the shell commands from the main language Does anyone know of OCaml trickery to do this? I've tried the following with no success: (* exec ocamlscript -o `basename $0 .ml` $0 ${1+"$@"} exit *) let rec main = print_endline "Hello World!" A: What you're looking for is a shell and Objective Caml polyglot (where the shell part invokes an ocaml interpreter to perform the real work). Here's a relatively simple one. Adapt to use ocamlscript if necessary, though I don't see the point. #!/bin/sh "true" = let exec _ _ _ = "-*-ocaml-*- vim:set syntax=ocaml: " in exec "ocaml" "$0" "$@" ;; (* OCaml code proper starts here *) print_endline "hello" A: After some trials, I found this shebang: #!/bin/sh "true" = let x' = "" in (*' sh script here *) x' It is sort of an improvement of Gilles’ proposal, as it permits to write a full shell script inside the OCaml comment, without being bothered at all with syntax incompatibilities. The script must terminate (eg. with exec or exit) without reaching the end of the comment, otherwise a syntax error will occur. This can be fixed easily, but it is not very useful regarding the intended use of such a trick. Here is a variant that entails zero runtime overhead on the OCaml side, but declares a new type name (choose it arbitrarily complicated if this is bothering): #!/bin/sh type int' (*' >&- 2>&- sh script here *) For example, here is a script that executes the OCaml code with modules Str and Unix, and can also compile it when passed the parameter --compile: #!/bin/sh type int' (*' >&- 2>&- if [ "$1" = "--compile" ]; then name="${0%.ml}" ocamlopt -pp 'sed "1s/^#\!.*//"' \ str.cmxa unix.cmxa "$name.ml" -o "$name" \ || exit rm "$name".{cm*,o} exit else exec ocaml str.cma unix.cma "$0" "$@" fi *) A: I do not think that ocamlscript supports this. It may be worth submitting a feature request to the author to allow customization of the compiled binary's extension without specifying the full output basename.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Running DOS command or batch file in tcl script in Windows 7 with ActiveTcl 8.5 The following is the tcl code. #!/bin/sh # \ exec tclsh "$0" ${1+"$@"} package require Expect package require log source [file join [info library] init.tcl] set exp::winnt_debug 1 log::lvChannel debug stdout log::log debug "debug msg ON\r" set env(TERM) dumb array set OPTS { host "" user "" passwd "" login telnet prompt "(%|#|>|\\$) $" ls "/bin/ls -A1" } set xlpad "yahoo.com" exec [auto_execok dir] while {1} { spawn ping $xlpad set loss 0 set replya 0 for { set pingc 0 } { $pingc < 3 } { incr pingc 1} { expect { "timed out" { incr loss 1 puts "intercepted time out message: $loss\n" } "Reply" { incr replya 1 } } if { $replya > 2 } { break } } break } return I got the following messages: couldn't execute "C:\Windows\System32\cmd.exe \c dir": no such file or directory while executing "exec [auto_execok dir]" (file "mytst.tcl" line 35) But the ping works ok. A: auto_execok returns a list, which is passed to exec as a single argument. You need to expand the list: exec {*}[auto_execok dir] example: % file mkdir tmp % cd tmp % close [open test w] % exec [auto_execok dir] couldn't execute "C:\WINNT\system32\cmd.exe \c dir": no such file or directory % exec {*}[auto_execok dir] Volume in drive D is Data Volume Serial Number is .... Directory of d:\glennj\tmp 2011-09-30 10:08 AM <DIR> . 2011-09-30 10:08 AM <DIR> .. 2011-09-30 10:08 AM 0 test 1 File(s) 0 bytes 2 Dir(s) 77,613,654,016 bytes free
{ "language": "en", "url": "https://stackoverflow.com/questions/7604286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Save NSView representation ignores transparency I am trying to change the icon of a file to a representation of an NSView. I am using the following code to do so. [mainDisplay lockFocus]; NSBitmapImageRep *rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[mainDisplay bounds]]; [mainDisplay unlockFocus]; NSImage *image = [[NSImage alloc] initWithData:[rep representationUsingType:NSTIFFFileType properties:nil]]; [[NSWorkspace sharedWorkspace] setIcon:image forFile:[savePanel filename] options:0]; This works. It changes the icon exactly how I would like, except for the fact that any transparency to white. How can I keep the transparency? I know it works for Photoshop, but is is possible using Apple's frameworks? A: You cannot get an image with transparency this way, because [NSBitmapImageRep initWithFocusedViewRect:] gets a piece of rendered image from the window server, where the view's image already flattened to an image with other underlaying views and the window's background. What you need is it to allocate a new clean NSBitmapImageRep with appropriate format and render the view's content on it: NSBitmapImageRep* rep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil pixelsWide:[mainDisplay bounds].size.width pixelsHigh:[mainDisplay bounds].size.height bitsPerSample:8 samplesPerPixel:4 hasAlpha:YES isPlanar:NO colorSpaceName:NSDeviceRGBColorSpace bytesPerRow:[mainDisplay bounds].size.width * 4 bitsPerPixel:32]; [mainDisplay cacheDisplayInRect:[mainDisplay bounds] toBitmapImageRep:rep];
{ "language": "en", "url": "https://stackoverflow.com/questions/7604287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript function not working based on the version of jquery being included. My code of my Script is given below. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type="text/javascript" src="scripts/prototype.lite.js"></script> <script type="text/javascript" src="scripts/moo.fx.js"></script> <script type="text/javascript" src="scripts/moo.fx.pack.js"></script> <script type="text/javascript"> function init(){ alert('init function called'); var stretchers = document.getElementsByClassName('box'); var toggles = document.getElementsByClassName('tab'); var myAccordion = new fx.Accordion( toggles, stretchers, {opacity: false, height: true, duration: 600} ); //hash functions var found = false; toggles.each(function(h3, i){ var div = Element.find(h3, 'nextSibling'); if (window.location.href.indexOf(h3.title) > 0) { myAccordion.showThisHideOpen(div); found = true; } }); if (!found) myAccordion.showThisHideOpen(stretchers[0]); } </script> <script type='text/javascript' src='javascripts/jquery-1.3.2.min.js'></script> <script type='text/javascript'> var verticalAdjuster = .30; var backgroundSpeed = .15; var childrenSpeed = .05; var dogSpeed = -.03; var ground = -.00; jQuery(document).ready( function(){ alert('other function called'); $("#painting").mousemove( function(e){ var x = 750 - (e.pageX - this.offsetLeft); var y = 435 - (e.pageY - this.offsetTop); //$("#city").css("background-position", (backgroundSpeed*x) + " " + (backgroundSpeed*verticalAdjuster*y)); $("#city").css("top", (backgroundSpeed*verticalAdjuster*y)); $("#city").css("left", (backgroundSpeed*x)); //$("#city").css("right", (backgroundSpeed*x*(-10)) ); $("#tree").css("top", (childrenSpeed*verticalAdjuster*y) + "px"); $("#tree").css("left", (childrenSpeed*x) + "px"); $("#boyAndBitch").css("top", (dogSpeed*verticalAdjuster*y) + "px"); $("#boyAndBitch").css("left", (dogSpeed*x) + "px"); }); }); </script> The issue is that only the later script is running right now. But if I remove the <script type='text/javascript' src='javascripts/jquery-1.3.2.min.js'></script> from where it is, and place it on the top, then only the init() function works and not the later. Can you please explain me how can I solve this issue. Regards Zeeshan A: You're including jQuery up at the very top, then Prototype right after that, then jQuery again at the bottom. The higher of the two script blocks appears to exclusively use Prototype, the lower of the two, exclusively jQuery. Each of those includes is going to re-define $. By moving the initially-lower jQuery 1.3.2 inclusion to "the top", I assume you're placing it above your Prototype script tag. So, down in your jQuery(document).ready callback, the $ has been hijacked by Prototype and you get errors because your code is written expecting that $ is jQuery. What you should do is: * *Only use one version of jQuery on this page. Pick one and go with it. *Call jQuery.noConflict(). Given the ordering you have now, things may work fine without it, but it's a good idea anyway, and will keep things from breaking if you change the order you include your libraries in. *Change the beginning of your jQuery code to: jQuery(document).ready(function($) { Adding that $ as a parameter to the ready callback will let you use the $ shortcut within the callback. Or, if you control all this code, just stick with either Prototype or jQuery, whichever you prefer. A: It seems odd that you are both linking to a google jquery version and local copy. I would recommend only linking to one. Also, you're going to want to do all of your imports before you actually write any scripts in the HTML file, unless you are using a noConflict() jQuery call. In that case you should use noConflict() before you import Prototype. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script type='text/javascript' src='javascripts/jquery-1.3.2.min.js'></script> These are different versions of jquery. Because the second call is the last one, only that version is being used. I would say that removing that call completely would fix your problem. A: If it is a requirement to use different versions of jQuery and also other javascript frameworks then it is possible using no-conflict mode to distinguish between them and also different the jQuery versions <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <script> jq162 = jQuery.noConflict(true); </script> <script type='text/javascript' src='javascripts/jquery-1.3.2.min.js'></script> <script> jq132 = jQuery.noConflict(true); </script> Instead of $("#city").css("top", (backgroundSpeed*verticalAdjuster*y)); You should use jq132("#city").css("top", (backgroundSpeed*verticalAdjuster*y));
{ "language": "en", "url": "https://stackoverflow.com/questions/7604289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverlight DataContext Databinding behavior I'll start off with a stripped-down/sanitized version of my code: Model: class DataObj : INotifyPropertyChanged { // these actually call OnPropertyChanged, and have associated private variables public string Name { get; set; } public int Age { get; set; } } class DataContextObj : INotifyPropertyChanged { public List<DataObj> DataItems { get; set; } } View: <StackPanel x:Name="MyPanel"> <TextBlock Text="{Binding Path=DataItems[0].Name}" /> <TextBlock Text="{Binding Path=DataItems[0].Age}" /> </StackPanel> View code-behind: //in the constructor MyPanel.DataContext = new DataContextObj(); Now, my question is, if the DataItems list is initialized but empty, what is the expected behavior when something tries to bind to, say, the first element in the list? My understanding is that it just ignores the binding; is that true? A: Yes it will ignore the binding. If subsequently an item is added to the empty list the text blocks will not update since the binding expression associated with them will not know that the change happened. The appropriate solution is to use: public class DataContextObj { public ObservableCollection<DataObj> DataItems {get; private set; } } Additions to the collection will notify "Item[]" has changed which will allow the binding expression to re-evaluate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: org.hibernate.MappingException: Unknown entity: java.lang.Long I am trying to create a named-native-query that returns a Long. Here is my orm.xml file (simplified as much as possible) <?xml version="1.0" encoding="UTF-8"?> <entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd" version="2.0"> <named-native-query name="getCaseNumberByCommId" result-class="java.lang.Long"> <query>SELECT case_id FROM communications WHERE comm_id =(?1)</query> </named-native-query> </entity-mappings> this is the error I get: ERROR - org.hibernate.impl.SessionFactoryImpl - Error in named query: getCaseNumberByCommId [coral:launch] org.hibernate.MappingException: Unknown entity: java.lang.Long I've also tried just specifying "Long" <named-native-query name="getCaseNumberByCommId" result-class="Long"> <query>SELECT case_id FROM communications WHERE comm_id =(?1)</query> </named-native-query> and strangely get this error: Caused by: org.hibernate.AnnotationException: Unable to find entity-class: Long ... Caused by: java.lang.ClassNotFoundException: Long Java can't find Long in java.lang? Thank you for any clues edit: I tried removing the 'result-class' annotation : <named-native-query name="getCaseNumberByCommId" > <query>SELECT case_id FROM communications WHERE comm_id =(?1)</query> </named-native-query> and get this error: nested exception is org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet supported Update* I never did find a way to do this, but since the database had a uniqueness constraint on comm_id, I was able to just return a mapped pojo object instead of a count. e.g. <named-native-query name="getByCommId" result-class="com.foo.model.Communication"> <query>SELECT * FROM communications WHERE comm_id =(?1)</query> </named-native-query> and then pull the desired case_id out of the returned pojo. A: Without looking into this further the result-class should be one of your mapped entities and because Long is not one of your Entities you're receiving the AnnotationException. Try removing the result-class from the mapping as it is only used for building queries that return Entity Objects. Edit: In regard to: org.hibernate.cfg.NotYetImplementedException: Pure native scalar queries are not yet supported: After a quick dig around I found this: https://hibernate.atlassian.net/browse/ANN-661 Where I read: Workaround is to do such queries using Session.createSQLQuery() or straight JDBC. There are a couple of examples for such queries here: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/querysql.html#d0e17378 i.e sess.createSQLQuery("SELECT * FROM CATS").list(); sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").list(); or further down in Example 18.4 http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/querysql.html#querysql-namedqueries <sql-query name="mySqlQuery"> <return-scalar column="name" type="string"/> <return-scalar column="age" type="long"/> SELECT p.NAME AS name, p.AGE AS age, FROM PERSON p WHERE p.NAME LIKE 'Hiber%' </sql-query> A: <named-native-query name="getCaseNumberByCommId"> <query>SELECT case_id FROM communications WHERE comm_id =(?1)</query> </named-native-query> something like this works for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Form Alignment input and drop downs How could I align my input boxes so that the first one is aligned with the label and the other two is aligned underneath the top input box. Why is my domain and dropdown menu not aligning? CSS: #newwebsiteForm{ padding:10px; margin:10px 0; width:480px; position: relative } #newwebsiteForm label{ display:block; float:left; clear:both; margin:0 15px 0 25px; width:240px; border:1px solid green; height:15px } #newwebsiteForm input{ display:block; float:left; width:240px; height:15px; } #newwebsiteForm .radioButton { width:15px; height:15px; } #newwebsiteForm .radioText { display:block; width:30px; height:20px; float:left; font-size:12px; border:1px solid red; } #newwebsiteForm #color1,#color2,#color3,#fav1,#fav2,#fav3{ display:block; float:left; margin-left:25px; background-color:red; } #newwebsiteForm textarea{ display:block; float:left; } input#domain,#newwebsiteForm select, .form-field{float:right;width:200px;margin-top:-15px} .form-field{width:220px} HTML: <div id="newwebsiteSection"> <form action="#" id="newwebsiteForm" method="get"> <fieldset> <div> <label>Do You Require Hosting?</label> <span class="radioText">Yes</span><input class="radioButton" type="radio" name="Yes" value="Yes"/> <span class="radioText">No</span><input class="radioButton" type="radio" name="No" value="No"/> </div> <div> <label>Do You Require A Domain?</label> <span class="radioText">Yes</span><input class="radioButton" type="radio" name="Yes" value="Yes"/> <span class="radioText">No</span><input class="radioButton" type="radio" name="No" value="No"/> </div> <label>Do You Have A Logo?</label> <span class="radioText">Yes</span><input class="radioButton" type="radio" name="Yes" value="Yes"/> <span class="radioText">No</span><input class="radioButton" type="radio" name="No" value="No"/> <label for="domain">What is your Domain?</label> <input type="url" id="domain" value="http://example.com"/> <label for="newwebsiteType">Type of site Required?</label> <select name="newwebsiteType" id="newwebsiteType"> <option value="shoppingCart">Shopping Cart</option> <option value="CMS">Content Management System</option> <option value="static">Static Website</option> <option value="otherDevelopment">Other Development</option> </select> <label>Do You Require A Design?</label> <span class="radioText">Yes</span><input class="radioButton" type="radio" name="Yes" value="Yes"/> <span class="radioText">No</span><input class="radioButton" type="radio" name="No" value="No"/> <div> <label>Three Favorite colors?</label> <div class="form-field"> <input id="color1" value=""/> <input id="color2" value=""/> <input id="color3" value=""/> </div> </div> <div> <label>What are your favorite websites?</label> <div class="form-field"> <input type="text" id="fav1" value=""/> <input type="text" id="fav2" value=""/> <input type="text" id="fav3" value=""/> </div> </div> <label for="comments">Comments?</label> <textarea name="comments" id="comments"></textarea> <input type="submit" name="submit" value="Send Quote Request"/> </fieldset> </form> </div> A: Despite all the flack they've gotten lately, I feel like this is one of the few examples of where a table is actually not only useful, but the most correct solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: New google calendar, "pop-out" events, if they don't fit in the defined area Take a look at what the new google calendar does when there are too many events to fit in the defined square. You can click the +2 more link (or whatever it may say), and the square pops out a bit... and displays everything. Does anyone know of a JS/JQuery library that has this functionality? Example: http://i.imgur.com/86tom.png Thanks! A: To get the pop out box, you could use a jQueryUI dialog and position it where you want it. Re-style it to match your UI, of course. If you are also hoping to get the logic to figure out how many items are hidden, and display a "+n more..." message there, that seems like it could be a little specific for a plugin, but maybe not. Here's one simple implementation. http://jsfiddle.net/gilly3/sxGSr/ There's a bit of hard-coding that could be made more dynamic, but this may give you a start.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to compare two text files, and create a third based on information I have two text files, master.txt and 926.txt. If there is a line in 926.txt that is not in master.txt, I want to write to a new file, notinbook.txt. I wrote the best thing I could think of, but given that I'm a terrible/newbie programmer it failed. Here's what I have g = File.new("notinbook.txt", "w") File.open("926.txt", "r") do |f| while (line = f.gets) x = line.chomp if File.open("master.txt","w") do |h| end while (line = h.gets) if line.chomp != x puts line end end end end end g.close Of course, it fails. Thanks! A: This should work: f1 = IO.readlines("926.txt").map(&:chomp) f2 = IO.readlines("master.txt").map(&:chomp) File.open("notinbook.txt","w"){ |f| f.write((f1-f2).join("\n")) } This was my test: 926.txt line1 line2 line3 line4 line5 master.txt line1 line2 line4 notinbook.txt line3 line5 A: You can do something like this: master_lines = [] File.open("notinbook.txt","w") do |result| File.open("master.txt","r") do |master| master.each_line do |line| master_lines << line.chomp end end File.open("926.txt","r") do |query| query.each_line do |line| if !master_lines.include? line.chomp result.puts line.chomp end end end end A: Use : http://raa.ruby-lang.org/project/compare/ OR %x(diff file1 file2) OR http://github.com/myobie/htmldiff/ A: Hope this helps dir = File.dirname(__FILE__) notinbook = "#{dir}/notinbook.txt" master = "#{dir}/master.txt" f926 = "#{dir}/926.txt" def file_into_ary(file) ary = [] File.open(file).each{ |line| ary << line } return ary end def write_difference(file, diff) File.open(file, 'w') do |file| diff.each do |line| file.write(line) end end end diff = file_into_ary(f926) - file_into_ary(master) write_difference(notinbook, diff) unless diff.empty?
{ "language": "en", "url": "https://stackoverflow.com/questions/7604302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Calling click from keydown, but getting the correct checkbox checked property This isn't a jQuery only question as it has to do with events and order of operation. Consider the following code, which is based on jQuery multiSelect plugin (please post citation if you can find it): Fiddle with it here var debug = $('#debug'); var updateLog = function (msg){ debug.prepend(msg + '\n'); }; var title = $('#title').focus(); var container = $('#container'); title.keydown(function(e){ // up or down arrows if (e.keyCode == 40 || e.keyCode == 38) { var labels = container.find('label'); var idx_old = labels.index(labels.filter('.hover')); var idx_new = -1; if (idx_old < 0) { container.find('label:first').addClass('hover'); } else if (e.keyCode == 40 && idx_old < labels.length - 1) { idx_new = idx_old + 1; } else if (e.keyCode == 38 && idx_old > 0) { idx_new = idx_old - 1; } if (idx_new >= 0) { jQuery(labels.get(idx_old)).removeClass('hover'); jQuery(labels.get(idx_new)).addClass('hover'); } return false; } // space/return buttons if (e.keyCode == 13 || e.keyCode == 32) { var input_obj = container.find('label.hover input:checkbox'); input_obj.click(); return false; } }); // When the input is triggered with mouse container .find('input:checkbox') .click(function(){ var cb = $(this); var class = "checked"; if (cb.prop(class)){ cb.parent('label').addClass(class); } else { cb.parent('label').removeClass(class); } updateLog( cb.closest('label').text().split(/[\s\n]+/).join(' ') + ': ' + this.checked + ' , ' + cb.prop(class)); title.focus(); }) ; Notice the difference in the checkbox value for when you click directly on the checkbox, versus when you select the checkbox with the space/enter key. I believe this is because it's calling click during the keydown event, so the value of the checkbox is not yet changed; whereas if you actually click the input, the mouseup event occurs before the click (?), so the setting is applied. The multiselect plugin does not call the click event, it has almost duplicate code. I'm curious if it would be better to pass a parameter to the click event (or use a global) to detect if it issued by the keyboard or mouse, or if it is better to just do what the plugin did and have the code inside the keydown function. Obviously, if the log were after the click() runs, the keydown would return trues, but there are things that happen inside of click that are based on the input's checked status. A: Changed it to use the change event instead of the click event for the checkboxes http://jsfiddle.net/QJsPc/4/
{ "language": "en", "url": "https://stackoverflow.com/questions/7604309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MYSQL search database for similar results Essentially what I want to do is search a number of MYSQL databases and return results where a certain field is more than 50% similar to another record in the databases. What am I trying to achieve? I have a number of writers who add content to a network of websites that I own, I need a tool that will tell me if any of the pages they have written are too similar to any of the pages currently published on the network. This could run on post/update or as a cron... either way would work for me. I've tried making something with php, drawing the records from the database and using the function similar_text(), which gives a % difference between two strings - this however is not a workable solution as you have to compare every entry against every other entry & I worked out with microtime that it would take around 80 hours to completely search all of the entries! Wondering if it's even possible!? Thanks! A: You are probably looking for is SOUNDEX. It is the only sound based search in mysql. If you have A LOT of data to compare, you're probably going to need to pregenerate the soundex and compare the soundex columns or use it live like this: SELECT * FROM data AS t1 LEFT JOIN data AS t2 ON SOUNDEX(t1.fieldtoanalyse) = SOUNDEX(t2.fieldtoanalyse) Note that you can also use the t1.fieldtoanalyze SOUNDS LIKE t2.fieldtoanalyze syntax. Finaly, you can save the SOUNDEX to a column, just create a column and: UPDATE data SET fieldsoundex = SOUNDEX(fieldtoanalyze) and then compare live with pregenerated values More on Soundex Soundex is a function that analyzes the composition of a word but in a very crude way. It is very useful for comparisons of "Color" vs "Colour" and "Armor" vs "Armour" but can also sometimes dish out weird results with long words because the SOUNDEX of a word is a letter + a 3 number code. There is just so much you can do sadly with these combinations. Note that there is no levenstein or metaphone implementation in mysql... not yet, but probably, levenstein would have been the best for your case. A: Anything is possible. Without knowing your criteria for similar, it's difficult to offer a specific solution. However, my suggestion would be pre-build a similarity table, utilize a function such as similar_text(). Use this as your index table when searching by term. You'll take an initial hit to build such an index. However, you can manage it easier as new records are added. A: Thanks for your answers guys, for anyone looking for a solution to a problem similar to this I used the SOUNDEX function to pull out entries that had a similar title then compared them with the similar_text() function. Not quite a complete database comparison, but near as I could get it!
{ "language": "en", "url": "https://stackoverflow.com/questions/7604314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: window.location.href and JQuery not working in FF 7 I have a login form from which the user enters user name and password. When they click on an image button to submit I do an ajax call to validate the user. The response returns a destination url. Now when I try to do a "window.location.href = url" the process doesnt work in FireFox 7(FF) but It does work on other browsers IE, Chrome... etc Here is my jquery ajax call. var loginSubmit = function () { if ($('#loginForm').data('isSubmitting')) return false; showProgress('Logging in..'); $('#loginErrors').empty(); $('#login-form').fadeTo(100, 0.4); $.ajax({ cache: false, url: '/dispatcher/user/login', data: { 'user': $('#userName').val(), 'pwd': $('#password').val(), 'continuePath': $('#continuePath').length > 0 ? $('#continuePath').val() : '/my-account' }, type: 'POST', success: function (data) { $('#loginForm').data('isSubmitting', true); console.log("Data from Controller: " + data.dest); if (data.dest) { var href = data.dest; window.location.href = href; return false; } else { console.log("DATA DEST FALSE"); $('#loginForm').data('isSubmitting', false); $('#login-form').fadeTo(100, 1); showError('Invalid username/password'); } } }); return false; }; $('#loginForm').submit(loginSubmit); Here is my form. <form id="loginForm" action="#"> <c:if test="${sessionScope['continuePath'] != null}"> <input type="hidden" name="continuePath" value="${sessionScope['continuePath']}"/> </c:if> <div id="progressMessage" style="color: #333; font-weight: bold;"></div> <div id="loginErrors" style="color: red; font-weight: bold"></div> <div id="login-form"> <dl> <dt><label for="userName">Email Address:</label></dt> <dd><input name="user" id="userName" type="text" size="30" maxlength="80"/></dd> <dt><label for="password">Password:</label></dt> <dd><input name="pwd" id="password" type="password" /></dd> </dl> <div class="login_button"> <input type="image" src="/assets/images/user/btn-log-in.gif" alt="Login"/> <br/><br/> <a href="javascript:openPopup('forgotPassword');" class="default">Forgot your password?</a> <!-- <a href="#" rel="#forgotPasswordDialog" class="default">Forgot your password?</a> --> </div> </div> </form> Why is this behavior different in FireFox 7? Can someone suggest a work around that will work in all browsers? Can you sense my frustration? A: What about: window.location = url; //no .href Edit based on comment. Since your url is relative to your site root, the "most correct" part of the window.location object to use would be pathname, as that describes the path relative to the host. window.location.pathname = "/my/relative/path/page.html"; However, any change to the window.location object should trigger the window.location.assign() method and load a new page. If that event is not triggering when you modify the object properties, you can always try calling it directly. window.location.assign(href); Finally, I was checking via the console and unable to reproduce this behavior with FF7. window.location worked with relative paths and full urls. further reference: https://developer.mozilla.org/en/window.location
{ "language": "en", "url": "https://stackoverflow.com/questions/7604315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Converting Pantone colors to RGB? Is it possible to connvert Pantone colors to RGB? From what I can tell you would need a lookup table of some sort. With thousands and thousands of colors I would never want to maintain this myself so does anybody know of an api? We use Java so a Java api would work best. A: Pantone does provide RGB values for the colors in their database, but they maintain that the database (of colors, and of their RGB mappings) is solely their intellectual property. Licensing information may be available at: http://www.pantone.com/pages/partners/become_a_licensee.aspx A: This is generally not possible, as a Pantone color is defined colorimetrically under specific lighting conditions, while RBG colors are at the mercy of the display gamut and calibration. In other words, a specific RGB color will display differently depending on the color space (sRGB, AdobeRGB, etc) and also on the calibration and color gamut of the monitor on which it's displayed. There's a whole industry around monitor calibration tools and software, but only graphics and photography professionals generally use calibration. In short, if you (or anybody) were to come up with a mapping table, it would be valid only for a specific computer and monitor combination, and would be visibly incorrect on many, if not most, other monitors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: display loader gif whilst ajax request fetched We have some code we use, that as the user types it fetches via ajax, the search results. The issue I have is I don't want a submit button, we want the code to display a loader gif (ala FaceBook style pips) whilst the content is fetched. When there is success, hide the loader. Input Element: <input name="suburbs" autocomplete="off" class="suburbsreviews" type="text" id="terms" size="50" onkeyup="getScriptPage('show_results','terms','1')" onblur="if ( this.value == '' ) this.value = this.defaultValue" onfocus="if ( this.value == this.defaultValue ) this.value = ''" <?if ($_GET['terms']){?>value="<?=$_GET['terms'];?>"<?}else{?>value="search"<?}?> /> I thought I would add a loading span that I can position in the input element absolutely using: <span class="loader">Loading...</span> Plus, I thought this code may work by displaying the loading pips: $.loader({ onAjax: true, align: 'center', img: 'images/facebook/pip.gif', mask: true }); It isn't working. Any ideas why? I use the latest jQuery. A: I think you're over complicating things, here's a function I use: function setAreaTree(){ $('#projecthierarchy').html('<center><br><br><br><br><img src="img/loading_eeeeee.gif"></center>'); $.ajax({ url: "sitemanager/sitemanager_ajax.php", data: { action:'getsidebar', pid:pid, aid:curaid, openareas:openareabars }, success: function(data) { $('#projecthierarchy').html(data) } }); } So I just have a single div with id="projecthierarchy". Immediately when the event is fired, the loader gif pops in, then when the ajax call returns successfully, it puts clobers that div with the content. Does that work for you?
{ "language": "en", "url": "https://stackoverflow.com/questions/7604321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Clip matrix for 3D Perspective Projection I am trying to create a simple 3D graphics engine and have found and used the equations I found here: http://en.wikipedia.org/wiki/3D_projection#cite_note-0. (I have calculations for Dx, Dy, Dz and Bx, By) I works, but when I rotate the camera enough lines start flying all over the place and eventually you see the polygons that went off screen start to come back on the opposite side of the screen (you can go here: http://mobile.sheridanc.on.ca/~claassen/3d.html and use the W, A, S and D keys to rotate the camera to see what I'm talking about) I read this discussion: How to convert a 3D point into 2D perspective projection? where he talked about using a clip matrix but Im still a little confused as to how exactly to use one. Also I'm not sure if I am using 'homogeneous coordinates' as described in the discussion. A: This might be a misunderstanding of the terminology. The clip matrix is more appropriately known as a projection matrix. In OpenGL at least, the projection matrix transforms 4D homogeneous coordinates in view coordinate space (VCS) to clipping coordinate space (CCS). Projection from the CCS to normalized device coodinate space (NDCS) requires the perspective division, i.e., dividing each component by the W component. Clipping is correctly done before this step. So, a 'clipping matrix' doesn't remove the need to clip the geometry prior to projection. I hope I've understood you, and this doesn't sound condescending. That said, I think you've obviously got the projection matrix right - it works. I suspect that the vertices passing behind the eye have negative W, which means they should be clipped; but I also suspect they have negative Z, so the division is yielding a positive Z value. If you really want to clip the geometry, rather than discard whole triangles, do a search for 'homogeneous clipping'. If you're not really working in 4D homogeneous space, you might start by looking at 'Sutherland-Hodgman' 3D clipping. A: After multiplying by the perspective projection matrix (aka clip matrix) you end up with a homogenious 4-vector [x,y,z,w]. This is called npc (normalized projection coordinates), and also called clip coordinates. To get the 2D coordinates on the screen you typically use something like xscreen = (x/w) * screen_width yscreen = (y/w) * screen_width For points in front of the camera this gives you what you want. But points behind the camera will have w<0 and you will get values that map to valid screen coordinates even though the point is behind the camera. To avoid this you need to clip. Any vertex that has a w<0 needs to be clipped. A quick thing to try is to just not draw any line if either vertex has w<0. This should fix the strange polygons that show up in your scene. But it will also remove some lines that should be visible. TO completely fix the problem you need to clip all the lines which have one vertex in front of the camera and one vertex behind the camera. Clipping means cutting the line in half and throwing away the half that is behind the camera. The line is "clipped" by a plane that goes through the camera and is parallel to the display screen. The problem is to find the point on the line that corresponds to this plane (i.e. where the line intersects the plane). This will occur at the point on the line where w==0. You can find this point, but then when you try to find the screen coordinates xscreen = (x/w) * screen_width yscreen = (y/w) * screen_width you end up dividing by 0 (w==0). This is the reason for the "near clipping plane". The near clipping plane is also parallel to the display screen but is in front of the camera (between the camera and the scene). The distance between the camera and the near clipping plane is the "near" parameter of the projection matrix: [ near/width ][ 0 ][ 0 ][ 0 ] [ 0 ][ near/height ][ 0 ][ 0 ] [ 0 ][ 0 ][(far+near)/(far-near) ][ 1 ] [ 0 ][ 0 ][-(2*near*far)/(far-near)][ 0 ] To clip to the near plane you have to find the point on the line that intersects the near clipping plane. This is the point where w == near. So if you have a line with vertices v1,v2 where v1 = [x1, y1, z1, w1] v2 = [x2, y2, z2, w2] you need to check if each vertex is in front of or behind the near clip plane. V1 is in front if w1 >= near and behind if w1 < near. If v1 and v2 are both in front then draw the line. If v1 and v2 are both behind then don't draw the line. If v1 is in front and v2 is behind then you need to find vc where the line intersects the near clip plane: n = (w1 - near) / (w1 - w2) xc = (n * x1) + ((1-n) * x2) yc = (n * y1) + ((1-n) * y2) zc = (n * z1) + ((1-n) * z2) wc = near vc = [xc, yc, zc, wc] Now draw the line between v1 and vc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Is it possible to invite exactly one friend by Facebook API Without showing the multiuser invite popup. For example I know the uid and that he/she is not using the app. So I want to offer a button, to invite this person. A: You can set the to parameter of the request dialog to specify that it should go to a single user. You can set frictionlessRequests : true in FB.init so that the first time it will prompt users to allow you to send requests without prompting the user each time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Switch from dual pane to single pane on orientation change maintaining fragment stack Currently I have a dual pane layout for both landscape and portrait on a tablet. Similar to say settings I have a single activity which loads a fragment into the left selection pane and then choices made in whatever right fragment is being shown result in further fragments being displayed into the right pane adding to the backstack all the way. Now I can see that for some tablets it would make sense to have a single pane for portrait and a dual one for landscape. However, I would want the following behaviour: A) If in landscape a fragment stack of depth N say is in the right pane then on an orientation change to portrait I would still want fragment N to be displayed and the stack to be maintained B) Then navigating back from fragment N in portrait mode I eventually want to come back to the selection screen. Now I can't figure out how to achieve this, ideas that I've come up with thus far are: 1) Have dual panes for both orientations but hide the left one on orientation change, would then need to reshow and hide right pane when stack is cleared 2) Rebuild the stack into the new containter, adding the selection fragment at the beginning on a switch to portrait Neither, if they work, seem entirely satisfactory to me. Just wondering what the better/recommended way of doing this is. Thanks in advance. Peter. Edit 1 It should be mentioned that I understand that you can have have different layouts for portrait and landscape and am finishing up a large project with a dual pane layout for both portrait and landscape so OK on the lifecycle of an orientation change. I have also looked at the FragmentLayoutSupport example but that doesn't maintain the data in the right pane on an orientation change to portrait, it shows the list again. A: PJL, so you are on the right track here, either you can check your orientation and then show or hide specific fragments or you can have two different layouts one for Portrait and one for Landscape, in your onCreate function of your Activity you can then check if the second Fragment is available via findViewById and then instantiate it or not. The View you are looking for would just have a FrameLayout with a known Id. So make sure you understand what happens during an orientation change enter link description here A really good Fragments Example is part of the Samples of the Book The Busy Coder's Guide To Advanced Android Development the book is part of a 40$ / year description. The Sample code is free though. Check out the Fragments Example it might help with your problems. Also of course you can have a look at the example FragmentLayoutSupport.java on developer.android.com A: If you are using the list with action intents and uri's you can reorder the frags depending on orientation, action and uri in onCreate. If not I guess you can keep a selectedId value in preferences and use it to keep track of your detail-view. You will have to keep this value up to date by saving it to preferences in onclick and make sure it is updated to -1 (or suitable) on things like back (if back closes this fragment).
{ "language": "en", "url": "https://stackoverflow.com/questions/7604329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Rails validates_uniqueness_of is causing an exponential number of queries. How do you optimize? I have the following: class List < ActiveRecord::Base accepts_nested_attributes_for :list_options, :reject_if => lambda { |a| a[:title].blank? }, :allow_destroy => true validates_associated :list_options class ListOption < ActiveRecord::Base validates_uniqueness_of :title, :scope => [:list_id] When a new list is created along with lets say 10 list items in the controller: @list = List.create(params[:list].merge(:user_id => current_user.id) The database get queried individually to check each listOption to see if it is unique. Is there a way to optimize the above so the db doesn't keep getting hit to check every item? Thanks A: I would suggest you create a unique index inside your database. First run script/rails generate migration unique_index to get a migration. It will be called something like db/migrate/20120313180200_unique_index.rb Put this inside: class UniqueIndex < ActiveRecord::Migration def up add_index(:list_options, [:list_id, :title], :unique => true) end def down remove_index(:list_options, :column => [:list_id, :title]) end end Run rake db:migrate in your rails-root. This will fail if there already are duplicate titles as your database will immediately check that each combination of list_id and title is unique. If you now try to save an duplicate entry into the database it will raise a ActiveRecord::RecordNotUnique exception. To handle it try something like begin ListOption.save rescue ActiveRecord::RecordNotUnique # Some handling code # use $! to access the exception for further details end Of cause you can also ignore these errors. A side-effect of adding the unique-index to the database is, that queries to check whether a certain pair of list_id and title is stored inside the database, are speed up quite a bit, so you may be able to leave the uniqueness-check inside your model and still have a much better response time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I support OpenGL ES GL10, GL11, and GL20 in Libgdx? I am writing a 3d game that is using GL10, but I'd like the application to support GL11 or GL20 if available. What is the best design for supporting all 3? Or is this a fool's errand and I should just focus on supporting one version? My current idea is to split my render() function into renderGL10, renderGL11, renderGL20 and call the appropriate render function based on the available GL instance. Inside each render function is the proper way to render for the GL version; there will likely be overlap for GL10 and GL11. Is this an appropriate way to handle my problem or is there a better way? public render(){ if (Gdx.graphics.isGL20Available()){ renderGL20(); } else if (Gdx.graphics.isGL11Available()){ renderGL11(); } else { renderGL10(); } } EDIT: Solution: If gl1.x is available, gl10 is also available (and Gdx.gl10 is not null). So, my render code should generally be structured as follows: public render(){ // Use Gdx.gl for any gl calls common to all versions if (Gdx.graphics.isGL20Available()){ // Use Gdx.GL20 for all gl calls } else { if (Gdx.graphics.isGL11Available()){ // Use Gdx.gl11 for any gl11 call not supported by gl10 } // Use Gdx.gl10 for all gl calls } } A: Do you actually use shaders in your OpenGL ES 2.0 path or do you rely on SpriteBatch and consorts to handle the dirty details for you? In the later case there's no real benefit in going GLES 2.0 (apart from non-power of two textures, which might be slower on some devices) Usually you chose between either GLES 1.x or 2.0. If you go with 1.x you don't have to do anything. If you want to use 2.0 you have to create an AndroidApplicationConfig and set the useGL20 flag to true. If GLES 2.0 is not supported on the device you run your app on, libgdx will fall back to 1.x. You can then use your above render loop which will use GLES 2.0 if available and fall back to 1.x otherwise. You are unlikely to have to have separate paths for 1.0 and 1.x though, unless you use GLES calls directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How did we get this real number in binary? from this article: the number 5.125 (binary 101.001) why? 101 is 5 , but how are decimal places converted? Also from that article - a bias is added to the actual exponent e. What is bias? What is the purpose of it? A: Why b101.001 = 5.125? That's just how digits after the binary point work. They're like the digits after the decimal point in base10 (commonly known as the "decimals"). b10 = 2^1 b1 = 2^0 b0.1 = 2^-1 b0.01 = 2^-2 b0.001 = 2^-3 = 0.125 This representation is called fixed-point. More information here. What is exponent bias? Bias is a part of the specification for representing floating-point numbers in binary (see IEEE 754). It's the number you add to the exponent to convert it from a -limit to +limit range to a 0 to +2*limit range. This makes the computer able to store the number with the unsigned interpretation. Why exponent bias? The reason for using the exponent bias is that it'll allow the computer to use an unsigned system instead of the two's complement. This makes floating-point comparison easier. A: Just the same way: Each "1"-digit contributes 2^d, where d is the place of the digit. The unit digit is in place 0, the place counts up to the left and down to the right, so the place right of the point is -1. So 0.001 is 2^-3, or 1/8, or 0.125. The purpose of the bias in the exponent in IEEE754 floating point representations is so that you do not require any extra logic to determine the sign of the exponent, and it has the additional advantage that the lexicographic ordering of the binary representation equals the value ordering (at least for a fixed sign): So 0x00000000, which is 0.0, is followed by 0x00000001, which is the smallest positive (though denormal) float. It's exponent is the smallest (negative) exponent, thanks to the bias. A: See the Floating-Point guide for a detailed explanation of how binary fractions work. What is bias? What is the purpose of it? A biased exponent is used because it allows floating-point numbers to compared for value exactly like integer numbers, i.e. if a bit pattern A is greater than a bit pattern B when interpreted as integer, the same is always true if you interpret the patters as floating-point numbers. A: 1 * 2^2 = 4 0 * 2^1 = 0 1 * 2^0 = 1 . 0 * 2^-1 = 0 0 * 2^-2 = 0 1 * 2^-3 = 0.125 ---------------- 101.001 = 5.125 The exponent on the base continues decrementing each digit past the decimal point. In base two that means that the first digit is worth 1/2 = .5, the second is 1/4 = .25 and the third is 1/8 = 0.125. It works the same way as base 10: The first digit is 1/10 = 0.1, the second is 1/100 = 0.01 etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/7604343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: passing by reference in Java doubts So I was reading this post and response no. 2. In that example, after calling that method, does the Dog value at address 42, name's changes to Max? Dog myDog; Dog myDog = new Dog("Rover"); foo(myDog); public void foo(Dog someDog) { someDog.setName("Max"); // AAA someDog = new Dog("Fifi"); // BBB someDog.setName("Rowlf"); // CCC } A: Java is pass by value - always, both for primitives and objects. In the case of objects, the thing that's passed is the reference to the object that lives out on the heap. A method cannot change what that reference points to when it's passed in. If that reference points to an object that has mutable data, the method can alter its state. From "The Java Programming Language Second Edition", by Ken Arnold and James Gosling (ISBN 0-201-31006-6 ) (probably from page 40--don't have the book handy right now): Some people will say incorrectly that objects in Java are "pass by reference." The term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory. [...] There is exactly one ParameterPassing mode in Java--pass by value--and that helps keep things simple. So let's look at your example (with some improvements): public class Dog { private String name; public static void main(String [] args) { Dog myDog = new Dog("Rover"); System.out.println("before foo: " + myDog); foo(myDog); System.out.println("after foo: " + myDog); } public static void foo(Dog someDog) { someDog.setName("Max"); // AAA someDog = new Dog("Fifi"); // BBB someDog.setName("Rowlf"); // CCC } public Dog(String n) { this.name = n; } public String getName() { return this.name; } public void setName(String n) { this.name = n; } public String toString() { return this.name; } } Here's the output: before foo: Rover after foo: Max Tool completed successfully You can't change what the reference that's passed to foo points to, so setting it to the reference with the name "Fifi" at line BBB, and subsequently changing the name of that object at line CCC, does nothing. That instance is eligible for garbage collection when foo exits. The incoming reference that points to "Rover" has a mutable data member: its name. Changing its value at line AAA is reflected in the reference that was passed in; hence the different output. A: This is probably the topic that is confusing for most novice developers in Java. duffymo had already provided a detailed answer (I'm not going to repeat that) but I could give you some articles for reference that I hope would clear the doubt from your mind. Jon Skeet's article about parameter passing in Java Pass-by-Value Please Does Java pass by reference or pass by value? HTH. A: that Dog (the one at address 42) is asked to change his name to Max Yes A: Does the Dog value at address 42, name's changes to Max? Yes. The name changes Dog myDog = new Dog("Rover"); foo(myDog); public void foo(Dog someDog) { someDog.setName("Max"); // AAA someDog = new Dog("Fifi"); // BBB someDog.setName("Rowlf"); // CCC } A: myDog and someDog share the same object and contain the same address value at the beginning. That is, both variables tell the JVM how to get to the Object Dog in memory (heap). So if you change something by invoking the setName method on someDog, myDog 'will feel' the effects! After someDog = new Dog("Fifi") a new Object Dog is created (Fifi) and the someDog variable contains a new value/address for Fifi. That is, the value of someDog changes and will tell the JVM how to get to Fifi from now on. At this point, every change on someDog won't affect myDog anymore. Check my answer (the one with the picture) on that post and note that I didn't use the word "pointer" and not even the word "reference" this time! ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Installing Scala 2.9.1/Lift 2.4-M4 using sbt 0.11.0 I am learning to do web development in Scala. currently trying to install the newest version of Scala/lift with sbt 0.11 in MAC OSX. I so far have already done the following: 1. Installed Scala 2.9.1 final 2. Downloaded latest sbt 0.11 from https://github.com/harrah/xsbt/wiki/Setup 3. Setup path environment for sbt What I am trying to do now is getting the latest lift framework (2.4-M4)from http://liftweb.net/download so that I can try running lift_basic project on localhost:8080 using jetty. I have several questions about that; * *Since on the sbt 0.11 I will have to do this: resolvers += "Web plugin repo" at "http://siasia.github.com/maven2" addSbtPlugin("com.github.siasia" %% "xsbt-web-plugin" % "0.1.2") instead of doing libraryDependencies += ... where should I put my object resolvers (checkout the following code below) that would enable me to install both the jetty and web plugin? so, under lift_basic folder should they go within Project/build/LiftProject.Scala or just delete LiftProject.scala and create Build.scala under Project/Build.scala? object Resolvers { val webPluginRepo = "Web plugin repo" at "http://siasia.github.com/maven2" val jettyRepo = "Jetty Repo" at "http://repo1.maven.org/maven2/org/mortbay/jetty" } object Dependencies { // web plugin val webPluginDeps = Seq( "org.mortbay.jetty" % "jetty" % "6.1.26" % "jetty", // The last part is "jetty" not "test". "javax.servlet" % "servlet-api" % "2.5" % "provided->default" ) *What should I do with the sbt.jar existing inside the lift_basic folder? It looks like that it has the old version of sbt there (probably 7.4.0 or so).. *Besides changing the sbt version to 0.11.0 on the Build.properties, what other changes do I need to make to accomodate this new install? Do I have to change the var BuildScalaVersion and var buildVersion on the Build.scala on the full configuration like the example https://github.com/harrah/xsbt/wiki/Full-Configuration-Example here? If yes, what would be the build version? I am a total newbie to Scala, and there hasnt been a lot of documentations out there for installing new scala/lift version. will appreciate any pointers/references/answers that would enable me to install new version of scala/lift. Thank you for your time. A: You can try to look at my project template. Maybe It will be helpful. https://github.com/viktortnk/lift-quickstart
{ "language": "en", "url": "https://stackoverflow.com/questions/7604354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Subset rows based on values of columns of unknown names and number of columns I am sure I have a very basic question but I am frustrated after searching for the idea on how to accomplish subsetting (getting row numbers) of some data frame/matrix which can have any number of columns and column names change all the time. I would like to find only rows (indexes) of the data frame for which any of the columns is greater than 0. Since column names and number of columns is unknown I do not know how to do this... An example: # these are the terms I am looking in terms <- c("beats", "revs", "revenue", "earnings") # dict <- Dictionary(terms) # dictStudy <- inspect(DocumentTermMatrix(mydata.corpus.tmp, list(dictionary = dict))) dictStudy <- data.frame(beats=c(0, 0, 0, 1, 0, 2), revs=c(0, 0, 0, 1, 0, 1), revenue=c(0, 0, 0, 0, 0, 0), earnings=c(1, 0, 0, 1, 0, 1)) ss <- expression(terms > 0) dictStudy.matching <- subset(dictStudy, eval(ss)) I was hoping that expression and eval would save me, but I can not figure this out. How to find only rows in a data frame that have any of the columns > 0? A: I'm assuming you mean you want the rows where at least one element of that row is greater than zero (i.e. any of the columns are greater than zero). > which(apply(dictStudy,1,function(x) any(x > 0))) [1] 1 4 6 As Tommy points out below, this assumes that all your columns are in fact numeric. You could sidestep this by subseting your data frame to pull out only those columns that are numeric: > which(apply(dictStudy[,sapply(dictStudy,is.numeric)],1,function(x) any(x > 0))) [1] 1 4 6
{ "language": "en", "url": "https://stackoverflow.com/questions/7604369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can not work correctly with posting form with jQuery I am trying to get the return from the mail.php but it does not work. What am I missing here? this is my form <form name="myform" id="myform" action="" method="POST"> <input type="text" name="email" id="email" size="30" value=""/> <input type="submit" name="button" id="button" value="Αποστολή"> </form> and this is the script $(function() { $("#myform").submit(function() { $.post('mail.php', function(data) { $('#results').html(data); }); }); }); this script works correctly with jQuery Validate $(document).ready(function(){ $("#myform").validate({ submitHandler: function(form) { // do other stuff for a valid form $.post('mail.php', $("#myform").serialize(), function(data) { $('#results').hide().html(data).fadeIn('slow'); }); } }); }); A: $(function() { $("#myform").submit(function(event) { $.post('mail.php', function(data) { $('#results').html(data); }); }); event.preventDefault(); }); }) Cancel the form submission because you are already doing it in ajax. Update This is how it should look like without validation: $(function(){ $("#myform").submit(function(event){ event.preventDefault(); // do other stuff for a valid form $.post('mail.php', $("#myform").serialize(), function(data) { $('#results').hide().html(data).fadeIn('slow'); }); }); }); The difference is you are sending the serialized data from (with $("#myform").serialize() ) the form. In the previous code you were not sending any variables. Serializing meangs it will take the values of the forms and concatenate them into a single string. Read more about this here: http://api.jquery.com/serialize/ A: Doesn't look like you are not sending the form data: $("#myform").submit(function(event) { event.preventDefault(); $.post("mail.php", $("#myform").serialize(), function(data) { $('#results').html(data); }); }); Preventing default behavior before ajax calls prevents the form from being submitting if the ajax has an error or for some reason causes the js to stop. A: $(function() { $("#myform").submit(function(e) { e.preventDefault(); var data = $(this).serialize(); $.post('mail.php', data, function(response) { $('#results').html(response); }); }); }); You had a syntax error plus you didn't prevent the default click event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MVC RESTFUL HTTPClient try catch oddity I'm a little puzzled why my try...catch exception does not seem to work properly. I set up the following code which works fine - to call a WCF restful service. I decided to test it by shutting off the WCF restful service in hopes that it will trap error messages or ignore a 200(ok) message etc but for some reason..the try catch and response.EnsureStatusIsSuccessful() seems to be ignored thus generating a HttpStageProcessingException error in the middle of the try catch.. As I understand it, I should only need to catch the ArgumentOutOfRangeException when a 200 is ignored...thoughts? // set up passing parameters var p = new HttpQueryString(); p.Add("username", username); p.Add("password", password); try { WebConfigurations cfg = new WebConfigurations(); HttpResponseMessage response; // cfg - gets the base address for the URL of the WCF using (HttpClient client = new HttpClient(cfg.GetBaseUrl())) { // exception HttpStageProcessingException occurs here... response = client.Get(new Uri(client.BaseAddress + "MainService/ValidateUser"), p); response.EnsureStatusIsSuccessful(); string memberallowed = string.Empty; // process the resonse xml etc..NOT a problem... ProcessStreamData proc = new ProcessStreamData(); memberallowed = proc.ReadStreamData(response); // blah balh return result; } } catch (ArgumentOutOfRangeException aorEx) { Console.Write("Argument Out of Range: " + aorEx.Message); return false; } // This really should not be here??? No error message is generated, too... catch (HttpStageProcessingException timeEx) { Console.Write("Stage Processing" + timeEx.Message); return false; } catch (Exception ex) { Console.Write("Standard error" + ex.Message); return false; } A: Have you tried doing this after telling Visual Studio not to break on thrown exceptions? From the Menu, Debug-> Exceptions and then uncheck thrown. Also, you probably want to dump that version of HttpClient from the Rest Starter Kit. The latest version can be found here http://nuget.org/List/Packages/HttpClient and be warned there are breaking changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Accessing javascript variable values of a parent page from the lightbox I have a form inside the main page and I have to populate some of the data present in the form fields into the iframe which is displayed using a lightbox (pretty photo) .I guess I could do it using javascript though I am not exactly sure how . My current code is : <a href="index.aspx?iframe=true&width=100%&height=100%" rel="prettyPhoto[iframes]" title="New form page"><input type="image" style="border-width: 0px;" src="images/form_ordernow_btn.jpg" tabindex="129" id="Form1_ImageButton1" name="Form1$ImageButton1" onclick="storevariables()"></a> </div> <script type="text/javascript"> function storevariables() { var firstname = PrimaryForm.elements["FIRST_NAME"].value; var lastname = PrimaryForm.elements["LAST_NAME"].value; } The above code stores the input form data for the fields "FIRST_NAME" and "LAST_NAME" but how do I pass it on the lightbox ? Any advice would be very helpful Thanks A: If you declare firstname and lastname as global variable i.e. outside the scope of storevariables, then you can access it from your iframe. So in you parent page change the function to: <script type="text/javascript"> var firstname = ""; var lastname = ""; function storevariables() { firstname = PrimaryForm.elements["FIRST_NAME"].value; lastname = PrimaryForm.elements["LAST_NAME"].value; } </script> And inside you iframe you can access them: <script type="text/javascript"> function someFunc() { var firsName = parent.firstname; } </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7604376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is using int + "" bad for converting Java int's to Strings? So our computer science teacher taught us how to convert ints to Strings by doing this: int i=0; String s = i+""; I guess he taught it to us this way since this was relatively basic computer science (high school class, mind you), but I was wondering if this was in some way "bad" when compared to: int i=0; String s = Integer.toString(i); Is it more costly? Poor habit? Thanks in advance. A: In theory The instruction String s = i + ""; does the following: convert i to String by calling Integer.toString(i), and concatenates this string to the empty string. This causes the creation of three String objects, and one concatenation. The instruction String s = Integer.toString(i); does the conversion, and only the conversion. In practice Most JIT compilers are able to optimise the first statement to the second one. I wouldn't be surprised if this optimisation is done even before (by the javac compiler, at compilation of your Java source to bytecode) A: i+"" is equivalent to new StringBuilder().append(i).append("").toString(); so yes it is less efficient, but unless you are doing that in a loop or such you probably won't notice it. [edited: from comments by StriplingWarrior-thanks] A: That technique works but it relies on the magic of string concatenation in Java (which is one of the few areas that involves operator overloading) and might be confusing to some. I find the following techniques to be more clear: String.valueOf(123); // => "123" Integer.toString(123); // => "123" And as others have mentioned, it results in more concise bytecode since it avoids the implicit construction of a new StringBuilder and the accompanying method calls. A: Using that method will compile, since your teacher used that, you might want to use that method when doing stuff in class, but to make it more clean, you might want to use the following code instead. int i=0; String s = Integer.toString(s); Its looks more official....
{ "language": "en", "url": "https://stackoverflow.com/questions/7604379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Check for [] operator How do I check whether an object supports [] operation in Python? I think of something like the following: if supports(obj, ?[]?): print("Supports") A: The internal name of the [] operator is __getitem__ (and __setitem__), so you can take a pretty good stab at this with: if hasattr(obj, '__getitem__'): print "Supports" A: You can check to see if the class has an __getitem__ method, as per the language docs. A: There's an easy way to see if you can iterate over an object (ie, do a for i in obj): import collections if isinstance(obj, collections.Iterable): print 'obj supports iteration' If you're concerned about checking if you can use an actual key, I'd recommend just "asking for forgiveness" rather than permission: try: value = obj[key] except (AttributeError, TypeError, IndexError): # These are different things that can return in different situations value = None print 'I guess that key doesn\'t work' The only reason I would suggest using collections.Iterable instead of this method is that having a try around your for loop around who knows what else, can get kind of complicated. A: You don't "check for support". You just use it: try: a = obj[whatever] except TypeError: # whatever your fall-back plan is when obj doesn't support [] (__getitem__) Writing your own isinstance is always the wrong thing to do. A new type that doesn't inherit from the collections ABC classes can still have the right behavior. Duck Typing means you can never rely on isinstance. Writing your own hasattr test merely duplicates Python's internal checking that raises the exception. Since Python must do the test, why duplicate that? Finally, "I think that with exception handling this code will be less readable." Is false. The Pythonic principle, accepted by many experienced Python programmers is that it's Easier to Ask Forgiveness That to Ask For Permission. The language is designed to do this with exceptions. A: Try hasattr(obj, "__getitem__"): if hasattr(obj, "__getitem__"): print("Supports") From the operator.getitem help: operator.getitem?? Type: builtin_function_or_method Base Class: <type 'builtin_function_or_method'> String Form: <built-in function getitem> Namespace: Interactive getitem(a, b) -- Same as a[b]. Check out the operator module: * *Return the value of a at index b: operator.getitem(a, b) operator.__getitem__(a, b) *Return the slice of a from index b to index c-1: operator.getslice(a, b, c) operator.__getslice__(a, b, c) *Set the value of a at index b to c: operator.setitem(a, b, c) operator.__setitem__(a, b, c) *Set the slice of a from index b to index c-1 to the sequence v. operator.setslice(a, b, c, v) operator.__setslice__(a, b, c, v) *Remove the value of a at index b: operator.delitem(a, b) operator.__delitem__(a, b) *Delete the slice of a from index b to index c-1: operator.delslice(a, b, c) operator.__delslice__(a, b, c) etc..
{ "language": "en", "url": "https://stackoverflow.com/questions/7604380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: function Wordpress to open image in lightbox implemented lightbox in Wordpress i have this code , but i need to modified to work , http://pastebin.com/hzkc2GwK The value on href= doesn't work , i need to open the image in lightbox mode , I use this option for upload a image http://imageshack.us/photo/my-images/217/51373696.jpg/ How can do fix this code???? very thanks!! A: Go Here It gives the Codex for working with the WP featured image options
{ "language": "en", "url": "https://stackoverflow.com/questions/7604381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What ribbon controls are there for Delphi Win32? Is there any ribbon-like tool for 32-bit Delphi? I use D2007. A: TMS Software has one in their component pack. DevelopersExpress has one also in their ExpressBars package. I haven't used either of them, but I've used other components from both vendors, and they're pretty good. There are probably others as well. A: Yet another option is to use Microsoft's Windows Ribbon Framework. This is the most onerous option for the programmer, but yields the best results for the user. On the other hand, this component is not available for XP so that often presents an insurmountable hurdle. Kudos to Ulrich for pointing out Erik van Bilsen's Delphi wrapper.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Active Directory user federation with Rails? Is it possible to use existing AD users to authenticate them in a ruby on rails app? To be a bit more precise here's the current situation. A rails app is hosted on a linux box. Currently Brightbox is used as hosting provider. There's only built in user authentification in the rails app and I can't see a way to make the app aware of connected AD users. Now there's a rather big customer in spe with hundreds of Active Directory users. Clearly they want to have their users logged in without creating a rails app account for each. All the known idendity providers (OpenId, Google, Facebook...) are no alternative. The only thing I could find doing this stuff is Microsofts ADFS2. But it looks like not really usable in the rails world. But that's exactly needed. A way to establish a trust between AD and my app to trust the external AD users. Any ideas? A: ADFS requires some flavour of web.config on the client side. You could protect the rails app. with another Access Manager product (OpenSSO / OpenAM). See Integrating Applications With OpenSSO. Or you could add a WIF "lookalike" plugin to Rails (if there is such a beast) which needs to handle either the WS-Federation or SAML protocol that ADFS recognises. A: Have a look at PingFederate which is sold by my employer, Ping Identity. You'll be done in no time. It makes this sort of integration very simple and secure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: AJAX Mouse Driven Signature Script (Sign and Save) I've found drawing program (point-based), I've found table-based version (with thousands of elements), and I've found a solution which uses canvas, which apparently IE doesn't support. There is a commercial script at realsignature.com which demonstrates what I'm looking to do. Be able to capture the users signature as a file. Does anyone know of an open source or free solution? A: This brilliant fellow may have just what you need: "A jQuery plugin for assisting in the creation of an HTML5 canvas based signature pad. Records the drawn signature in JSON for later regeneration." http://thomasjbradley.ca/lab/signature-pad
{ "language": "en", "url": "https://stackoverflow.com/questions/7604391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Disable application functionality when missing assembly I'm building an application that uses the Oracle.DataAccess.dll to connect to a database to do some work. The database access isn't necessary to perform 90% of what the application does and the application loads fine without the dll thanks to JIT loading. However, it does crash when accessing the specific part of the application that uses the dll when it's not present. I'd like to be able to disable access to that form proactively when the dll is missing, is there any way to detect that dll at application load? Update: I was able to find a potential solution by doing if (!File.Exists("Path to Oracle.DataAccess.dll")) { toolStripMenuItem.Enabled = false; } Are there any better solutions out there? A: You could try Assembly.Load and see if it works; otherwise, perhaps GetLoadedModules may do what you need. A path search isn't going to work as it'd exclude the GAC and other places assemblies can be.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get query string in PHP doesn't work I am a php newbie, and I'm trying to follow suggestions for how to get the query string. I want the words searched on in a readable format. Now, the strings come from a database, where they have been previously collected using the request object's referer property in Asp.Net. But as far as I know that shouldn't make any difference. So I tried this: function getQuery($url) { $processed_url = parse_url( $url ); $query_string = $processed_url['query']; if($url != '') { return $query_string; } else { return $url; } } So I tried a variation, which should also extract the query string: $query = parse_url($url, 6); return $query; Well, that sort of works. It gives me a query string part, but including the "q=" and all that, not just the text of the query string. So I tried the parse_str() function on this, which is supposed to be able to parse the query string itself: parse_str($query, $myArray); return $myArray[0]; But that didn't work at all, it gives me no results in the result page (a grid). What am I doing wrong? First of all with the first method for getting the query above, and secondly for parsing the query string into its components? (the 0 index was just an example, I thought I'd concatenate it later if I managed to get out only the text parts)? A: It would seem that you are trying to parse a url from a string, not from the current request (as mentioned in comment) On the PHP docs in the comments, there is a great function, that does exactly what you want, i have copied it here, so it can be used in future references - all credit goes to "Simon D" - http://dk.php.net/manual/en/function.parse-url.php#104527 <?php /** * Returns the url query as associative array * * @param string query * @return array params */ function convertUrlQuery($query) { $queryParts = explode('&', $query); $params = array(); foreach ($queryParts as $param) { $item = explode('=', $param); $params[$item[0]] = $item[1]; } return $params; } ?> which means it should be used like this: $array = convertUrlQuery(parse_url($url, 6));
{ "language": "en", "url": "https://stackoverflow.com/questions/7604396", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does this Program run from Aptana IDE and not in python command? The following code results in a htmlbody,emailaddress = ConnEmailParser() TypeError: 'NoneType' object is not iterable Error but works fine in IDE. Emails are being sent and PDF files generated. But from command line just ConnEmailParser() is working. What can I do, that the program runs smoothly? Here the code snipped: import imaplib import email import quopri from cStringIO import StringIO import ho.pisa as pisa from datetime import datetime import logging import smtplib from email.generator import Generator from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.Utils import formatdate from email import Encoders def sendPdfSurvey(): def ConnEmailParser(): try: saver = StringIO() SERVER = "server" USER = "user" PASSWORD = "nono" subject="a certain phrase" imap4 = imaplib.IMAP4(SERVER) imap4.login(USER, PASSWORD) imap4.select() imap4.search(None, 'ALL') typ, data = imap4.search(None,'(UNSEEN SUBJECT "%s")' % subject) #looking for phrase count = 0 for num in data[0].split(): count = count + 1 # this is stupid but it gets just oone messsage if count ==1 : typ, data = imap4.fetch(num,'(RFC822)') email7 = email.message_from_string(data[0][1]) varSubject = email7['subject'] # The phase from above has an emailaddress in the subject field emailaddressraw = varSubject[13:] emailaddressmedium = emailaddressraw.replace("<","") emailaddress= emailaddressmedium.replace(">","") msg = email.message_from_string(data[0][1]) typ, data = imap4.store(num,'+FLAGS','\Seen') a=str(msg) i= a.decode('quopri').decode('utf-8') saver.write(i) savercontent = saver.getvalue() # body of the email is html and all of the header elements get deleted planhtml = savercontent.split('<html xmlns="http://www.w3.org/1999/xhtml">')[1].strip() return planhtml, emailaddress.strip() saver.close() imap4.close() imap4.logout() except: "could not get participant email!" #here somewhere is the trouble maker htmlbody,emailaddress = ConnEmailParser() filenamePDF= "UmfrageEthics_%s.pdf" % datetime.utcnow().strftime('%m%d%H%M%S%f') def printPdf(): try: html = htmlbody result = StringIO() pdf = pisa.pisaDocument(StringIO(html.encode("UTF-8")), result, encoding='UTF-8') filetoparse=open(filenamePDF,"wb") filetoparse.write(result.getvalue()) filetoparse.close() #pisa.startViewer(filenamePDF) except: print "could not write PDF" def sendPdfParticipant(): try: oNachricht = MIMEMultipart() oNachricht['From'] = 'some@email.com' oNachricht['To'] = emailaddress oNachricht['Date'] = formatdate(localtime= True) oNachricht['Subject'] = 'A subject' oAnhang = MIMEBase('application','octet-stream') oAnhang.set_payload(open(filenamePDF,'rb').read()) Encoders.encode_base64(oAnhang) oAnhang.add_header('Content-Disposition', 'attachment;filename = some.pdf') message_text_plain = u'Some message...' oNachricht.attach(MIMEText(message_text_plain.encode('utf-8'), 'plain', 'UTF-8')) io = StringIO() g = Generator(io, False) g.flatten(oNachricht) oNachricht.attach(oAnhang) user = 'user' pwd = 'pwd' smtpserver = smtplib.SMTP("smtp.raumopol.de",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(user, pwd) smtpserver.sendmail('som@eemail.com',emailaddress,oNachricht.as_string()) smtpserver.quit() except: print"could no send data" sendPdfSurvey() A: In def ConnEmailParser(), check if data is None before calling data[0].split(). If it is None, check if imap4 is correctly initiated and if login worked. If that is the case, post a reduced part of your code pinpointing on where it actually goes wrong. As @Jim Garrison pointed out, a traceback would help us (and you) a lot. This is how: import traceback try: some_code... except TypeError: traceback.print_exc() edit (based on your comment) When you encode a unicode string, you are replacing characters that are not part of ASCII with codes as '\xfc'. Apparently, saver.write() tries to encode your already encoded text, after first interpreting it as unicode (you got u'\xfc'). So don't encode yourself. If it still goes wrong, see how you can change the encoding (e.g. 'utf-8', 'cp1252'). Get the current encoding of your OS with import locale encoding=locale.getlocale()[1]
{ "language": "en", "url": "https://stackoverflow.com/questions/7604399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ticking checkboxes using mechanize I have the following html piece from this website: http://catalogue.bl.uk/F/NTBK6NCP3LK56BPNU2NJ4FF4MBLIRUNMFX66JLHKBDV1RNCAAB-02920?func=short-0&set_number=151530 <form name="XXX000001" method="GET"><input type="checkbox" name="ckbox" onclick="javascript:select_record(this.form);" onkeypressed="javascript:select_record(this.form);"></form> I was wondering if there is anyway I can use mechanize to tick the checkboxes? It seems that these boxes are not formed using the normal html. I don't know javascript A: I assume you're talking about submitting information back to the page using Mechanize as if a human was using a browser to tick the checkboxes. The easiest way to do this is to first use WireShark to watch everything that happens when you actually submit the form with a web browser (with the checkboxes checked) and then mimic that same behavior when you submit the form using Perl. A: Maybe you should check WWW::Selenium in order to deal with JavaScript web pages. WWW::Selenium is a kind of remote control for browsers. From the documentation: Selenium Remote Control (SRC) is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser. SRC provides a Selenium Server, which can automatically start/stop/control any supported browser. It works by using Selenium Core, a pure-HTML+JS library that performs automated tasks in JavaScript; the Selenium Server communicates directly with the browser using AJAX (XmlHttpRequest). After you have downloaded and installed the Selenium server ( a Java apllication ), you can use the module WWW::Seletion, to control the server which will use browsers to interact with complex JavaScript enabled web sites. With an instance of the class WWW::Selenium my $sel = WWW::Selenium->new( host => "localhost", port => 4444, browser => "*iexplore", browser_url => "http://www.google.com", ); almost every kind of interaction with a web site become possible. One has to define a locator to pinpoint an element in the page, in order to issue a command ( select, click, ... ). You'll find detailed help in the module documentation. A: Because WWW::Mechanize does not speak javascript, you either need to do as suggested and figure out what the javascript does and go around its back or you can use something like WWW::Mechanize::Firefox that will allow you to control a browser. A: I have a suggestion that is admittedly not the most elegant solution but in the spirit of "gett'r done" you could try and create an autoit script that did some of the gui interactions for you. It is pretty neat little tool. I was bored of leveling my character in a game once so I created an autoit script to level my player for me and it only took me about a day to learn the syntax and create the script. I am sure automating a webpage would take much, much less time. Just a thought...
{ "language": "en", "url": "https://stackoverflow.com/questions/7604400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to print object in an array? I am trying to print multiple Information entries that will be inserted in an array as an object, and I want to use the methods that are available to those objects and print the result. This is my code. I am getting an error in my last two sentences using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace homework2 { class Shapes { protected string ShapeName; protected double ShapeWidth; protected double ShapeHeight; public Shapes(string ShapeName, double ShapeWidth, double ShapeHeight) { this.ShapeName = ShapeName; this.ShapeWidth = ShapeWidth; this.ShapeHeight = ShapeHeight; } } class Rectangle : Shapes { public Rectangle(string ShapeName, double ShapeWidth, double ShapeHeight) : base(ShapeName, ShapeWidth, ShapeHeight) { this.ShapeName = ShapeName; this.ShapeWidth = ShapeWidth; this.ShapeHeight = ShapeHeight; } public double GetArea() { if (ShapeName == "Circle") { ShapeHeight = 3.14; double x = ShapeHeight * (ShapeWidth * ShapeWidth); return x; } else { double Area = ShapeHeight * ShapeWidth; return Area; } } } class Program { static void Main(string[] args) { Rectangle Rec = new Rectangle("Circle",5,2); System.Console.WriteLine("This is the Rectangle Area :"+Rec.GetArea()); System.Console.WriteLine("Please Enter How Many Shapes You want To enter:"); String x = Console.ReadLine(); int y = int.Parse(x); for (int i = 0; i <= y; i++ ) { System.Console.WriteLine("Enter Name for Shape No."+i+"Please"); String ShapeName = Console.ReadLine(); System.Console.WriteLine("Enter width for Shape No." + i + "Please"); String ShapeWidth = Console.ReadLine(); int sw = int.Parse(ShapeWidth); System.Console.WriteLine("Enter height for Shape No." + i + "Please"); String ShapeHeight = Console.ReadLine(); int sh = int.Parse(ShapeHeight); for(int j = 0; j < 4; j++) { Rectangle[,] z = new Rectangle[y,4]; Rectangle z[i,j] = new Rectangle(ShapeName, sw, sh); } } } } } A: Firstly, in your derived class Rectangle, you do not need to reassign the variables in shape as the base constructor will still be called. Also, it would make more sense to, instead of passing in a string like "Circle" to create a circle, to create a new class Circle : Shapes that implemented a different GetArea() rather than having your rectangle class calculate the area of a circle. The error you are presumably having is with the line: Rectangle z[i,j] = new Rectangle(ShapeName, sw, sh); Because you have already defined z[i,j] as an array this line should read z[i,j] = new Rectangle(ShapeName, sw, sh); (Without the rectangle). However, I suspect you want to define your array of Rectangles outside of the first for loop. With the current code, you are going to end up with y 2D arrays with one column filled in for each one. You need to move this: outside of the first for loop Rectangle[,] z = new Rectangle[y,4];
{ "language": "en", "url": "https://stackoverflow.com/questions/7604402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: calling a buttons click Event method I have a form (AddNewCamper), which contains a textbox and a submit button. In a different form, I'm trying to write: if (submit button is clicked) do stuff In the window that the button is actually in, I have a click event created. So I guess I'm trying to call that click event inside the if statement (which is in a different window from where the click event is located). Here's what I have: AddNewCamper camp = new AddNewCamper(); camp.Show(); // This is where I'm confused. How do I say if this button is clicked, // or how do i call its click event that's located in AddNewCamper? if (camp.btnNewSubmit_Click_1()) { Camper person = new Camper(camp.txtNewFirstName.Text); camp.txtNewFirstName.Text = person.getName(); c.testListBox.Items.Add(person.getName()); campersFrame.Content = c; } A: As I understand your question, seems you want to display some content in the parent form when the submit button click on the AddNewCamper Form. Below is one way that you can do that. Add a public method to the ParentForm to Show(or refresh) the content once Submit clicked from the AddNewCamper. In the ParentForm public RefreshCamper(string firstName) { Camper person = new Camper(camp.txtNewFirstName.Text); camp.txtNewFirstName.Text = person.getName(); c.testListBox.Items.Add(person.getName()); campersFrame.Content = c; // ETC... } Pass the ParentForm instance to the AddNewCamper Form in the contructor. private ParentForm _parentForm; public AddNewCamper(ParentForm parentForm) { _parentForm = parentForm; } private void btnNewSubmit_Click_1() { _parentForm.RefreshCamper(txtNewFirstName.Text); } Create an AddNewCamper instance as below from the ParentForm. AddNewCamper camp = new AddNewCamper(this); camp.Show(); // Or ShowDialog if you want Model.. Or you can set a flag in the ParentForm in the same way to identify that the Submit button is clicked. A: Go to the event handler of the button (in the Form view of visual studio, in the properties grid find the click event and double click on the box next to it, this will take you to it [or create it if it hasn't been created yet]) From here, you need to call the method you want to do when the user presses the button. Looking at the code you have provided, I assume what you want to do is wait at the if statement until the user has pressed the button. Unfortunately, unless this code is on a separate thread, if you were to wait for the user to press the button, the program would hang. Instead, you have to work out what you want to happen when the user presses the button, put this in a method and get the button event handler to call that method. A: When you have the "camp" form show, pass a reference to the parent form like this: camp.Show(this); Then, when someone clicks on the submit button of the "camp" form, you can reference the parent form using the owner variable to do the things you want on that form like this: ((ParentForm)owner).SomeMethod(parametersToPassToParentForm);
{ "language": "en", "url": "https://stackoverflow.com/questions/7604414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to bind this collection to my listbox How do i wrap a collection of wrapped class. I have a property in my View Model which is of type AsyncVirtualizingCollection<Item> ItemValues{get;set;} Where Wrapper is a generic type Wrapper<T> Of Item class. Basically I am trying to do a data Virtualization from this link Item is a simple class containing three properties (Caption, Key and IsSelected (Implements INotifyPropertyChanged) I need to bind that to a List Box (with checkboxes). I have this templete and am binding this way Templete : <Style x:Key="CheckBoxStyle" TargetType="{x:Type ListBox}"> <Setter Property="VirtualizingStackPanel.IsVirtualizing" Value="True"/> <Setter Property="VirtualizingStackPanel.VirtualizationMode" Value="Recycling"/> <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="True"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBox}"> <Border Background="{x:Null}" BorderThickness="0"> <ScrollViewer x:Name="scrollViewer" VerticalScrollBarVisibility="Visible" Background="{x:Null}"> <ItemsPresenter /> </ScrollViewer> </Border> </ControlTemplate> </Setter.Value> </Setter> <Setter Property="ItemContainerStyle"> <Setter.Value> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="Height" Value="23" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Grid Width="auto" x:Name="grid1"> <CheckBox x:Name="checkBox" IsChecked="{Binding IsSelected}" Content="{Binding Caption}" HorizontalAlignment="Left" HorizontalContentAlignment="Left" VerticalAlignment="Center" VerticalContentAlignment="Center" Foreground="#FF3F3F3F" Background="{x:Null}" FontSize="13" FontFamily="Segoe UI Semibold" ClickMode="Release"> <CheckBox.Style> <Style TargetType="{x:Type CheckBox}"> <Setter Property="Margin" Value="5,2,0,2" /> </Style> </CheckBox.Style> </CheckBox> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> </Setter.Value> </Setter> </Style> And the Main Listbox is like this : <Grid x:Name="gridMain" Height="auto" Width="auto" Background="White"> <ListBox x:Name="listBox" ItemsSource="{Binding Path=ItemValues}" IsSynchronizedWithCurrentItem="True" Style="{StaticResource CheckBoxStyle}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" VirtualizingStackPanel.IsVirtualizing="True" Background="{x:Null}" BorderBrush="Transparent"> </ListBox> </Grid> On running this it only shows the Checboxes and not the Caption. I know i am doing something wrong here in binding. If i remove the style from the list box it shows me list of strings ".Wrapper`1[.Item]" Any suggestions what could be missing here ? A: I found that using this works Content="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Content.Data.Caption}" Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7604417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why does a centered HTML DIV move depending on its content? I have a div with the following css class applied: div.centralcolumn { width: 90%; max-width: 720px; margin-left: auto; margin-right: auto; font-size: 80%; font-family: verdana, helvetica, arial, sans-serif; line-height: 1.6em; text-align: left; } It centers because the auto margins evenly divide the remaining space between both sides. However, one of my pages draws the div slightly further to the left than the others. Upon inspection the divs are the same width (720px) and if I modify the content then the problem div moves back to the correct position. The content in question is a list item, here's the actual block of html: <p> <a href="http://ucf.academia.edu/SebastianRisi/Papers/842358/Task_Switching_in_Multirobot_Learning_through_Indirect_Encoding"> <strong>Task Switching in Multirobot Learning through Indirect Encoding</strong> </a><br/>David B. D'Ambrosio, Joel Lehman, Sebastian Risi, and Kenneth O. Stanley (2011). <br /> <strong>In: Proceedings of the International Conference on Intelligent Robots and Systems (IROS 2011 San Fransisco, CA)</strong> </p> That last line of text seems to be the culprit. If I shorten it then the problem goes away, I tried inserting a to stop the text reaching the edge of the div but that had no effect. BTW I'm using Chrome and Firefox, both exhibit the problem. A: I would suggest making the max-width by 40px bigger at first. If it seems too wide, then shorten in by 10px and so on till it's perfect width for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Resharper, Javascript: "Use of implicitly declared global variable 'X'" I'm using Resharper 6 and ASP.NET Web Methods and have an irritating warning in my Javascript files: "Use of implicitly declared global variable 'X'" The reason is that the web method is created in Javascript as: new X.example().webMethod(arg1, arg2, successCallback, failureCallback); And X...is implicitly defined. I'm wondering if there is a solution to explicitly define this? It's defined in some auto-generated JS file, created by the ASP.NET web method framework stuff. My question is: how do I get rid of the error for this situation, without getting rid of it for legitimately wrong situations? Thanks! A: Adding following to the top of your script file ///<reference path="my.js" /> (my.js is the file where X is defined) will likely fix this warning since ReSharper start seeing this global variable. Otherwise to minimize changes you can add var X = window.X; near the top of the file. Try to make it not to polute global namespace and make sure it will not confuse code that actually instantiates X on the window. A: Got exactly the same problem after moving Jasmine to an external Bower package and excluding Jasmine's code from VS project. Resharper immediately started complaining on Use of an implicitly declared global variable 'describe' and so on. I solved this by adding to the project another file named workaround.js dummy definitions for the variables. In your case it would be: // This is a workaround for R# complaining on undefined global variables. // In practice they come from and are defined by external frameworks, so // this is not a real issue. var X = function () { }; And this is a file in my project - https://gist.github.com/barahilia/62871d9219cee825d82e. A: When using symbols (functions, constants, global variables) defined in other JavaScript files, I pass them to the current file's "scoping function" (top-level, usually anonymous, function that prevents global namespace pollution) as parameters: As you can see from the screenshot, ReSharper (6.0.2202.688) is happy with jQuery, ContainerA and ContainerB even though they are not defined anywhere in the current file. The comment in line 1 is only there for JSLint (no errors). This technique assumes that all the other JavaScript files follow the JavaScript best practice of minimally polluting the global namespace by defining a single top-level object that contains all the exported (public) symbols (i.e. jQuery is the only global object for jQuery library and its plugins, ContainerA is the only global object for LibraryA, ContainerB is the only global object for LibraryB, etc). Because you clearly don't have control over ASP.NET Web Methods generating constructor functions into global namespace, in your case you have to resort to the ultimate container, window: This is a slight variation on the technique suggested by @sethobrien in his comment. An important (IMHO) advantage is that you're not hard-coding window.X into your code. Instead, your code is instantiating classes from the aspNet container (that at the moment happens to be a synonym for window, but that might change in the future). Also, having aspNet.X in the code declares your intention more clearly for people who will read your code in the future. Finally, local variables can be shortened by JavaScript minimizers yielding slightly smaller file transmitted to client browsers. A: If it is an error that can be ignored you can use // ReSharper disable once UseOfImplicitGlobalInFunctionScope
{ "language": "en", "url": "https://stackoverflow.com/questions/7604419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "50" }
Q: Multibinding ComboBox.Text I have a combobox for selecting screen resolution width x height . For example : 1024x768 (Standard) 800x699 (Standard) 1500x900 (Wide) I have a MutliValueConverter to convert the resolution string to a view model width and height member (in the ConvertBack method of the converter ) , but the Convert method just return null. in the xaml for the combobox I have <ComboBox.Text> <MultiBinding Converter="{StaticResource resolutionConverter}"> <Binding Path="GameWidth"/> <Binding Path="GameHeight"/> </MultiBinding> </ComboBox.Text> When I click to select a value in the combobox , the combobox will fall back to selecting nothing . Why is that ? A: I do not think you are supposed to do anything like that, normally you would just set the ItemsSource to your collection of viewmodels and the DisplayMemberPath to the name of the property which holds the display string and that should be about it. The selected item will then be the view model. If the viewmodels have no display string you could bind to a dictionary of <string,ViewModel>, then you need to set the DisplayMemberPath to Key and the SelectedValuePath to Value, then the selected VM will be in the SelectedValue property. (Another option to generate the displayed string for the items is using the ItemTemplate. the VM's should then of course have suitable properties which can be used in it. This will not work well together with IsEditable though)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 'xmlParseEntityRef: no name' warnings while loading xml into a php file I am reading an xml in php using simplexml_load_file. However while trying to load the xml it displays a list of warnings Warning: simplexml_load_file() [function.simplexml-load-file]: <project orderno="6" campaign_name="International Relief & Development" project in /home/bluecard1/public_html/test.php on line 3 Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in /home/bluecard1/public_html/test.php on line 3 Warning: simplexml_load_file() [function.simplexml-load-file]: http://..../index.php/site/projects/:15: parser error : xmlParseEntityRef: no name in /home/bluecard1/public_html/test.php on line 3 Warning: simplexml_load_file() [function.simplexml-load-file]: ional Relief & Development" project_id="313" client_name="International Relief & in /home/bluecard1/public_html/test.php on line 3 Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in /home/bluecard1/public_html/test.php on line 3 Warning: simplexml_load_file() [function.simplexml-load-file]: http://..../index.php/site/projects/:15: parser error : xmlParseEntityRef: no name in /home/bluecard1/public_html/test.php on line 3 How do I rectify to remove these warnings? (XML is generated from url http://..../index.php/site/projects & loaded into a variable in the test.php. I dont have write priveleges to index.php) A: Found this here ... Problem: An XML parser returns the error “xmlParseEntityRef: noname” Cause: There is a stray ‘&’ (ampersand character) somewhere in the XML text eg. some text & some more text Solution: * *Solution 1: Remove the ampersand. *Solution 2: Encode the ampersand (that is replace the & character with &amp; ). Remember to Decode when reading the XML text. *Solution 3: Use CDATA sections (text inside a CDATA section will be ignored by the parser.) eg. <![CDATA[some text & some more text]]> Note: ‘&’ ‘<' '>‘ will all give problems if not handled correctly. A: PROBLEM * *PHP function simplexml_load_file is throwing parsing error parser error : xmlParseEntityRef while trying to load the XML file from a URL. CAUSE * *XML returned by the URL is not a valid XML. It contains & value instead of &amp;. It is quite possible that there are other errors which aren't obvious at this point of time. THINGS OUT OF OUR CONTROL * *Ideally, we should make sure that a valid XML is feed into PHP simplexml_load_file function, but it looks like we don't have any control over how the XML is created. *It is also not possible to force simplexml_load_file to process an invalid XML file. It does not leave us with many options, other than fixing the XML file itself. POSSIBLE SOLUTION Convert Invalid XML to Valid XML. It can be done using PHP tidy extension. Further instructions can be found from http://php.net/manual/en/book.tidy.php Once you are sure that the extension exists or is installed, please do the following. /** * As per the question asked, the URL is loaded into a variable first, * which we can assume to be $xml */ $xml = <<<XML <?xml version="1.0" encoding="UTF-8"?> <project orderno="6" campaign_name="International Relief & Development for under developed nations"> <invalid-data>Some other data containing & in it</invalid-data> <unclosed-tag> </project> XML; /** * Whenever we use tidy it is best to pass some configuration options * similar to $tidyConfig. In this particular case we are making sure that * tidy understands that our input and output is XML. */ $tidyConfig = array ( 'indent' => true, 'input-xml' => true, 'output-xml' => true, 'wrap' => 200 ); /** * Now we can use tidy to parse the string and then repair it. */ $tidy = new tidy; $tidy->parseString($xml, $tidyConfig, 'utf8'); $tidy->cleanRepair(); /** * If we try to output the repaired XML string by echoing $tidy it should look like. <?xml version="1.0" encoding="utf-8"?> <project orderno="6" campaign_name="International Relief &amp; Development for under developed nations"> <invalid-data>Some other data containing &amp; in it</invalid-data> <unclosed-tag></unclosed-tag> </project> * As you can see that & is now fixed in campaign_name attribute * and also with-in invalid-data element. You can also see that the * <unclosed-tag> which didn't had a close tag, has been fixed too. */ echo $tidy; /** * Now when we try to use simplexml_load_string to load the clean XML. When we * try to print_r it should look something like below. SimpleXMLElement Object ( [@attributes] => Array ( [orderno] => 6 [campaign_name] => International Relief & Development for under developed nations ) [invalid-data] => Some other data containing & in it [unclosed-tag] => SimpleXMLElement Object ( ) ) */ $simpleXmlElement = simplexml_load_string($tidy); print_r($simpleXmlElement); CAUTION The developer should try to compare the invalid XML with a valid XML (generated by tidy), to see there are no adverse side effects after using tidy. Tidy does an extremely good job of doing it correctly, but it never hurts to see it visually and to be 100% sure. In our case it should be as simple as comparing $xml with $tidy. A: I use a combined version : strip_tags(preg_replace("/&(?!#?[a-z0-9]+;)/", "&amp;",$textorhtml)) A: The XML is invalid. <![CDATA[ {INVALID XML} ]]> CDATA should be wrapped around all special XML characters, as per W3C A: This is in deed due to characters messing around with the data. Using htmlentities($yourText) worked for me (I had html code inside the xml document). See http://uk3.php.net/htmlentities. A: This solve my problème: $description = strip_tags($value['Description']); $description=preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $description); $description= preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $description); $description=str_replace(' & ', ' &amp; ', html_entity_decode((htmlspecialchars_decode($description)))); A: The XML is most probably invalid. The problem could be the "&" $text=preg_replace('/&(?!#?[a-z0-9]+;)/g', '&amp;', $text); will get rid of the "&" and replace it with it's HTML code version...give it a try. A: Try to clean the HTML first using this function: $html = htmlspecialchars($html); Special chars are usually represented differently in HTML and it might be confusing for the compiler. Like & becomes &amp;. A: If you are getting this issue with opencart try editing catalog/controller/extension/feed/google_sitemap.php For More info and How to do it refer this: xmlparseentityref-no-name-error
{ "language": "en", "url": "https://stackoverflow.com/questions/7604436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "105" }
Q: redirect based on url match I can't get a certain URL to redirect using mod rewrite. I am getting more basic rewriting happening so this is functioning as far as that goes so there is a problem with my URL. I tried the string here and it showed the patter works.. http://regexpal.com/ testing the following RewriteCond %{HTTP_HOST} ^landed.at/component/jreviews/search-results/criteria:5/query:any/jr_country:sri-lanka/order:rdate$ RewriteRule (.*) http://landed.at/itworked [L,R=301] I would like in fact to pull the criteria:5 and jr_country:sri-lanka out to make my variables so my url would become http://landed.at/tours/sri-lanka - tours if criteria:5 and sri-lanka from the jr_country I'm getting no where fast with regex and why doesn't my basic search match happen? according to regexpal it should find the condition and do the rewrite? A: You have included a full path including slashes, but you are only testing it against the HTTP_HOST which will be just landed.at. Did you mean to use REQUEST_URI? (That would have to include the http:// also.) I'd suggest this can probably be done more cleanly with plain old redirects. Don't drag the Swiss Army Chainsaw that is mod_rewrite into the game until you really need it. eg: Redirect permanent /component/jreviews/search-results/criteria:5/query:any/jr_country:sri-lanka/order:rdate http://landed.at/itworked
{ "language": "en", "url": "https://stackoverflow.com/questions/7604439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgrade to Flex SDK 4.5.1 from 4.1.0 causes namespace compile errors for certain mx components I have a Flash builder project that I am migrating from SDK 4.1.0 to 4.5.1. This has been a relatively easy change (we are using maven for our builds, and were able to get a successful build after updating to the 4.5.1 dependencies). As said, the project builds fine with maven and flexmojos. The issue is when opening the project in flash builder. The maven project is imported and then set as a flex project by running the maven flexmojos:flexbuilder build command. The issue lies when certain mx components that are specified with the s: namespace are no longer accepted by the IDE, and result in an error. For example, for the following to compile: <s:states> <s:State name="normal" /> <s:State name="disabled" /> </s:states> s:State must be changed to the mx namespace: <s:states> <mx:State name="normal" /> <mx:State name="disabled" /> </s:states> This is just one example, and only happens for certain spark-namespaced components. Why is this? Why does this compile OK with Flex SDK 4.1.0 but not with Flex SDK 4.5.1, and what is the cause of the necessary namespace change? A: I've found the same problems using FlexMojos because it seems that Adobe did a little trick of specifying the spark namespace for mx components (like State and Spacer). Also, if you're using flexmojos:flexbuilder, it means you're also using an old version of FlexMojos (3.8?). There's version 4.0 now (RC2), however, the flexbuilder goal has been removed for now. Anywho, back to your question, I see it the other way in my project (s:Spacer works in Flash Builder, not in FlexMojos). Personally, I feel that these namespace shouldn't intersect and as a developer it's easier to just specify the exact namespace and not bother with the namespace trickery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: get the value of simplexmlelement object php I try too many thing to read the value of the [label] from the code below : Array ( [0] => SimpleXMLElement Object ( [id] => x [published] => 2011 [category] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [scheme] => y [term] => t ) ) [1] => SimpleXMLElement Object ( [@attributes] => Array ( [scheme] => y2 [term] => Film [label] => Film & Animation ) ) it start with numeric array. A: Isn't your answer as simple as: $data->category['label']? See simplexml documentation next time, all attributes are accessible from an array, and all subnodes are accessible through the object property operator. If you have many categories, then you will have an array at "category[0]"
{ "language": "en", "url": "https://stackoverflow.com/questions/7604442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Microsoft.Maintainability Error with List Extension Methods So I have tried to create some basic extension methods for List. Essentially I have a UniqueAdd and UniqueAddRange. It will check for the existence of a value before adding and if its already in the List it will not add it. Here is the code: public static class ListExtensions { /// <summary> /// Adds only the values in the 'values' collection that do not already exist in the list. Uses list.Contains() to determine existence of /// previous values. /// </summary> /// <param name="list"></param> /// <param name="values"></param> public static void UniqueAddRange<T>(this List<T> list, IEnumerable<T> values) { foreach (T value in values) { list.UniqueAdd(value); } } /// <summary> /// Adds the value to the list only if it does not already exist in the list. Uses list.Contains() to determine existence of previos values. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="value"></param> public static void UniqueAdd<T>(this List<T> list, T value) { if (!list.Contains(value)) { list.Add(value); } } } And I get the following error when building: CA0001 : Rule=Microsoft.Maintainability#CA1506, Target=Some.Namespace.ListExtensions : Collection was modified; enumeration operation may not execute. Here is the link to the error but I'm not sure how to fix my extension methods given this information. It says to Try to redesign the type or method to reduce the number of types to which it is coupled. Does anyone know why I'm getting this error and how to fix my extension methods so they do not violate this rule? Thanks! PS: Before anyone mentions it, I have considered using a HashSet but HashSet does not exist in the compact framework. A: I think your code triggered a bug in FxCop, "Collection was modified" is a classic oops. It then decided that its bug was your problem, catch(Exception) style. Look for an update. The one I use doesn't complain about your code (VS2010 version). A: It's telling you that you are changing the list as you are enumerating it. This is clear from your code (you're adding to the list at the same time as enumerating). How about: public static void UniqueAddRange<T>(this List<T> list, IEnumerable<T> values) { list.AddRange(values.Except(list)); } Or, if the interface is right for your needs, use a Hashset. It does what you want out of the box.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What would be the best table structure? I'm developing an app that will store MLS (Multiple Listing Service) Property Listings from several different MLS's. The majority of my customers will only use one MLS, however, some will use mutliple MLS's. My question is: What is the best method to setup the table(s)? Let's say I have 50 different MLS's. Each MLS will have roughly 80k records and 100 fields. Should I put all listings into a single table and reference by an MLSID? or should I create a new table for each MLS? Each MLS will always have the same field names and datatypes. I would think that putting each MLS into it's own table would be best for performance, but not for scalability. If I were to put all records into a single table, how much do you think that would effect the performance? I'm also thinking a single table may be better because when the customer uses multiple MLS's, I can pull from a single table rather than multiple tables. Thoughts or ideas? A: I would put all MLS's in the same table. Normalization would dictate that if there is repeatable data, some MLS data would be stored separately as well. I don't know enough about the business to speak on that. And if clients can have more than one MLS I would create an intersection table to explicitly show the one to many relationship.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pairs of strings in reverse order in a list of more than million strings? Recently asked during some interview that "How to find reverse of all strings if exists in a list of more than million strings? For E.g. str[1] = "abc", I need to check for "cba" exactly, no anagrams. Method 1. Store all the strings in a hashset, start traversing from the first string and check for the reversed form exists in Hashset. if yes, then pair else move to next element. Can you suggest any method if memory is the constraint? A: If allowed, you could in-place sort the strings so when you look up the reverse of a string you can do a binary search. A: You can use a Bloom Filter which will tell you if a string already exists within a hash table like structure, but each bucket is only 0 or 1 so very little space is used. Exactly 1 000 000 bits == 125 KB A: First I would hash the strings using a hash that was independent of direction. This could be a simple sum of characters, though there are certainly better schemes that would hash from both ends. And to "sweeten the deal" one could append string length to the hash value, or otherwise incorporate it in the hash. Then when you have the strings broken into identical hash groups, do the "long hand" compare. Note that, using either this scheme or the one where you simply use a direction dependent hash forwards or backwards, the thing to do is to not immediately insert the string into the hash set, but rather check it (with the reversed hash if needed) first, and if you get a match (and the subsequent long compare is true) remove the already-hashed string and pair the two. The second string never goes into the set, and, if all the strings have matches at most you'd only ever have 500,000 entries in the hash set, and, if the strings were random, probably closer to 250,000 (I haven't sat down to figure the probabilities). So you'd need only one pass through the set of strings to do the whole thing. A: With "memory as a constraint" then I wouldn't even go for a HashSet (which, afaik will also remove the duplicated strings in the original list) because you'll be using the additional structure of a HashSet which takes some memory. Sorting, wouldn't improve memory usage either. I would use the original list (which is already there, so no extra memory will be used) + a 3 byte integer variable to iterate the list. 3 bytes can iterate over a list of 2^24 = 16777216 strings With "memory as a constraint" I would go for 2 for loops. I think a C-Like pseudocode will be easier to understand that my plain english. Notes: * *From the example provided in the question, it is not actually a List but an Array, so I will operate over the structure as if it was an Array *The question is not clear whether how to pair this "abc","def","cba","abc". I will be pairing the first "abc" with "cba" and also that "cba" with "the second "abc" (the intention is unclear in the question) *I assume we can't modify the original list Here is the least memory-consumption code I can think of: // "list" holds the original list (array) for (int i = 0; i < length(list) - 1; i++) { for (int j = i + 1; j < length(list); j++) { if (list[i] == reverse(list[j])) { print(list[i] + " reversed is " list[j]) } } } Regarding memory usage, this solution will take 2 integer variables (usually 4 bytes each) + the original list, which I assume we can not get rid of. Regarding CPU usage (actually, not relevant based on the question), the amount of times a strings will be reversed will be: (N*(N+1))/2 where N is the length of the list A: You can choose HashTable and use buckets to reduce hash conflict. What we now need to do for a specific query string is just reverse it, hash it and find in the HashTable instead of traverse from start to then end. A: This is jus my opinion: I would create a hash with key=character value=List of string which start with that character * *Now start a loop inside which you need to start at the first string. *reverse it *Take the first character and search for that key in the hash *then in the value of that,it contains the list of strings and find the string in that list
{ "language": "en", "url": "https://stackoverflow.com/questions/7604454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to search in Redis? In MySQL I have a table called: cities which includes 2 columns: name and population and then I get the search results with this: SELECT * FROM cities WHERE name LIKE '%Bu%' ORDER by population DESC LIMIT 2 And I get the Results Bucharest, Budapest. How can I do this in Redis? I mean how can I create a similar structure and then how can I search for values? A: I think you need to do some more research on how key-value storage works, but to use your post as an over-simplified example, one way to do this would be for you to create keys for all your values and then create indexes matched to those keys like: SET c1 "Bucharest" SET c3 "Budapest" SADD city:bu c1 SADD city:bu c3 SMEMBERS city:bu => ["c1","c3"] you can use: http://try.redis-db.com/ to try it out. to extend that for 3 character search: SADD city:buc c1 SMEMBERS city:buc =>["c1"] There are many ways to approach this, including methods where you can assign rank to your index, etc. Also note that this example is a different approach from that referenced example, but a bit easier to understand -- it's similar to one used here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Give access to an image for a limited time until an admin removes the access right? I want people to have access to images for a limited amount of time. Example they pay for x.jpg and they have access to it until I decide they no more have access to download it. note: The 'images' server that store x.jpg is independant from the 'www' server so the system can scale easily. (The two servers don't share data, db access or so...) The best solution I found so far is this one: On the www server, I generate an encrypted string that contains two parameters: "filename" and "expiration_stmp". I pass this encrypted string to a script on the image server that decrypts it, check if the expiration stmp is not in the past and if everything is ok, read the file on disk, output the correct headers and output the image binary data to the client. So I have a link like this one on www server: "img src=http://IMAGES.myserver.com/get.php?XJDKUJHKDJSHJKDHJKHJKDJKDJKD" where the "XJDKUJHKDJSHJKDHJKHJKDJKDJKD" when decrypted will extract to filename=x.jpg,expiration_stmp=132920302030 and get.php on images server will contains something like header('Content-type...bblablabl'); readfile(x.jpg)..... The problem I have to solve is the fact that at the time I generate the encrypted string XJDKUJHKDJSHJKDHJKHJKDJKDJKD, I cannot know the expiration_stmp because the access right can be removed by an admin anytime by in the future, from 1 minute to 5 days. So when an admin in the admin panel remove the right to read the file for that particular user, the user must be denied access to the file. To handle that, I thought of regenerating the page that contains the links every hour by a forced refresh of the page to generate new encrypted string that contains new expiration_stmps that are valid for 1 hour maximum. So the links "img src=http://images.myserver.com/get.php?XJDKUJHKDJSHJKDHJKHJKDJKDJKD" would be valid only for 1 hour, So when an admin cancels the access right of a user, I just refuse to regenerate a new encrypted string so the user can no more access the file after the last generated expiration_stmp has expired (1 hour max). For now it is the best solution I found....I would love to hear any thoughts or better way to handle such a situation? thanks A: Why are you under the impression that restricting by user or session won't scale. You could probably generate an access code instead of your encrypred string. Stor the access code in the DB linked to the image you are supposed to serve, as well as th user id. If the admin wants to remove access just delete the record, or flag it as expired. Databases are very quick and there is no reason a database with proper indexes shouldn't be able to handle this, even of scaled up to millions of active images. A: The best solution would be using a database in the following structor : * *Create a database with 2 tables (you could add more if you need) token, image. token : token will have a field for userID which will point to another table to store user's info , an image ID which will refer to an image in the image database, and an expiry date and an ID. image : it will have ID, imagename for the download link, you could simply do : download.php?tokenID=xxx and the script would go and check if the expiry date is in the past or not, this will happen in real time when the user clicks on the file so you wont have the problem of unauthorized access. once the expiry is checked you can get the imageID from the token field and find the image on the other server. You can easily scale this structure by having one or more database servers (one should be enough in my opinion) and connect all the file/script servers to the remote database server. without having a database it would be impossible considering that the file will only get the date from the GET vars and cant check it with any reference, and the system should be easily hackable if you use any common php functions to encrypt the vars.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android mediaplayer auto restart How can i make mediaplayer auto restart after the sound has finished this is my code: it plays the music then just stops after it finished i want it to replay after it stops MediaPlayer mediaPlayer = MediaPlayer.create(main.this, R.raw.ngmusic); mediaPlayer.start(); A: Did you try to use this one ? mediaPlayer.setLooping( true );
{ "language": "en", "url": "https://stackoverflow.com/questions/7604459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I setup Fmod to very basic functionality in a Win32 console application? I'm new to Visual Studio and would like to set up the very basic functionality of Fmod in a Win32 console application. What I think the main problem is, is that I don't understand quite good how headers, additional libraries and dll files work. Currently I have added "fmodex64_vc.lib" to additional dependencies. The following error occurs: Error 1 error C3861: 'FSOUND_Init': identifier not found c:\PATH\documents\visual studio 2010\projects\fmod\fmod\test.cpp 13 And I use the following code: #include "include/fmod.h" #include "include/fmod.hpp" #include "include/fmod_errors.h" #include <windows.h> #include <stdio.h> #include <conio.h> int main(int argc, char* argv[]) { // Initalize the Fmod System at 44Khz and 32 channels if(FSOUND_Init(44100, 32, 0)) { printf("FMOD Init OK\n"); } else { printf("FMOD Init Failed!\n"); return 0; } } Any suggestions? Thanks! A: fmodex64_vc.lib is an import library for FMODEx (version 4.xx.xx), FSOUND_Init is a function from FMOD (version 3.xx.xx) the two are not compatible. I'm guessing you have downloaded the latest FMODEx release, but are using example code from somewhere else (designed for FMOD3). I would recommend looking inside the FMODEx install directory and use the examples found within along with the fmodex.chm docs as a reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Could not find rake-0.9.2 in any of the sources I have no idea why I am getting this? $ which rake /Users/kamilski81/.rvm/gems/ruby-1.9.2-p290@depot/bin/rake [~/Sites/work/depot, kamilski81@mac] $ /Users/kamilski81/.rvm/gems/ruby-1.9.2-p290\@depot/bin/rake test Could not find rake-0.9.2 in any of the sources Run `bundle install` to install missing gems. After I do a "bundle install" I get : Installing sqlite3 (1.3.4) with native extensions Installing turn (0.8.2) Installing uglifier (1.0.3) Updating .gem files in vendor/cache Your bundle is complete! It was installed into ./rake and all my gems are installed into ./rake of my root dir...pretty annoying. A: It looks like you typed bundle install rake at some point. The bundle command doesn't take the name of a gem to install. Instead, the parameter "rake" is the name of the folder that you install your bundled gems into. If you look in your current project folder, you will see a hidden .bundle directory. The config file in there keeps track of how you set up your bundle install options, and it remembers the directory you set for the next time you run bundle install. The easiest thing to do is to remove the option from that config file, and re-run bundle install without a third parameter. The second part of this issue is that different bundles will install their own version of the commands such as rake. In order to run the correct version, have bundler run it for you by running bundle exec rake instead of just rake. A: For me adding: source 'https://rubygems.org' to my Gemfile solved the problem. For some reason I removed it previously. Thanks to Andrew for the tip initially with the .bundle directory. A: Add the --development parameter once to install all development dependencies from rubygems.org . So if you're trying to run: bundle exec rake build Instead run: bundle --development exec rake build You'll see any missing development dependencies being installed, including rake 0.9.2. Thereafter the --development parameter can be removed when you rebuild. Note that this method also means you don't need to add source http://rubygems.org to every gem you write.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Passing js variables to django view I'm using jquery .submit() function to calculate two variables(f_amount and f_variables) but I don't know how to pass them to the next django view. <form method="POST" action="/app/view">{% csrf_token %} <select id="fd" name="fd"> <option value="2">2</option> <option value="3">3</option> <option value="5">5</option> <option value="1">1</option> </select> <div id="demo2" class="demo"> <ul> {% for f_type, fs in f.items %} <li> <a>{{ f_type }}</a> <ul> {% for f in fs %} <li><a id="{{f.0}}">{{f.1}}</a></li> {% endfor %} </ul> </li> {% endfor %} </ul> </div> <input id="plan" type="submit" value="sched it!" class="btn primary" /> </form> <script> $("form").submit(function() { var checked_ids = new Array(); var f_amount = $("select option:selected").val(); $("#demo2").jstree("get_checked",null,true).each (function (index,value) { if (value.children[2].id) { checked_ids.push(value.children[2].id); } }); var f_ids = checked_ids.join(" "); }); </script> A: i could do it this way in Django 2.1 x123.html First create a hidden input field like this in the 1st html file <form id="scoresForm" method="POST"> {% csrf_token %} <input type="hidden" name="scores" value=""/> </form> views.py then define your View in the views.py and do the POST data handling def result(request, league_id, season_id, matchday): scores = request.POST.get("scores", None) if scores != None: scores = scores.replace("&quot;", "'") #scores = scores[1:-1] scores = json.loads(scores) context = { 'league_id': league_id, 'season_id': season_id, 'matchday': matchday, 'scores': scores, } return render(request, 'matchstatistics/result.html', context) x123.js and lastly in your JS file which belongs to your 1st html template var resultUrl = currentUrl + "/result/" + league_id + "/" + season_id + "/" + matchday + "/"; var scoresForm = document.forms['scoresForm']; scoresForm.action = resultUrl; scoresForm.elements["scores"].value = JSON.stringify(scores); document.getElementById("scoresForm").submit(); y123.html You are able to access the passed Array/Variable easily in your following view by calling f.e. {{ scores }} in your Django Template Please feel free to optimize the code, especially the JSON-Object serialization and deserialization part, im new to Django/Python/JavaScript :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7604471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to disable dragging with mouse click any images? I have an image <img src="fullscreen.jpg" /> for online driving exams, where the questions are asked using image text and with image embedded. When anyone click the image and drag the mouse it moves the image. But how can i stop this dragging? So that nobody is allowed to do so. A: $('#id-of-your-image').mousedown(function(){return false}); Of course you may have to use other selector as in your example image has no id attribute. A: If you're using jQuery, you're looking for the dragstart event. $("img").bind('dragstart', function(){ return false; }); A: Try any of these 3 if you can't or don't want to use an id or jQuery (cross-browser performance has not been tested): <img src="http://www.google.com/intl/en_com/images/srpr/logo3w.png" ondragstart='return false;'/> <img src="http://www.google.com/intl/en_com/images/srpr/logo3w.png" onmousedown='return false;'/> <img src="http://www.google.com/intl/en_com/images/srpr/logo3w.png" onmousedown='return false;' ondragstart='return false;'/> Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7604472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use javascript to center anchor object when page loads I want to jump to an anchor tag when my page loads AND have the anchor object centered in the window. I've used a simple function to go to the anchor when the page loads: <body onload="goToAnchor();"> <script type="text/javascript"> function goToAnchor() { window.location = "#center"; } </script> But in order for the anchor object to be centered, I need to somehow offset the location of the window. For another function, I used something like this to achieve the appropriate offset (the width of the object is a fixed 1500px): var $offset_target = (1500 - $(window).width())/2; This successfully ensured that each time I jumped to an anchor, the object was centered in the viewport, regardless of the window size. Any ideas? Thanks!! UPDATE/ANSWER So, I used two of the replies below to come up with this: function goToAnchor() { document.body.scrollLeft = document.documentElement.scrollLeft = document.getElementById('center').offsetLeft- (Math.ceil((- 1500 + $(window).width()) / 2)); } It might not be the most elegant solution, but it gets the job done! Thanks so much for your answers! If anyone has a better way to do this, please let us know! A: Without jQuery: function goToAnchor() { document.body.scrollTop = document.documentElement.scrollTop = document.getElementById('center').offsetTop-window.innerHeight/2; } This will work fine in most cases. If #center is located in an element with position other than static then it would need a bit extra to calculate the correct offset, but otherwise it'll work as is. A: I did this for a website not too long ago, the code below uses the users window width and subtracts it from your static object's width, divides by two and scrolls horizontally to that location which will center the object horizontally. $(window).scrollLeft(Math.ceil((1500 - $(window).width()) / 2)); A: You don't need script at all, use CSS: .centered { text-align: left; width: 500px; margin-left: auto; margin-right: auto; } IE needs to be in standards mode for this to work (which just means using a valid DOCTYPE). Setting both margins to auto makes them have the same value. Here's a full example that centers the body element: <style type="text/css"> .centered { text-align: left; width: 500px; margin-left: auto; margin-right: auto; border: 1px solid blue; } .panel1 {border: 1px solid red;height: 200px} .panel2 {border: 1px solid green;height: 200px} </style> <body class="centered"> <div class="panel1"> <div class="panel2"></div> </div> <div class="panel1"> <div class="panel2"></div> </div> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/7604485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it common to store geocoded data? On my site, companies are able to enter in locations (addresses, etc) for each of their branches. Rather than geocoding through Google each an every time that I would like to display it on a (Google) map, it seems better to simply geocode each address upon entry, and store the coordinates for later. With all the legal jargon, however, I am confused if this is a regular practice, or whether developers usually geocode on the fly each time? A: Yes, it is a common practice especially when you are running in a bandwidth-limited environment. However, you are not allowed to store all the data indefinitely. Some restrictions apply on the content you are downloading from the API. Here is Google take on this problem (Google Maps API Family Terms Of Service, http://code.google.com/apis/maps/terms.html ; 10.1.3.b): You must not pre-fetch, cache, or store any Content, except that you may store: (i) limited amounts of Content for the purpose of improving the performance of your Maps API Implementation if you do so temporarily, securely, and in a manner that does not permit use of the Content outside of the Service The most important parts are: * *You are not allowed to pre-fetch *Data conservation has to be temporary *Data has to be kept in small amounts A: One thing to consider is that the geocoded coordinate and your address isn't always describing the same point. No geocoding service is perfect in this matter, due to interpolation of street numbers and other inaccuracies. Depending on what you are using the coordinates for, it is quite often so that you will be able to relocate the point and therefore have to save it in your data. For instance if you have a set of companys with addresses like "Kings street 11-15", where is the main entrance to the company? Where will deliveries be made? Things like this can make it impossible to geocode on the fly. Even if you want to use the geocoded coordinat "as is", I can recall that Bing Maps did an exception to the rule of "not saving any data" as to allow storing of geocoded locations. Not sure if Google does the same though... A: Ofcourse - its not like geocode (which essentially just is latitude and longitude) is something google are the only ones to use. Its a pretty much how everyone does it (and has been done for the last decade) A: With my Google Maps project for SugarCRM, I am storing limited amounts of data from the Google Maps Geocoding API in the database (Address Cache Module). I don't store the entire object, just parts of it. Just store what you need for efficiency. Mainly: * *Full One Line Address *Geocode Status *Longitude *Latitude The data is stored in an Address Cache to identify addresses with status "OK". So, I'm only storing limited amounts of the data returned from Google Maps. Which I think it absolutely fine to do so. ALso, I'm only storing this as Address Cache, which can be destroyed and repopulated at any time. Without the "pre-populated" Longitude/Latitude information it would take several minutes to populate a map with 5,000 records. With the cache, a Map with 5,000 records can be displayed in under 10 seconds. http://www.jjwdesign.com/sugarcrm/google-maps-for-sugarcrm Questions to Ponder: * *What does Google Maps consider "Limited Amounts of Content"? Under a 1GB of data? *How do you interpret "purpose of improving the performance"? Using the service on-the-fly perhaps?
{ "language": "en", "url": "https://stackoverflow.com/questions/7604489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NLP algorithm to 'fill out' search terms I'm trying to write an algorithm (which I'm assuming will rely on natural language processing techniques) to 'fill out' a list of search terms. There is probably a name for this kind of thing which I'm unaware of. What is this kind of problem called, and what kind of algorithm will give me the following behavior? Input: docs = [ "I bought a ticket to the Dolphin Watching cruise", "I enjoyed the Dolphin Watching tour", "The Miami Dolphins lost again!", "It was good going to that Miami Dolphins game" ], search_term = "Dolphin" Output: ["Dolphin Watching", "Miami Dolphins"] It should basically figure out that if "Dolphin" appears at all, it's virtually always either in the bigrams "Dolphin Watching" or "Miami Dolphins". Solutions in Python preferred. A: It should basically figure out that if "Dolphin" appears at all, it's virtually always either in the bigrams "Dolphin Watching" or "Miami Dolphins". Sounds like you want to determine the collocations that Dolphin occurs in. There are various methods for collocation finding, the most popular being to compute point-wise mutual information (PMI) between terms in your corpus, then select the terms with the highest PMI for Dolphin. You might remember PMI from the sentiment analysis algorithm that I suggested earlier. A Python implementation of various collocation finding methods is included in NLTK as nltk.collocations. The area is covered in some depth in Manning and Schütze's FSNLP (1999, but still current for this topic). A: I used the Natural Language Toolkit in my NLP class in university with decent success. I think it's got some taggers that can help you determine which are the nouns, and help you parse it into a tree. I don't remember much, but I'd start there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Android: How to send an image as email attachment from application? I'm currently trying to create an app that will take a picture and then attach that picture to an email that will be going to a pre determined email address. I have the email working and I have the camera working. I cant seem to get the picture that the camera has taken to add as an attachment. I have the image popping up in the app as a kind of preview image which I have no problem taking out if this is why it wont attach. When the email is sent a picture has been created but is corrupt and doesn't open. Its as if I'm creating a non existent picture. I think it will be a case of tying the picture taken to the creating attachment part but I have no idea! If anybody could help I would be extremely grateful! Here is my MainActivity where the email is being created along with the camera: import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore.Images; import android.provider.MediaStore.Images.Media; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; public class EmailActivity extends Activity { Button send; EditText address, subject, emailtext; protected static final int CAMERA_PIC_REQUEST = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.email); send=(Button) findViewById(R.id.emailsendbutton); address=(EditText) findViewById(R.id.emailaddress); subject=(EditText) findViewById(R.id.emailsubject); emailtext=(EditText) findViewById(R.id.emailtext); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { } File pngDir = new File( Environment.getExternalStorageDirectory(), "Android/data/com.phstudios.jbrefurb/quote"); if (!pngDir.exists()) pngDir.mkdirs(); File pngFile = new File(pngDir, "pic1.png"); Uri pngUri = Uri.fromFile(pngFile); Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setType("image/png"); emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ "random@yahoo.co.uk"}); emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject.getText()); emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailtext.getText()); emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, pngUri); emailIntent.setType("image/png"); EmailActivity.this.startActivity(Intent.createChooser(emailIntent, "Send mail...")); } }); Button camera = (Button) findViewById(R.id.button2); camera.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); ; } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode== 0 && resultCode == Activity.RESULT_OK){ Bitmap x = (Bitmap) data.getExtras().get("data"); ((ImageView)findViewById(R.id.imageView1)).setImageBitmap(x); ContentValues values = new ContentValues(); values.put(Images.Media.TITLE, "title"); values.put(Images.Media.BUCKET_ID, "test"); values.put(Images.Media.DESCRIPTION, "test Image taken"); values.put(Images.Media.MIME_TYPE, "image/png"); Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); OutputStream outstream; try { outstream = getContentResolver().openOutputStream(uri); x.compress(Bitmap.CompressFormat.JPEG, 70, outstream); outstream.close(); } catch (FileNotFoundException e) { // }catch (IOException e){ // } } } } I'm hoping its something simple that I'm just not linking them together. A: public class MainActivity extends Activity { Button send; Bitmap thumbnail; File pic; EditText address, subject, emailtext; protected static final int CAMERA_PIC_REQUEST = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); send=(Button) findViewById(R.id.emailsendbutton); address=(EditText) findViewById(R.id.emailaddress); subject=(EditText) findViewById(R.id.emailsubject); emailtext=(EditText) findViewById(R.id.emailtext); Button camera = (Button) findViewById(R.id.button1); camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0){ Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); } }); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0){ Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_EMAIL, new String[]{"fake@fake.edu"}); i.putExtra(Intent.EXTRA_SUBJECT,"On The Job"); //Log.d("URI@!@#!#!@##!", Uri.fromFile(pic).toString() + " " + pic.exists()); i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic)); i.setType("image/png"); startActivity(Intent.createChooser(i,"Share you on the jobing")); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_PIC_REQUEST) { thumbnail = (Bitmap) data.getExtras().get("data"); ImageView image = (ImageView) findViewById(R.id.imageView1); image.setImageBitmap(thumbnail); try { File root = Environment.getExternalStorageDirectory(); if (root.canWrite()){ pic = new File(root, "pic.png"); FileOutputStream out = new FileOutputStream(pic); thumbnail.compress(CompressFormat.PNG, 100, out); out.flush(); out.close(); } } catch (IOException e) { Log.e("BROKEN", "Could not write file " + e.getMessage()); } } } A: try this Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_EMAIL , new String[]{"123@gmail.com"}); i.putExtra(Intent.EXTRA_SUBJECT, " report"); i.putExtra(Intent.EXTRA_TEXT , "PFA"); i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(destinationFile));//pngFile startActivity(Intent.createChooser(i, "Send mail...")); A: try this send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_EMAIL, new String[]{"fake@fake.edu"}); i.putExtra(Intent.EXTRA_SUBJECT, "On The Job"); //Log.d("URI@!@#!#!@##!", Uri.fromFile(pic).toString() + " " + pic.exists()); if(pic != null) { i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));} i.setType("image/png"); i.setType("message/rfc822"); startActivity(Intent.createChooser(i, "Share you on the jobing")); } }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7604498", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: MySQL Query for Tagging System, Selecting Used Tags Only I have a tagging system implemented in PHP and MySQL, with the following tables: Table: blog_tags * *tag_id *tag_name Table: blog_tags_assoc * *tag_assoc_id *article_id *tag_id Table: blog_articles * *article_id *article_title *article_content I have them all linked using the Many to Many relationship (reference to something similar: How to store tags in MySQL tags, one field in total or one filed for each tag?) What I'm trying to do now is make a MySQL query that selects all the tags from blog_tags that have actually been referenced by the articles in blog_articles. So far, I know that "HAVING" is something I might use…but I'm not sure how? Any ideas or suggestions would be most welcome. Thanks! A: If you only want to know the tags that have been used in articles, then you can simply do this: SELECT DISTINCT tag_id, tag_name FROM blog_tags INNER JOIN blog_tags_assoc USING ( tag_id ); A: This will get a tag name as well as a count of articles that tag has been used. SELECT `blog_tags`.`tag_name`, count(*) AS `blog_article_count` FROM `blog_tags` JOIN `blog_tags_assoc` ON `blog_tags`.`tag_id`=`blog_tags_assoc`.`tag_id` JOIN `blog_articles` ON `blog_articles`.`article_id`=`blog_tags_assoc`.`article_id` GROUP BY `blog_tags`.`tag_name`
{ "language": "en", "url": "https://stackoverflow.com/questions/7604509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: NSPopover: Class Unavailable (NSPopover on Mac OS X versions prior to 10.7) I want to update my App and switch to Lion only, since I'm using the new NSPopover class. I set my deployment target and the base SDK to 10.7 but I'm still getting the error message: NSPopover: Class Unavailable (NSPopover on Mac OS X versions prior to 10.7) I also set the XIB, where I'm using NSPopover to Interface Builder 4.1 and its SDK to 10.7. What am I doing wrong? Edit: I forgot to mention that the project successfully builds and it runs and works fine with the popover! There is only that annoying Error which is showing up constantly. I don't know if it affects the submission to the App Store… A: I can't replicate the problem you are getting. If I create a xib file with a popover in it, then set the Deployment setting of that xib in interface builder to 10.6, I get the same error as you. When I change it to either 10.7 or the Project SDK version, it disappears. This happens either with a brand new project or an old one that I dug out and "modernised" using the options that come up in Xcode. I have tried changing all of the deployment targets in the project but nothing actually makes the error come up except for the setting in interface builder. It might be worth you opening the offending xib file in a text editor and looking for the following: <int key="IBDocument.SystemTarget">1070</int> If this is a different value or it is repeated or missing, that may be your problem. If you have multiple localised versions of the xib, you will need to change the setting in all versions. Failing that, I think all you can do is copy out the contents of the xib into a new file, which may or may not be a massive pain depending on how complicated it is. I hope some of this helps, I imagine this is a very frustrating problem. Oh, also, if your app is Lion-only, you can set the architecture to 64 bit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7604511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Out of memory Exception when converting video file I'm converting a Video file to string using Base64 encoding. try { encodedString =Base64.encodeBytes((getBytesFromFile(new File(Description.PATH))),Base64.GZIP); } catch (IOException e) { e.printStackTrace(); } When i'm converting 60 sec video, I'm getting out of memory exception.. 09-30 04:52:52.322: ERROR/AndroidRuntime(29995): Caused by: java.lang.OutOfMemoryError 09-30 04:52:52.322: ERROR/AndroidRuntime(29995): at java.nio.CharArrayBuffer.<init>(CharArrayBuffer.java:43) 09-30 04:52:52.322: ERROR/AndroidRuntime(29995): at java.nio.ReadWriteCharArrayBuffer.<init>(ReadWriteCharArrayBuffer.java:47) 09-30 04:52:52.322: ERROR/AndroidRuntime(29995): at java.nio.BufferFactory.newCharBuffer(BufferFactory.java:82) 09-30 04:52:52.322: ERROR/AndroidRuntime(29995): at java.nio.CharBuffer.allocate(CharBuffer.java:53) 09-30 04:52:52.322: ERROR/AndroidRuntime(29995): at java.nio.charset.CharsetDecoder.decode(CharsetDecoder.java:214) 09-30 04:52:52.322: ERROR/AndroidRuntime(29995): at java.nio.charset.Charset.decode(Charset.java:730) Please let me know how to solve this issue. Thanks in advance A: I think you should use encodeToString instead of encodeBytes().
{ "language": "en", "url": "https://stackoverflow.com/questions/7604518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django: CSRF with AJAX I have a problem/bug found? in AJAX with CSRF. I don't use {% csrf_token %} at all. I use only AJAX forms so - there is no cookie set for csrf. In taht case - enter link description here is useless :( I can use get_token to generate it, but I have to put it in all my sites so it has no sense. How can I make that cookie without using csrf tag? A: Any random 32-digit alphanumeric string will work as the token. Simply save it in a cookie named "csrftoken", and then submit it with your post. This will auto generate a token or re-use an existing one. It will handle all form submits on the page. If you have off-site forms you'll need to make sure they don't run this code. <script> $(document).on('submit', 'form[method=post]', function(){ if(!document.cookie.match('csrftoken=([a-zA-Z0-9]{32})')){ for(var c = ''; c.length < 32;) c += Math.random().toString(36).substr(2, 1) document.cookie = 'csrftoken=' + c + '; path=/' } if(!this.csrfmiddlewaretoken) $(this).append('<input type="hidden" name="csrfmiddlewaretoken">') $(this.csrfmiddlewaretoken).val(document.cookie.match('csrftoken=([a-zA-Z0-9]{32})')[1]) }) </script> requires jQuery 1.7+ A: You can use the csrf_exempt decorator on your view https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.csrf_exempt A: If you imprint csrf token into some JS variable on server side, then later you can send custom HTTP header that will be recognized by Django X-CSRFToken: {{ csrf_token }}} also see that Q&A: Django CSRF failure on ajax post requests on Opera only Example of working request: POST /main/uploadpage/ HTTP/1.1 Host: 127.0.0.1:8000 Connection: keep-alive Content-Length: 505853 Origin: http://127.0.0.1:8000 X-File-Name: Screen Shot 2013-05-12 at 5.13.34 PM (2).png User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31 Content-Type: image/png Cache-Control: no-cache X-Requested-With: XMLHttpRequest X-CSRFToken: 1kCcyDzpHIxicSzCqvuXUMbpGaXvFpCZ Accept: */* Referer: http://127.0.0.1:8000/main/uploadpage/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 A: have u consider disabling CSRF at all? to do that just remove the middleware : 'django.middleware.csrf.CsrfViewMiddleware',
{ "language": "en", "url": "https://stackoverflow.com/questions/7604519", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }