text
stringlengths
8
267k
meta
dict
Q: How do I draw an outline on a specific wedge of a flex pie chart? I want to have a different coloured stroke (outline) used on the pie wedge under the mouse from the outline used on the other wedges. The PieSeriesItem referenced by the mouseover event doesn't have a stroke parameter, and it looks like it is an all or nothing deal with the outline colour on the whole pie. Is there any way of specifying the stroke parameter on a specific wedge? A: It looks like this is done by specifying an itemRenderer on the PieSeries. The default is the WedgeItemRenderer, so subclassing will allow overriding the line definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does Castle Windsor throw a ComponentNotFoundException in this simple example? I'm just getting started with the Castle Windsor IoC, and I'm having a hard time following the examples. Can somebody please explain why this simple console application fails? I must be missing something easy. Thanks. using System; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Castle.Windsor.Installer; namespace CastleTest { public interface ISomething { void DoSomething(); } public class Something : ISomething { public void DoSomething() { Console.WriteLine("Hello World"); } } public class SomethingInstaller : IWindsorInstaller { public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(AllTypes.FromThisAssembly().BasedOn<ISomething>()); } } class Program { static void Main() { using (var container = new WindsorContainer()) { container.Install(FromAssembly.This()); // the following line throws a ComponentNotFoundException var something = container.Resolve<ISomething>(); something.DoSomething(); } } } } A: Nevermind, I found the problem. The installer needs to register the service. This fixed it: public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(AllTypes.FromThisAssembly().BasedOn<ISomething>() .WithService.DefaultInterface() ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7589662", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql Simple Query question I wrote out this Mysql query, but return a lot of blank fields for the customers_telephone table since it was never a required field. I would like to return some dummy data on my query (without inserting it into the database) if the field is NULL. I know MySQL uses if clauses but I think it's only for creating databases or ... ? here's my stamp SELECT orders.orders_id AS recipient_id, delivery_company, delivery_street_address, delivery_city, delivery_postcode, delivery_state, delivery_country, customers_telephone FROM orders, orders_products WHERE orders.orders_id = orders_products.orders_id AND products_id = 416 ORDER BY `orders`.`orders_id` DESC UPDATE I tried doing this, but it still is not working, maybe I did it in the wrong place? SELECT orders.orders_id AS recipient_id, delivery_company, delivery_street_address, delivery_city, delivery_postcode, delivery_state, delivery_country, IFNULL(customers_telephone, 'no number') AS customers_number FROM orders, orders_products WHERE orders.orders_id = orders_products.orders_id AND products_id = 416 ORDER BY `orders`.`orders_id` DESC Returns recipient_id delivery_company delivery_street_address delivery_city delivery_postcode delivery_state delivery_country number 191743 This Chick Bakes 31-31 48th Ave #B Long Island City 11101 NY United States 917.848.6437 191724 44 Miraflores Ave (studio) San Rafael 94901 CA United States 191723 397 South River Street Wilkes-Barre 18702 PA United States A: Use the IFNULL function to provide a value if the field is NULL: IFNULL(customers_telephone, 'dummydata') AS customers_telephone IFNULL is a non-standard MySQL extension. The standard way is to use the COALESCE function for this purpose. COALESCE is also supported by MySQL, but it is slightly slower than IFNULL, though it probably won't matter here. A: One way SELECT COALESCE(customers_telephone, 'no number') FROM ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7589667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: shutting down android sub activity I'm trying to implement a sub-activity to play an mp4 movie using MediaPlayer. In trying to finish the activity with setResult and finish inside of onCompletion proved problematic. Then I started searching and searching for examples of closing a sub activity and learned that it must finish from the UI thread. I simplified the sub activity removing most the media player and moved the finish code into onCreate to at least get it to work from there. This works: // calls onActivityResult, graceful exit, etc Log.d("TAG", Thread.currentThread().getName()); // outputs "main" signMovieActivity.this.setResult(99); signMovieActivity.this.finish(); So, how do I do this from onCompletion? The best suggestion I've found so far is to use a handler to do it however this code inside of onCreate works just as poorly as calling finish from the mediaplayer callback: Handler handler = new Handler(); handler.post(new Runnable() { public void run() { Log.d("TAG", Thread.currentThread().getName()); // outputs "main" signMovieActivity.this.setResult(99); signMovieActivity.this.finish(); // Full meltdown starting with "I/AndroidRuntime(26581): AndroidRuntime onExit calling exit(0)" } }); Please put me back on track! Here is logcat output when finish() is at the end of onCompletion(): D/movie( 2144): onCompletion called D/movie( 2144): thread is main I/FFPlayer( 1169): tm 05460 [InputDemux] Start to wait a/v done 2 2 I/FFPlayer( 1169): tm 00858 [InputDemux] Start to wait a/v done 2 2 I/FFPlayer( 1169): tm 01216 [AudioProc] thread exited I/FFPlayer( 1169): tm 00902 [InputDemux] Start to wait a/v done 0 2 I/FFPlayer( 1169): tm 300655 [VideoPlay] thread exited I/FFPlayer( 1169): tm 00473 [VideoProc] thread exited I/FFPlayer( 1169): tm 03737 [inputDemux] thread exited. I/FFPlayer( 1169): tm 85592 FFPlayer deleted, mEngine = 0x3c148 this = 0xc860, Count = 0 D/dalvikvm( 2026): GC_EXPLICIT freed 823 objects / 57624 bytes in 55ms D/dalvikvm( 2037): GC_EXPLICIT freed 618 objects / 42128 bytes in 71ms <<< finish called here >>> I/AndroidRuntime( 2144): AndroidRuntime onExit calling exit(0) I/ActivityManager( 1357): Process com.sign (pid 2144) has died. I/WindowManagerService( 1357): WIN DEATH: Window{4617dc40 com.sign/com.sign.signActivity paused=false} I/ActivityManager( 1357): Start proc com.sign for activity com.sign/.signActivity: pid=2165 uid=10126 gids={3003, 1015} I/WindowManagerService( 1357): WIN DEATH: Window{461a3f90 com.sign/com.sign.signMovieActivity paused=true} I/WindowManagerService( 1357): WIN DEATH: Window{460f5a10 SurfaceView paused=false} <<< entire application restarts >>> A: I don't see any problem in calling finish() in the onCompletion() method. I do that myself in a custom video player I made using MediaPlayer, and it works just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Boost.Regex vs C++11 Regex Could someone explain the differences between the two? Which would be better to learn right now? How would knowledge transfer from one to the other and vice-versa? A: One major difference is, that C++11 does not provide the Perl syntax for regular expressions. So, if you tend to use Perl syntax you have to use the Boost::Regex library. A: The boost regex library made it into C++0x so I'm guessing it will slowly be removed from boost. However, using boost is nice because you can still use it with compilers without C++0x support. So it's really up to you. A: At least in Visual Studio 2013 this and related names (cmatch, regex_match) are the same in both namespaces. They also have the same (or similar?) interface. So you can just change namespace and the same code will be compiled with another regex without warning and errors. And it should work the same of course. P.S. I would prefer std::regex since it is part of C++11 and boost::regex is a third-party library. I'm sure few years later, boost will remove support for boost::regex.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: PHP curl authentication question I have my own site that store login info only in session. I need to use CURL to submit form, but trick is you need to login first before you can access page with form. So i tried to create two requests but it dont seem to work as intended even though i do get login on login page page with form still shows i am logged out. //add data to be posted $post_string1 = "username=test&password=1234"; $post_string2 = "value1=555"; //create cURL connection $curl_connection1 = curl_init("http://".$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['PHP_SELF']), '/\\')."/login.php"); $curl_connection2 = curl_init("http://".$_SERVER['HTTP_HOST'].rtrim(dirname($_SERVER['PHP_SELF']), '/\\')."/formpage.php"); //create the multiple cURL handle //set options curl_setopt($curl_connection1, CURLOPT_POST, 1); curl_setopt($curl_connection1, CURLOPT_POSTFIELDS, $post_string1); curl_setopt ($curl_connection1, CURLOPT_COOKIEJAR, 'cookie.txt'); curl_setopt($curl_connection1, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($curl_connection1, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($curl_connection1, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection1, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection1, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curl_connection2, CURLOPT_POST, 1); curl_setopt($curl_connection2, CURLOPT_POSTFIELDS, $post_string2); curl_setopt ($curl_connection2, CURLOPT_COOKIEJAR, 'cookie.txt'); curl_setopt($curl_connection2, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($curl_connection2, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); curl_setopt($curl_connection2, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection2, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection2, CURLOPT_FOLLOWLOCATION, 1); $mh = curl_multi_init(); curl_multi_add_handle($mh,$curl_connection1); curl_multi_add_handle($mh,$curl_connection2); $active = null; do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); while ($active && $mrc == CURLM_OK) { if (curl_multi_select($mh) != -1) { do { $mrc = curl_multi_exec($mh, $active); } while ($mrc == CURLM_CALL_MULTI_PERFORM); } } //close the handles curl_multi_remove_handle($mh, $ch1); curl_multi_remove_handle($mh, $ch2); curl_multi_close($mh); //show information regarding the request print_r(curl_getinfo($curl_connection1)); echo curl_errno($curl_connection1) . '-' . curl_error($curl_connection1); //show information regarding the request print_r(curl_getinfo($curl_connection2)); echo curl_errno($curl_connection2) . '-' . curl_error($curl_connection2); Cookie.txt is writable and contains session, here's the response: Array ( [url] => http://mysite.com/login.php [content_type] => text/html; charset=UTF-8 [http_code] => 200 [header_size] => 762 [request_size] => 404 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 1 [total_time] => 0.270866 [namelookup_time] => 2.9E-05 [connect_time] => 0.000118 [pretransfer_time] => 0.000193 [size_upload] => 0 [size_download] => 132955 [speed_download] => 490851 [speed_upload] => 0 [download_content_length] => 0 [upload_content_length] => 0 [starttransfer_time] => 0.250872 [redirect_time] => 0.01623 ) 0-Array ( [url] => http://mysite.com/formpage.php?login=destroyed [content_type] => text/html; charset=UTF-8 [http_code] => 200 [header_size] => 786 [request_size] => 415 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 1 [total_time] => 0.056873 [namelookup_time] => 2.6E-05 [connect_time] => 9.9E-05 [pretransfer_time] => 0.000198 [size_upload] => 0 [size_download] => 9790 [speed_download] => 172137 [speed_upload] => 0 [download_content_length] => 1 [upload_content_length] => 0 [starttransfer_time] => 0.013818 [redirect_time] => 0.042138 A: Don't use two parallel curl handles for this. Depending on network conditions, your SECOND curl request could actually reach the server first, BEFORE the login request. As well, CURL reads the cookie files at the time the request is executed. Both of your requests will fire off at basically the same time, BEFORE any login cookies are returned from the server. So both requests will be in a "not logged in" state. Use a SINGLE curl handle, and do each invocation in sequence> $ch = new CURL(); ... set up login ... ... do login ... ... set options for second post ... do second post ... Such a sequence guarantees that the login request (and cookie) will be completed and available before you start on the second request.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Codeigniter: Can't seem to get my edit to work So basically I am trying to combine what I found in these two tutorials to make a working CRUD: http://fwebde.com/php/simple-crud-with-codeigniter/ http://ie.mirror.twsweb-int.com/codeigniter/user_guide/tutorial/create_news_items.html Basically, where I am is that I can get the edit page to render the appropriate item details in the form but whenever I press submit, I get a 404 error and the table doesn't get updated. My edit.php that is tied to my news controller: <?php echo validation_errors(); ?> <h2>Edit a news item</h2> <?php echo form_open('news/edit') ?> <p> <label for="title">Title</label> <?php echo form_input('title',$news_item['title']); ?> </p> <p> <label for="text">Text</label> <?php echo form_textarea('text',$news_item['text']); ?> </p> <?php echo form_hidden($news_item['id']); ?> <p> <?php echo form_submit('submit', 'Save Changes'); ?> </p> <?php echo form_close(); ?> </br> </br> <a href='<?php echo site_url('news');?>'>Back</a> My news controller on the edit method: public function edit($slug) { $data['news_item'] = $this->news_model->get_news($slug); if (empty($data['news_item'])) { show_404(); } $data['title'] = 'Edit: '.$data['news_item']['title']; $this->load->helper('form'); $this->load->library('form_validation'); $this->form_validation->set_rules('title', 'Title', 'required'); $this->form_validation->set_rules('text', 'text', 'required'); if($this->form_validation->run() === FALSE) { $this->load->view('templates/header', $data); $this->load->view('news/edit', $data); $this->load->view('templates/footer'); } else { $this->news_model->update_news( $this->input->post('id'), $this->input->post('title'), $this->input->post('text')); $this->load->view('news/success'); } } Appropriate methods in my model: public function get_news($slug = FALSE) { if ($slug === FALSE) { $query = $this->db->get('news'); return $query->result_array(); } $query = $this->db->get_where('news', array('slug' => $slug)); return $query->row_array(); } public function set_news() { $this->load->helper('url'); $slug = url_title($this->input->post('title'), 'dash', TRUE); $data = array( 'title' => $this->input->post('title'), 'slug' => $slug, 'text' => $this->input->post('text') ); return $this->db->insert('news', $data); } public function update_news($id, $title, $content) { $data = array( 'title' => $title, 'content' => $content ); $this->db->where('id', $id); $this->db->update('news', $data); } My routes: $route['news/edit/(:any)'] = 'news/edit/$1'; $route['news/create'] = 'news/create'; $route['news/(:any)'] = 'news/view/$1'; $route['news'] = 'news'; A: You are submitting the form to the edit method which is expecting an item id $slug, you can change your view to the following: <?php echo form_open('news/edit/' . $news_item['id']) ?> A: Basically there were a couple of errors: 1) ifaour's suggestion 2) passing the primary key and slug around as parameters to be used for later 3) forgot I had changed the table column (forgot I had renamed the content column as text) Model in its final form: public function get_news($slug = FALSE) { if ($slug === FALSE) { $query = $this->db->get('news'); return $query->result_array(); } $query = $this->db->get_where('news', array('slug' => $slug)); return $query->row_array(); } public function set_news() { $this->load->helper('url'); $slug = url_title($this->input->post('title'), 'dash', TRUE); $data = array( 'title' => $this->input->post('title'), 'slug' => $slug, 'text' => $this->input->post('text') ); return $this->db->insert('news', $data); } public function update_news($id, $title, $content) { $data = array( 'title' => $title, 'text' => $content ); $this->db->where('id', $id); $this->db->update('news', $data); } Edit in its final form: <h2>Edit a news item</h2> <a href="<?php echo site_url('news/delete/'.$news_item['id']); ?>">Delete this article</a> <?php echo validation_errors(); ?> <?php echo form_open('news/edit/'.$news_item['slug']) ?> <p> <label for="title">Title</label> <?php echo form_input('title',$news_item['title']); ?> </p> <p> <label for="text">Text</label> <?php echo form_textarea('text',$news_item['text']); ?> </p> <?php echo form_hidden('slug',$news_item['slug']); ?> <?php echo form_hidden('id',$news_item['id']); ?> <p> <?php echo form_submit('submit', 'Save Changes'); ?> </p> <?php echo form_close(); ?> </br> </br> <a href='<?php echo site_url('news');?>'>Back</a> news controller edit method in final form: public function edit($slug) { $data['news_item'] = $this->news_model->get_news($slug); if (empty($data['news_item'])) { show_404(); } $data['title'] = 'Edit: '.$data['news_item']['title']; $this->load->helper('form'); $this->load->library('form_validation'); $this->form_validation->set_rules('title', 'Title', 'required'); $this->form_validation->set_rules('text', 'text', 'required'); if($this->form_validation->run() === FALSE) { $this->load->view('templates/header', $data); $this->load->view('news/edit', $data); $this->load->view('templates/footer'); } else { $this->news_model->update_news( $this->input->post('id'), $this->input->post('title'), $this->input->post('text')); $data['news_item'] = $this->news_model->get_news($slug); $this->load->view('templates/header', $data); $this->load->view('news/success'); $this->load->view('news/edit', $data); $this->load->view('templates/header', $data); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7589675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Autotools include path I have a directory structure like Makefile.am Configure.ac src/ hello.c Makefile.am include/ hello.h How to specify the include path in Makefile.am of src so that it includes header files from include/ dir as well as c file depends on header file. So if I modify any .h file it force to recompile .cc file. Defining AM_CPPFLAGS' is giving warning configure.ac:5: warning: macro `AM_CPPFLAGS' not found in library A: In src/Makefile.am, write: AM_CPPFLAGS = -I$(top_srcdir)/include bin_PROGRAMS = hello hello_SOURCES = hello.c There is no need to mark the dependency between hello.c and hello.h, it will be recorded automatically the first time you build your project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Weird control characters in ruby test output inside emacs buffer I'm using ruby-test to run rails tests from inside emacs into the *Ruby-Test* buffer. It works great except that the output is cluttered with ascii color-control characters (not sure what the right terminology is). Example: MyTest: ^[[32m PASS^[[0m Test Passed (2.85s) If I run the test in a terminal that shows up as a green "PASS". Is there something I can do to get the colors to show up in my output buffer? There's a related question about getting color for commands run with M-|, but I couldn't figure out how to adapt it for a generic buffer. emacs shell command output not showing ANSI colors but the code A: In order to get Emacs to guess ansi-color mode for regular buffers, use: (require 'tty-format) (add-hook 'find-file-hooks 'tty-format-guess) You need to download the tty-format package first. See: https://unix.stackexchange.com/questions/19494/how-to-colorize-text-in-emacs Looking at the code, it looks like the author's made a bunch of questionable decisions, but maybe this will help: (defadvice ruby-test-runner-sentinel (after add-ansi-colors activate compile) (ansi-color-apply-on-region (point-min) (point-max))) A: Do you have ansi-color.el installed and active? See this also. A: Try running the ansi-color-for-coming-mode-on function in this buffer
{ "language": "en", "url": "https://stackoverflow.com/questions/7589677", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: execute sql returned in sql query I have a query that runs against a sql server database that produces a sql statement for each row of the query returned. EG. DROP PROCEDURE dbo.[Proc1] DROP PROCEDURE dbo.[Proc2] etc In the same script, how can I execute the sql returned in the query? A: Check out sp_executesql A: One way is, you'll have to iterate through your result set and use sp_executesql. Just curious though, what are you trying to accomplish A: Dump the results into a variable of type varchar(max) or nvarchar(max) and then EXEC them -- Create a terrible, horrible cursor to run the statements -- You have just now killed a kitten DECLARE Csr cursor for SELECT P.name AS proc_name , schema_name(P.schema_id) AS schemaname FROM sys.procedures P DECLARE @query varchar(max), @proc_name sysname, @schema sysname OPEN Csr FETCH NEXT FROM Csr INTO @proc_name, @schema WHILE (@@fetch_status <> -1) BEGIN IF (@@fetch_status <> -2) BEGIN BEGIN TRY -- build out the drop statement, may not be necc SET @query = 'DROP PROCEDURE' + QUOTENAME(@schema) + '.' + QUOTENAME(@proc_name) -- Actually run the dynamic query EXECUTE(@query) END TRY BEGIN CATCH -- Be good and note what failed, fix this manually PRINT 'This query failed' PRINT @query END CATCH FETCH NEXT FROM Csr INTO @proc_name, @schema END END CLOSE Csr DEALLOCATE Csr A: What you need to do is have your query output into a variable. If you are using a stored procedure, then specify an output paramater of varchar. Then when you call the stored procedure to generate the SQL query just pass that varchar variable to sp_executesql.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Counting values in table joined several times I have a problem counting a table joined several times. The question table : +----+----------+ | id | question | +----+----------+ | 1 | Foo? | +----+----------+ The answer one : +----+-------------+--------+ | id | question_id | choice | +----+-------------+--------+ | 1 | 1 | 1 | | 2 | 1 | 1 | | 3 | 1 | 1 | | 4 | 1 | 2 | | 5 | 1 | 3 | | 6 | 1 | 3 | +----+-------------+--------+ The expected result : +----------+-------+-------+-------+ | question | num_1 | num_2 | num_3 | +----------+-------+-------+-------+ | Foo? | 3 | 1 | 2 | +----------+-------+-------+-------+ The (failing) query and its result : SELECT q.question AS question, COUNT(a1.id) AS num_1, COUNT(a2.id) AS num_2, COUNT(a3.id) AS num_3 FROM question q LEFT JOIN answer a1 ON a1.question_id = q.id AND a1.choice = 1 LEFT JOIN answer a2 ON a2.question_id = q.id AND a2.choice = 2 LEFT JOIN answer a3 ON a3.question_id = q.id AND a3.choice = 3 GROUP BY q.id +----------+-------+-------+-------+ | question | num_1 | num_2 | num_3 | +----------+-------+-------+-------+ | Foo? | 6 | 6 | 6 | +----------+-------+-------+-------+ I don't understand why I get this result. Can you help me? A: Because choice = 1 gives 3 rows, choice = 2 gives 1 row, choice = 3 gives 2 rows and 1 * 2 * 3 = 6. if you remove the group by and aggregates and look at the results it should be clear. You can use SELECT q.question AS question, COUNT(CASE WHEN a.choice = 1 THEN 1 END) AS num_1, COUNT(CASE WHEN a.choice = 2 THEN 1 END) AS num_2, COUNT(CASE WHEN a.choice = 3 THEN 1 END) AS num_3 FROM question q LEFT JOIN answer a ON a.question_id = q.id AND a.choice IN (1,2,3) GROUP BY q.id, q.question A: If you run your query without the counts and grouping, you'll see you get results like this: +------+------+------+------+ | q | num1 | num2 | num3 | +------+------+------+------+ | foo | 1 | 4 | 5 | | foo | 1 | 4 | 6 | | foo | 2 | 4 | 5 | | foo | 2 | 4 | 6 | | foo | 3 | 4 | 5 | | foo | 3 | 4 | 6 | +------+------+------+------+ As expected, 6 rows, so each aliased field will give you a count of 6. Martin Smith's got the right answer above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Java - Program accepting negative numbers when it shouldn't I have to make a program that uses nested loops to collect data and calculate the average rainfall over a period of years. First, the program should ask for the number of years. (The outer loop will iterate once for each year.) The inner loop will iterate 12 times, once for each month. Each iteration of the inner loop will ask the user for inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period. Input Validation: Do not accept a number less than 1 for the number of years. Do not accept negative numbers for the monthly rainfall. I have finished the program, but there is a tiny problem: when it asks for the inches, if I enter 1 for the year it is going to to ask to me input inches 12 times. If I put in a negative number first, it will tell me the number is invalid and then loop again and ask me to put a number equal to or more than zero. Now if I input a series of numbers that are >=0 and then put a negative number, it does not tell me that I cannot put a negative number. It is not supposed to accept negative numbers at all, but it does when the previous 2 or more number were >= zero. import java.util.Scanner; public class Averagerainfallteller { /** * This program tells asks the user to enter an amount of years and then asks * the user to given the amount of inches that fell for every month during * those years and then give the average rain fall, total inches of rain and * total months. */ public static void main(String[] args) { double totalInches = 0; double totalMonths = 0; double avgInches = 0; double inches = 0; Scanner kb = new Scanner(System.in); System.out.println(" PLease enter the number of years"); int numYears = kb.nextInt(); while (!(numYears >= 1)) { System.out.println(" PLease enter the number that is more than or equal to one."); numYears = kb.nextInt(); } for (int years = 1; years <= numYears; years++) { for (int months = 1; months <= 12; months++) { System.out.println("How many inches fell for Year: " + years + ", during Month: " + months + "? "); inches += kb.nextDouble(); while (!(inches >= 0)) { System.out.println("PLease enter the number that is more than or equal to zero."); System.out.println("How many inches fell for Year: " + years + ", during Month: " + months + "? "); inches += kb.nextDouble(); } } } totalMonths = 12 * numYears; avgInches = totalInches / totalMonths; System.out.println(".....HERE ARE THE RESULTS....."); System.out.println(""); try { Thread.currentThread().sleep(1000); } catch (Exception e) { } System.out.println(" Total inches is " + totalInches); System.out.println(""); try { Thread.currentThread().sleep(1000); } catch (Exception e) { } System.out.println(" Average Inches is " + avgInches); System.out.println(""); try { Thread.currentThread().sleep(1000); } catch (Exception e) { } System.out.println(" Total months is " + totalMonths); } } A: Don't do inches +=kb.nextDouble(); instead do input = kb.nextDouble(); if input > 0 then inches += input; otherwise loop. This should help you to filter out negative numbers before your arithmetic logic. A: The problem is this: inches += kb.nextDouble(); Instead try this: System.out.println("How many inches fell for Year: "+years+", during Month: "+months+ "? "); inches = kb.nextDouble(); //HERE while(!(inches>=0)) { System.out.println("PLease enter the number that is more than or equal to zero."); System.out.println("How many inches fell for Year: "+years+", during Month: "+months+ "? "); inches =kb.nextDouble(); //HERE } totalInches += inches; //HERE Basically you were continuing to add the number input by the user to the same variable inches continuously. Also you seem to use totalInches without initializing it, so it would always be zero. A: Make sure a new value for inches (non negative) is entered and than add it up to totalInches. for (int months = 1; months <= 12; months++) { do { System.out.println("How many inches fell for Year: " + years + ", during Month: " + months + "? "); inches = kb.nextDouble(); }while(inches < 0); totalInches += inches; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7589692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: configure akka debugging Using Akka 1.0 I cannot stop stdout-debug-output although I have set the event-handler-level to ERROR in my akka.conf which is definetely being read correctly. My sys-out is polluted with these messages: [akka:event-driven:dispatcher:global-3] DEBUG akka.actor.Actor$ - Scheduling timeout for Actor[pkg.Caller] A: Akka 1.0 doesn't use event handler: https://github.com/jboner/akka/blob/v1.0/config/akka-reference.conf You need to change your logback config.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using qmake to generate a makefile that has FLTK fluild files? I was wondering if anyone might have an idea how to use qmake to generate a program that has FLTK fluid files ? I have foo.fl that generate fl.cxx and fl.hxx which get compiled. I don't know how or if it is even possible to get qmake to do this pre-processing step as well as add the sources to the list that needs to be compiled. I was hoping someone might have a suggestion. Thanks, Danny A: I think you want to use the qmake variable QMAKE_EXTRA_COMPILERS. See QMake's Documentation on Configuring Its Environment for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OnPreviewTextInput not always providing Text We have an existing application we are trying to replace with a new WPF application. One of the controls we use in the legacy application has a specialized behavior where the control redirects any text input by the user to be processed externally. After which the result is updated programmatically back into the control. (the control behaves similarly to a read-only TextBox in that the user is not allowed edit text directly in the control; any text the user types is redirected before it is shown in the control) We settled on using the OnPreviewTextInput event to redirect e.Text and mark the event as e.Handled. This worked using English input as well as the Microsoft Japanese IME. But when we tried using the Microsoft Korean IME, e.Text comes through as an empty string... Any thoughts on why it would work for Japanese, but not for Korean?
{ "language": "en", "url": "https://stackoverflow.com/questions/7589701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mainline DHT bootstrap process Can somebody clarify me the statement from the specification of mainline DHT? Upon inserting the first node into its routing table and when starting up thereafter, the node should attempt to find the closest nodes in the DHT to itself. It does this by issuing find_node messages to closer and closer nodes until it cannot find any closer. What does "until it cannot find any closer" mean? When my program start to send find_node messages it has empty set of nodes. Each response to find_node message returns about 8 dht nodes. My program collects them in the list. When must my program stop sending find node messages? I think that it must stop sending when it will receive the set of dht nodes all elements of which are in the list of already collected nodes? Am I right? Thank you in advance. A: Mainline DHT is a kademlia implementation, for details, see the paper. From the 8 nodes you receive, sort them by their node-id's closeness to your own ID, then send find_node to the 3 top ones (the 3 closest to you). You will then receive 8 x 3 more nodes, insert them in your node list, still ordered by how close the nodes are to you. Keep sending find_node messages to the 3 top nodes (ignoring ones you've already sent messages to), until the nodes you get back are already in your list. i.e. the termination condition is that you have sent a message to all 8 nodes closest to you (at the top of the list). As the paper explains, the distance metric is XOR. To calculate how far away your node-ID is from another node's, you XOR the node-IDs. The lower the result is, the closer the nodes are to each other. In real life you might want to do this a bit more sophisticated, by keeping 3 outstanding requests at any given time and temporarily open up more outstanding requests half way through timeouts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Learning C# and ASP.NET MVC for a Django/Pylons programmer We have a project coming down the line that's likely going to be in ASP.NET of some sort. I really hope this means ASP.NET MVC :) I've created a SOAP web service and a small website in ASP.NET (non-MVC) before, so I'm familiar with the bare basics of C#, ASP.NET, and LINQ (except templates still confuse me significantly). I am however a rather advanced Python programmer, and I've had a ton of experience in Django and Pylons. What's the best way to translate this knowledge to ASP.NET? I'm especially interested in anything that involves the latest versions of .NET, and in best practices for .NET, Visual Studio, etc. A: Knowing Django will put you in a good position to use ASP.NET MVC - you'll already know about the roles of Models and Views etc. Python is generally a higher level language than C# so you might find that it can be less powerful to use. On the whole I'd say there isn't much between them though. The best advice I could give would be to read Pro ASP.NET MVC Framework (Steve Sanderson). This book goes beyond simply teaching the reader about the features of the framework but clearly demonstrates them in context and gives clear examples of what could be considered 'best practice' (subjective, but I largely agree with the techniques he advocates). I'm actually going the inverse at the moment. I've been using ASP.NET MVC for a couple of years but am moving towards Django for some upcoming projects. A: I'm a big fan of PluralSight training. As a supplement to the Sanderson book, not a replacement for. But for $29/month you won't find better training materials. You can watch ASP.Net MVC courses, C# courses and many other things. http://www.pluralsight-training.net/microsoft/
{ "language": "en", "url": "https://stackoverflow.com/questions/7589721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Social Network Database Design - Friend/Block Relationships I'm working on a social networking site and need users to be able to friend each other and/or block each other. The way I see it, 2 users can either be Friend, Pending, Block, or NULL. I'd like to have a single view that shows a single row for each confirmed relationship. My view properly shows the relationship but I had to do a workaround to only show 1 row/relationship without unioning the table with itself and swapping the order or Requestor and Requestee. Anybody have any ideas about how to clean this up? Thanks, - Greg Relationship Table: Requestor (int) | Requestee (int) | ApprovedTimestamp (smalldatetime) | IsBlock (bit) vwRelationship View: SELECT DISTINCT CASE WHEN f.Requestor < f.Requestee THEN f.Requestor ELSE f.Requestee END AS UserA, CASE WHEN f.Requestor < f.Requestee THEN f.Requestee ELSE f.Requestor END AS UserB, CASE WHEN b.Requestor IS NULL AND b.Requestee IS NULL THEN CASE WHEN f.AcceptedTimestamp IS NULL THEN 'Pending' ELSE 'Friend' END ELSE 'Block' END AS Type FROM dbo.Relationship AS f LEFT OUTER JOIN (SELECT Requestor, Requestee FROM dbo.Relationship WHERE (IsBlock = 1)) AS b ON f.Requestor = b.Requestor AND f.Requestee = b.Requestee OR f.Requestor = b.Requestee AND f.Requestee = b.Requestor Example Query: Select Type From vwRelationship Where (UserA = 1 AND UserB = 2) OR (UserA = 2 AND UserB = 1) Scenario: * *User 1 and User 2 don't know each other | Relationship Type = NULL *User 1 friends User 2 | Relationship Type = Pending *User 2 accepts | Relationship Type = Friend *a month later User 2 blocks User 1 | Relationship Type = Block A: Here's what I ended up using: Table - Relationship RelationshipID, RelationshipTypeID, CreatedByUserID, CreatedTimestamp Table - RelationshipType RelationshipTypeID, RelationshipTypeName Table - UserRelationship UserID, RelationshipID, IsPending Anybody think of anything better?
{ "language": "en", "url": "https://stackoverflow.com/questions/7589725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what does the @d mean in ''xterm -display @d' An existing .bat script running on Windows XP has a call to xterm with the flag '-display @d'. I need to alter the display value being passed through to xterm, to point to a different IP address. However, it would help to know what the @d currently stands for and passes in. A: @d is an Exceed specific variable. Your hostname will get substituted for the @d along with a :0.0 If you want to alter the value of @d you can just remove it and replace it with whatever hostname or IP address you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589726", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Class function that creates an instance of itself in Delphi Can you have a class function that creates an instance of a class: TMyClass = class(TSomeParent) public class function New(AValue : integer) : TMyClass; end; TDerivedClass = class(TMyClass) public function Beep; end; and then use it as follows ... var myList : TList<T>; item : TDerivedClass; begin myList.Add(TDerivedClass.New(1)) myList.Add(TDerivedClass.New(3)) myList.Add(TDerivedClass.New(5)) for item in myList do item.Beep; //times the count in the class function ... And if so, what does that function code look like? Do you use TObject's NewInstance method and do you re-implement every-time for every derived class? Is it saver/better to use the Constructor? The goal is to use this approach in a command pattern and load the command list with class types and a receiver e.g: //FYI: document is an instance of TDocument commandList.Execute(TOpenDocument(document)); commandList.Execute(TPasteFromClipboard(document)); //... lots of actions - some can undo commandList.Execute(TPrintDocument(document)); commandList.Execute(TSaveDocument(document)); And the reason for this is that some commands will be specified via text/script and will need to be resolved at runtime. A: Yes, it is technically possible to create an instance from a class method, simply call the actual constructor and then return the instance it creates, eg: type TMyClass = class(TSomeParent) public constructor Create(AValue : Integer); virtual; class function New(AValue : integer) : TMyClass; end; TDerivedClass = class(TMyClass) public constructor Create(AValue : Integer); override; function Beep; end; constructor TMyClass.Create(AValue : Integer); begin inherited Create; ... end; function TMyClass.New(AValue : integer) : TMyClass; begin Result := Create(AValue); end; constructor TDerivedClass.Create(AValue : Integer); begin inherited Create(AValue); ... end; var myList : TList<TMyClass>; item : TMyClass; begin myList.Add(TDerivedClass.New(1)) myList.Add(TDerivedClass.New(3)) myList.Add(TDerivedClass.New(5)) for item in myList do TDerivedClass(item).Beep; In which case, you are better off just using the constructor directly: type TMyClass = class(TSomeParent) end; TDerivedClass = class(TMyClass) public constructor Create(AValue : Integer); function Beep; end; var myList : TList<TDerivedClass>; item : TDerivedClass; begin myList.Add(TDerivedClass.Create(1)) myList.Add(TDerivedClass.Create(3)) myList.Add(TDerivedClass.Create(5)) for item in myList do item.Beep; A: Can you have a class function that creates an instance of a class. Is it saver/better to use the Constructor? Constructor is a class function that creates an instance of class. Just put: constructor New(); virtual; And you are good to go. The virtual; part will let you call same New() constructor for all descendant classes. A: What you're looking for is called the factory pattern. It can be done in Delphi; it's how the VCL deserializes forms, among other things. What you're missing is the registration/lookup part of the system. Here's the basic idea: * *Somewhere, you set up a registration table. If you're on Delphi XE, you can implement this as a TDictionary<string, TMyClassType>, where TMyClassType is defined as class of TMyClass. This is important. You need a map between class names and class type references. *Put a virtual constructor on TMyClass. Everything that descends from it will use this constructor, or an override of it, when the factory pattern creates it. *When you create a new descendant class, have it call a method that will register itself with the registration table. This should happen at program startup, either in initialization or in a class constructor. When you need to instantiate something from a script, do it like this: class function TMyClass.New(clsname: string; [other params]): TMyClass; begin result := RegistrationTable[clsName].Create(other params); end; You use the registration table to get the class reference from the class name, and call the virtual constructor on the class reference to get the right type of object out of it. A: Another option is to use RTTI. The code below runs as a normal method in my class as a way to get a new instance of the object with a subset of items, but as the items (along with the list object itself) are probably of descendent objects, creating an instance of the object in which the method is defined isn't good enough as it needs to be of the same type of the instance. i.e. TParentItem = Class End; TParentList = Class Items : TList<TParentItem>; Function GetSubRange(nStart,nEnd : Integer) : TParentList; End; TChildItem = Class(TParentItem) end TChildList = Class(TParentList) end List := TChildList.Create; List.LoadData; SubList := List.GetSubRange(1,3); The implementation if GetSubRange would be something like... Function TParentList.GetSubRange(nStart,nEnd : Integer) : TParentList; var aContext: TRttiContext; aType: TRttiType; aInsType : TRttiInstanceType; sDebug : String; begin aContext := TRttiContext.Create; aType := aContext.GetType(self.ClassType); aInsType := aType.AsInstance; Result := aInsType.GetMethod('Create').Invoke(aInsType.MetaclassType,[]).AsType<TParentList>; sDebug := Result.ClassName; // Should be TChildList // Add the items from the list that make up the subrange. End; I appreciate for some things it may be a bit OTT, but in the design above, it works and is another alternative, although I appreciate, its not a class method. A: You should use a constructor (a special "kind" of class function). TObject.NewInstance is not a suitable option, unless you require special memory allocation. And regarding the Execute routine of the command list: the action involved now depends on the type of the object. Imagine a document being able to open, print, paste and save at the same time (not a weird assumption), that would be difficult to implement in this structure. Instead, consider to add interfaces (IOpenDocument, IPasteFromClipboard, IPrintable, ISaveDocument) which indeed could all be actions of one document instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: css inline list needs width, height and vertical-alignment, for background-image swap on hover, using sprite I have placed the corresponding code at http://cssdesk.com/QSwDG The sprite (referenced as 'circle.png' in the code) is at: http://i54.tinypic.com/34jas79.png Objectives: - To get the list items inline while maintaining the 60x60 size of each. - To have the lower part of the sprite apear when each link is hovered over: A circle should appear around the link. - To vertically centre the text within each 60 x 60 container. I know I can create separate images for each of the links and achieve the desired visual outcome but I want to see if the above is possible. Thanks A: well... if you don't have to support IE < 8 then you can use display:table-cell;. I'm not entirely versed in display:table so I just floated the lis. http://cssdesk.com/3hKth a.roll{ ... vertical-align: middle; display: table-cell; } A: @caseyc For horizontally and vertical centralization, try it: li{ float:left; width:60px; height:60px; border:1px dotted green; display:block; text-decoration:none; display:table; } a.roll{ vertical-align:middle; display:table-cell; text-align:center } Now, make the background property on "a.roll". Cleber.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Silverstripe: Excluding current page from list of the parent's children Using Silverstripe's "ChildrenOf" syntax, I've been successfully able to list all children of a page's parent. It's being used in a "see also" style list on a page. I'd like to exclude the current page from the list but unsure how to determine which is the same as the current page, as within the control loop I'm in the parent's scope. Any ideas? Here's a pseudocode of what I'm doing: <% control ChildrenOf(page-url) %> <!-- Output some stuff, like the page's $Link and $Title --> <% end_control %> A: there's a built-in page control for this, so to exclude the current page from your list: <% control ChildrenOf(page-url) %> <% if LinkOrCurrent = current %> <!-- exclude me --> <% else %> <!-- Output some stuff, like the page's $Link and $Title --> <% end_if %> <% end_control %> see http://doc.silverstripe.org/sapphire/en/reference/built-in-page-controls#linkingmode-linkorcurrent-and-linkorsection UPDATE as you mentioned in your comment below that you'd like to use the $Pos control, you need to filter the dataobjectset before iterating over it. add the following to your Page_Controller class: function FilteredChildrenOf($pageUrl) { $children = $this->ChildrenOf($pageUrl); if($children) { $filteredChildren = new DataObjectSet(); foreach($children as $child) { if(!$child->isCurrent()) $filteredChildren->push($child); } return $filteredChildren; } } then replace 'ChildrenOf' in your template by 'FilteredChildrenOf': <% control FilteredChildrenOf(page-url) %> //use $Pos here <% end_control A: In Silverstripe 3.1 you can use a method like this - <% loop $Parent.Children %> <% if $LinkingMode != current %> <!-- Output some stuff, like the page's $Link and $Title , $Pos etc --> <% end_if %> <% end_loop %> This way you can list all parent's children pages. See https://docs.silverstripe.org/en/3.1/developer_guides/templates/common_variables/
{ "language": "en", "url": "https://stackoverflow.com/questions/7589740", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Combining several tables with some common fields into a single table I have a series of text files (one per year) which contain the answers to an annual survey/questionnaire. Column headings in the files refer to question numbers, and each row represents one person's answers to the questions e.g. Q1, Q2, Q3, ... P1A1, P1A2, P1A3, ... P2A1, P2A2, P2A3, ... etc. [where Q1 is Question 1, P1 is Person 1 and A1 is Answer 1]. The questionnaire uses the same core set of questions each year, but each year new questions are also added and some old ones are removed. My tables therefore have lots of fields in common, but they're not all the same e.g. Year 1 | Year 2 | Year 3 etc. Q1, Q2, Q3 | Q1, Q2, Q4 | Q1, Q2, Q5 P1A1, P1A2, P1A3 | P1A1, P1A2, P1A4 | P1A1, P1A2, P1A5 P2A1, P2A2, P2A3 | P2A1, P2A2, P2A4 | P2A1, P2A2, P2A5 In this example Q1 and Q2 are the core questions, while Qs 3, 4 & 5 depend on the survey year. Removed question numbers are never re-used: if a new question is added, it's given a completely new number. The real surveys have between 300 and 500 questions, and approximately 40,000 people respond each year. I want to combine all of this data into a single table, the column headings of which would be the set of distinct headings in the original files, plus a column for the year. For years where a question isn't relevant, I'd like to have nulls e.g. Year, Q1, Q2, Q3, Q4, Q5 1, P1A1, P1A2, P1A3, Null, Null 1, P2A1, P2A2, P2A3, Null, Null 2, P1A1, P1A2, Null, P1A4, Null 2, P2A1, P2A2, Null, P2A4, Null 3, P1A1, P1A2, Null, Null, P1A5 3, P2A1, P2A2, Null, Null, P2A5 Essentially, I just want to append columns where they match and otherwise have nulls, but if possible I'd like to generate the set of column headings for the final table automatically (from the input tables) as the number of questions in the survey is large and the prospect of working-out and then typing the Create Table statement is horrific! I suppose what I'm after is some kind of variation on UNION ALL that doesn't require me to specify all the columns in order and which can handle the non-matching columns. Does anyone have any tips or suggestions, please? I was originally hoping to use SQLite, but I'm willing to try pretty-much anything. I'm not a databasing expert, but I have a basic understanding of SQL and can do a bit of Python scripting if that's any help. If you've made it this far thanks for reading! I thought this would be a very simple problem, but it's surprisingly difficult to describe in detail. A: Step 1. Stop coding. Step 2. Buy a book on data warehousing and star-schema design. Ralph Kimball's Data Warehouse Toolkit, for example. http://www.amazon.com/Data-Warehouse-Toolkit-Complete-Dimensional/dp/0471200247 Step 3. Design a proper star schema. Question is a dimension. Time (specifically year) is a dimension. Respondent (if you know them) is a dimension. Response (individual survey instrument) is a dimension. Facts are answers to questions in a given year. Each survey becomes multiple rows of facts. Step 4. Load your star schema with your various years of data. The dimensions (questions) are a little complex to load because each year reuses some questions and adds new ones. Once the dimensions are loaded, the fact rows are pretty easy to load. Step 5. Now you can write a quick reporting application to extract the requisite data from the various fact rows and assemble the desired report. A: First SQLite isn't going to have the fancy features of a larger DBMS. If you don't want to write a select statement fragment for each question, you'd need a pivot table, which SQLite doesn't have. The original format is confusing - I would create a single table with columns Person, Question, Answer and Year. (Parse out the person and the question number.) and go at it from there. If this doesn't work, use the original format in a single table. From this, computing the final table is something you could easily do in Python instead of SQL A: here is a rough sudo code sketch using only basic python stuff have a master list for all 'entries' * *read in the first line of your file, getting all the questions *create a set() and add to the set all questions from all years *create a dictionary with the 'keys' as the question *additionally add a key for person's name and the year *load up a new dictionary for each person and append it to your list *do this for each file, st you have a list of dictionaries *make yourself a formatting function which asks element_in_list.has_key('a question from the set of questions') ... if it does, great, if not, print "NONE" or w/e your set() of questions should be casted to a list() to preserve order in the final output [ {"year":"2001","name":"bob","q1":"hello"} {"year":"2011","name":"rob","q5":"world"} ]
{ "language": "en", "url": "https://stackoverflow.com/questions/7589745", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to merge Setup.exe, Setup.msi and .NetFramework prerequisite in a single installer? How can the setup files and prerequisite files from a vs2010 setup project be merged together? ..in my release directory there are 3 files: setup.exe Setup1.msi DotNetFX40Client/dotNetFx40_Client_x86_x64.exe and I need these files to be in one simple setup file. I tried using IExpress tool from windows but it doesn't work because "dotNetFx40_Client_x86_x64.exe" is inside a directory, and the tool does not support it. Is there any way to make setup.exe look for the .net framework prerequisite in the root folder so I can use the IExpress tool??And if not, is there any other way to merge these files into a single installer? Thanks in advance!! Cheers! A: I have had a good bit of success using dotNetInstaller 1.10 as a post-build step (the original installer, [optional] MSI, and any support bundles are wrapped into the dotNetInstaller output executable): dotNetInstaller enables the developer to define the application prerequisites and install the correct version(s) of these components in a predictable order based on the processor architecture, user operating system type and language, allow the user to download these components from the web, install these components directly from a single packaged setup, local media or both. dotNetInstaller is very feature rich and runs on all known Windows operating systems with a very tiny footprint. A boostrapper [dotNetInstaller] doesn't replace tools like InstallShield, Wise, Visual Studio Setup and Deployment Project or Wix. The goal is to create an application to help users with installing the correct prerequisites. Most real world applications need to install several components to work properly, including Windows Service Packs, Internet Explorer, MDAC or .NET Framework. This kind of applications are most commonly known as bootstrappers. dotNetInstaller is such a bootstrapper. It takes some work to get the "rules correct", but it Works Well Enough for Me. Happy coding. A: Make use of the NSIS installer - you may find it here, there's tutorials to be a plenty from here. Here's an example of the syntax adopted to your usage scenario: (...) SetOutPath "$INSTDIR\resources" SetOverwrite off File "setup.exe" File "setup1.msi" File "DotNetFX40Client/dotNetFx40_Client_x86_x64.exe" (...) Exec "$INSTDIR\resources\setup.exe" The NSI file is then compiled into a single file installer that includes all your material in one exe - the functionality of that exe file can be anywhere in between simply unpackaging and executing your own setup.exe file and a full custom installer (can't see why you would want that in your case).
{ "language": "en", "url": "https://stackoverflow.com/questions/7589746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to find average without using group by statement in sql I want to know if its possible to get the functionality of group by with using it. I need to find average without using group by. basically I am looking for an alternative for the below simple query without using group by. SELECT AVG(salary) , g.emp_id FROM #emp e ,#salary d WHERE e.emp_id=d.emp_id GROUP BY e.emp_id A: One option SELECT e.emp_id , ( SELECT AVG(salary) FROM #salary d WHERE d.emp_id = e.emp_id ) FROM #emp e A: If your DB supports partition you can do: SELECT e.emp_id , AVG(s.salary) OVER(PARTITION BY s.emp_id) AS average_salary FROM #emp e INNER JOIN #salary s ON (e.emp_id = s.emp_id) I fail to see the purpose of this exercise however. It just makes your query harder to read, harder to debug and replaces commonly used syntax with obscure code. Group by rocks Did you know that group by even as a 'grant total' function build in SELECT AVG(d.salary) , e.emp_id FROM #emp e INNER JOIN #salary s ON (e.emp_id = s.emp_id) GROUP BY e.emp_id WITH ROLLUP See: SQL-server: http://msdn.microsoft.com/en-us/library/bb522495.aspx MySQL: http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html Remark Do not use implicit SQL '89 syntax, as much as I love Bill Joel's we didn't start the fire it is time to move on to the much better SQL '92's Explicit join syntax. As for songs, 1989 really has a better year: A: If you really wanted to do this, you could SELECT ... ORDER BY employee and then write a cursor to calculate the averages piecemeal. I don't see any good reason to do this, though. A: Are you looking for something like this? SELECT AVG(d.salary) over (partition by null), e.emp_id FROM #emp e JOIN #salary d ON e.emp_id = d.emp_id; It will return all employee ids and the average salary calculated for all employees (so it will contain the same information for all rows). A: Try This: select * from (SELECT AVG(salary) , g.emp_id FROM #emp e ,#salary d WHERE e.emp_id=d.emp_id GROUP BY e.emp_id) a`
{ "language": "en", "url": "https://stackoverflow.com/questions/7589756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I define an XSL variable and assign a value in xsl:choose I want to define a variable named 'category' in XSL, assign a value to it, and reuse that variable a bit down in my code. if objecttype=1 the variable value should be 'car' if objecttype=2 the variable value should be 'bus' How can I achieve that? <xsl:template match="/"> <html> <head><style type="text/css">body{font-size:11px;font-family:Verdana;}</style></head> <body> Dear <xsl:for-each select="user"> <xsl:value-of select="firstname"/><xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> <xsl:if test="middlename != ''"> <xsl:value-of select="middlename"/><xsl:text disable-output-escaping="yes">&amp;nbsp;</xsl:text> </xsl:if> </xsl:for-each> <xsl:value-of select="user/lastname"/>,<br/> <br/> You have created a company listing for "<xsl:value-of select="user/objecttitle"/>".<br/> <br/> Did you know Google uses the number of Facebook 'likes' for webpages in its rankings?<br/> You can like you page here: <xsl:for-each select="user"> <xsl:variable name="category"> <xsl:choose> <xsl:when test="objecttype='1'">car</xsl:when> <xsl:when test="objecttype='2'">bus</xsl:when> </xsl:choose> </xsl:variable> </xsl:for-each> <a href="http://www.mydomain.com/{$category}/{user/objectid}/{user/objecturl}">Click here to go to your company listing now.</a><br/> Kind regards,<br/> <br/> <br/> </body> </html> </xsl:template> A: This is a common error for XSL newcomers. The correct approach is: <xsl:variable name="category"> <xsl:choose> <xsl:when test="objecttype='1'">car</xsl:when> <xsl:when test="objecttype='2'">bus</xsl:when> ... etc </xsl:choose> </xsl:variable> In your example, the variable is local to the <xsl:when...> tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Exporting data to excel in vb.net I am unable to export my data into excel. I have tried the suggestions on S/O, but have not had any luck. Dim sqlString As String = "spExportRateProfile" & Session("OfficeNumber") & "," & Session("SalesRepID") Dim conn As SqlConnection = New SqlConnection(Utils.GetConfigKey("ConnectionStringVimas")) conn.Open() Dim dt As DataTable = New DataTable() Dim da As SqlDataAdapter = New SqlDataAdapter(sqlString, conn) da.Fill(dt) Response.AddHeader("content-disposition", "attachment;filename=ReportExport.xlsx") Response.ContentType = "application/vnd.ms-excel" What do I need do after this to export my data to excel? A: You could use a ExcelLibrary like EPPlus(GPL) which i can warmly recommend. Then it is as easy as this to create Excel-Files from a DataTable and write it to the Response: Dim pck = New ExcelPackage() Dim ws = pck.Workbook.Worksheets.Add("Worksheet-Name") ws.Cells("A1").LoadFromDataTable(dt, True, OfficeOpenXml.Table.TableStyles.Medium1) Response.Clear() Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" Response.AddHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx") Response.BinaryWrite(pck.GetAsByteArray()) Here is another example: http://epplus.codeplex.com/wikipage?title=WebapplicationExample A: once you have your datatable dt here you should do this (C# - just copied from the Internet) ... da.Fill(dt); Response.ContentType = "Application/x-msexcel"; Response.AddHeader("content-disposition", "attachment; filename=\"test.csv\""); Response.Write((new ExportXMLCSV()).ToCSV(dt)); Response.End(); and here the method ToCSV of the class ExportXMLCSV (C# - just copied from the Internet) public string ToCSV(DataTable dataTable) { //create the stringbuilder that would hold our data StringBuilder sb = new StringBuilder(); //check if there are columns in our datatable if (dataTable.Columns.Count != 0) { //loop thru each of the columns so that we could build the headers //for each field in our datatable foreach (DataColumn column in dataTable.Columns) { //append the column name followed by our separator sb.Append(column.ColumnName + ','); } //append a carriage return sb.Append("\r\n"); //loop thru each row of our datatable foreach (DataRow row in dataTable.Rows) { //loop thru each column in our datatable foreach (DataColumn column in dataTable.Columns) { //get the value for tht row on the specified column // and append our separator sb.Append(row[column].ToString() + ','); } //append a carriage return sb.Append("\r\n"); } } //return our values return sb.ToString(); } everything just copied from here: http://forums.asp.net/t/1115305.aspx you should be good to go with a little exercise of conversion C# -> VB.NET ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7589768", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Command /usr/sbin/chown failed with exit code 1? Each time I try to archive my application to submit it to apple Xcode keeps giving me this error! I'v Triple checked that in the Cocos2d libraries Target i made that my Install Group & Install Owner are correct and i;v restarted my computer & reinstalled Xcode. It runs just fine in the simulator. But like i said as soon as I hit Archive it gives me this error SetOwnerAndGroup "Home:staff" "/Users/Home/Library/Developer/Xcode/DerivedData/Swimmu-bdswkmmaijgxvyasdnmkpmnfgxji/ArchiveIntermediates/Swimmu/InstallationBuildProductsLocation/usr/local/lib/libcocos2d libraries.a" cd /Users/Home/Documents/Swimmu setenv PATH "/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin" /usr/sbin/chown -RH "Home:staff" "/Users/Home/Library/Developer/Xcode/DerivedData/Swimmu-bdswkmmaijgxvyasdnmkpmnfgxji/ArchiveIntermediates/Swimmu/InstallationBuildProductsLocation/usr/local/lib/libcocos2d libraries.a" chown: /Users/Home/Library/Developer/Xcode/DerivedData/Swimmu-bdswkmmaijgxvyasdnmkpmnfgxji/ArchiveIntermediates/Swimmu/InstallationBuildProductsLocation/usr/local/lib/libcocos2d libraries.a: No such file or directory Command /usr/sbin/chown failed with exit code 1 A: Your name entered in Install Owner should match the name of your Mac OS login under which you are logged in and the Name of Apple's Dev License and certificates. So go to System Preferences | Users & Groups and set a Full name that matches your Apple's Developer License name A: Yet a third problem with the same error... Different solution as well. In my case, the default install group $(INSTALL_GROUP) was a windows domain and had \ in it, which translated to space and caused the build to fail.. I fixed it by changing my install group to be admin. A: "libcocos2d libraries.a" The problem may be related to the space in the library. If you created that library target it should be easy to fix by changing the name of the library target to "cocos2d_libraries". A: I had a different problem than you, but had the same error: Command /usr/sbin/chown failed with exit code 1 When I created my XCode project, my app name had a space in it, so trying to deploy my app always failed. I was able to fix this by using a Custom Archive Name. In XCode 4... * *Edit the Deployment Scheme *Click on the Archive tab *Then specify an Archive Name that doesn't have spaces in it. A: I was able to fix this by cleaning the project, deleting derived data, and restarting Xcode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Change last octet of IP returned by gethostentry Was wondering if anyone could help me out here. I don't dont much with c# but its easy for what im trying to do. I am making a small application that will take in the hostname on my network and then return the full ipaddress(ipv4) ....From there i have options to ping/vnc/telnet...etc. My question lies here... I am using GetHostEntry to return the ip address. Then I want to store the IP into a variable, and change the last octet. I figured a simple sting.split('.') would be the answer, but I can't convert the IP to a string because the source is not a string. Any ideas? Here is my Method to get the IP address, its just the basic GetHostEntry method: IPHostEntry host = Dns.GetHostEntry( hostname ); Console.WriteLine( "GetHostEntry({0}) returns: {1}", hostname, host ); // This will loop though the IPAddress system array and echo out // the results to the console window foreach ( IPAddress ip in host.AddressList ) { Console.WriteLine( " {0}", ip ); } A: Assuming there is only one network adapter: // When an empty string is passed as the host name, // GetHostEntry method returns the IPv4 addresses of the local host // alternatively, could use: Dns.GetHostEntry( Dns.GetHostName() ) IPHostEntry entries = Dns.GetHostEntry( string.Empty ); // find the local ipv4 address IPAddress hostIp = entries.AddressList .Single( x => x.AddressFamily == AddressFamily.InterNetwork ); Once you have the host IP, you can then use the IP bytes to create a new IP address by modifying any of the octets. In your case, you're wanting the last octect to be modified: // grab the bytes from the host IP var bytes = hostIp.GetAddressBytes(); // set the 4th octect (change 10 to whatever the 4th octect should be) bytes[3] = 10; // create a new IP address var newIp = new IPAddress( bytes ); Of course, you can change any of the octets. The above example is only for the 4th octet. If you wanted the first octet, you'd use bytes[0] = 10. A: You can convert it to a string by using the IPAddress object's ToString() method. Have you considered just using the System.Net.IPAddress object? Here is the document on its Parse method, which takes a string and attempts to convert it to an IPAddress object, so you could do whatever string magic you wanted to do: http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx Or, if you want to know how to convert a string to a number, try the numeric data type's TryParse method. Perhaps Int32.TryParse would work. A: Here's a rather brittle method that relies on the byte order of your machine and, obviously, the family of the provided address. byte[] ipBytes = ip.GetAddressBytes(); while (ipBytes[0]++ < byte.MaxValue) { var newIp = new IPAddress(ipBytes); Console.WriteLine(" {0}", ip); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7589772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to export Jar with Jfreechart library I am looking to export a Java project into a Executable Jar file from eclipse. I have tried to export from Eclipse a) as Jar b) as Executable Jar. There are Jfreechart libraries in project, although I check the option "export all referenced libraries" the UI run from exported Jar doesn't really draw the graph. I tried adding Fat Jar into project "Referenced libraries" in Eclipse, no luck yet. This is related to my previous question as well : Provide/Export executable file to client A: (Posted solution on behalf of the question author, in order to move it to the answer space). Found the solution, Fat Jar helped me do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I access the nth character(s) in an NSString? I've got HEX colors as NSStrings and want to check if a particular string contains an F at the first, third, or fifth character, but to ignore it if it contains an F at the second, fourth or sixth character. This is to identify if the color in question is a light color or not. I searched for this, but only found answers regarding how to find character ranges. A: You can use the characterAtIndex member of NSString. char fifthChar = [yourString characterAtIndex:5]; A: As @Daniel Pereira says, you can use the -[NSString characterAtIndex:] method to check characters. NSString *string = /* Assume this exists */; if ([string characterAtIndex: 1] == 'F' || \ [string characterAtIndex: 3] == 'F' || \ [string characterAtIndex: 5] == 'F') { // F at odd-indexed character } else { // Do other stuff here... } A: Have you tried to use characterAtIndex? You can use the method to retrieve the string at the first, third and fifth character (of course one at a time) and compare it with F. Note that all your HEX colors must be 6 characters. Sometimes, you can represent a color with only three hex values (eg. FFF would still give you white in HTML). So if your color is represented using three chars only, and you try to get the char at index 5, the method will throw an 'out of range' exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Auto-responding to http traffic on local computer I am looking for a small utility that can perhaps sit in the tray that functions similar to Fiddler's Auto-Responder. I would be willing to write such a utility that supports taking a request and responding with data located in a file containing the response headers/body. I am writing an application is C# that would benefit from such a utility. If there is no such utility, could someone point me in the right direct for beginning to write such an application? I ask because I figured someone out there probably knows and would point me in the right direction in no time. Thank you in advanced for your help. A: Typically we call this a web server. They listen for web traffic and automatically respond to it with a file, typically a webpage. Apache is cheap. I think MS has a free IIS package too. A: You haven't explained what's wrong with simply using Fiddler itself? If you run it using the -quiet command line argument, it sits quietly in the tray. If you want to write your own application in C#, you can do so using FiddlerCore; see http://www.fiddler2.com/core/ for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: adding mobile browser detection, rule selection, into a ruleset I would like to add functionality to a ruleset that fires a distinct rule based on whether or not the browser is mobile or not. (one rule fires for a standard browser, a different rule fires for a mobile browser) I know that the browser detection can be done any number of ways, but my first inclination would be with javascript. Any thoughts on how to start with this? A: You can use the useragent object, like this: rule detect_agent { select when pageview ".*" pre { browser_name = useragent:browser_name(); browser_version = useragent:browser_version(); os = useragent:os(); os_type = useragent:os_type(); os_version = useragent:os_version(); full_useragent = useragent:string(); message = << <p><strong>Information about your browser:</strong></br /> <em>Browser name:</em> #{browser_name}</br /> <em>Browser version:</em> #{browser_version}</br /> <em>Operating system:</em> #{os}</br /> <em>OS type:</em> #{os_type}</br /> <em>OS version:</em> #{os_version}</br /></p> <p>#{full_useragent}</p> >>; } append("body", message); } You might have to do some parsing of your own, though, since the browser_name and os may or may not be correct. Here's what it looks like in Chrome on a Mac (you can test it using this URL in any browser): Here's what it looks like in Safari on an iPad: Do some research into what the UserAgent strings look like for the browsers you care about. Then you can use the useragent:string() function together with match() to determine what to do with it. (If you want an example of how to do that, let me know.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7589782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Oracle query that will list of the database objects referenced by a view Is there an Oracle view that will list all of the database objects referenced by the DDL of a given view, procedure, or function? So if a view is defined as: CREATE OR REPLACE VIEW_B AS SELECT * FROM TABLE_A INNER JOIN VIEW_A running a query on this system view: SELECT REF_OBJECT_NAME, REF_OBJECT_TYPE FROM V$XXX WHERE OBJECT_NAME='VIEW_B' would list something like: REF_OBJECT_NAME REF_OBJECT_TYPE TABLE_A TABLE VIEW_A VIEW A: Try: select * from dba_dependencies where owner = 'view owner' and name = 'view name';
{ "language": "en", "url": "https://stackoverflow.com/questions/7589789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java searching option I have drop down that has list of column name. When user selects column name and enters serach value i populate the page but I am trying to bring everything from table if they dont enter search value but seleted one of the drop down column name. I tried to do this way if search value is null dont look for where clause just go straight to the else but this is not working for me..Can someone tell me what I am doing wrong over here? Thank you sql.append(" SELECT id, name, dept, email"); if ((this.getSearch() != null)&& (this.getSelected().equals("1"))){ sql.append(" from table "); sql.append(" where id = '"); sql.append(this.getSearch()); sql.append("'"); }else if ((this.getSearch() != null)&& (this.getSelected().equals("2"))){ sql.append(" from table "); sql.append(" where name = '"); sql.append(this.getSearch()); sql.append("'"); }else{ sql.append(" from table "); } A: Perhaps this.getSearch() does not return null but something else like an empty string or a string containing whitespace characters. Have you sanitized that String already? A: Whenever dealing with a String returned from some code that i didn't write, I usually check for NULL first and then for a Zero Length String: String str = myClass.getMyString(); if (str == null || str.length() < 1) { /* Failure case */ } else { /* Success case */ } The above code makes the assumption that the return value methodology states that a zero length string is a mode of failure, so keep that in mind. A: There is a tool for this, called a debugger.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I use C libraries in assembler? I want to know how to write a text editor in assembler. But modern operating systems require C libraries, particularly for their windowing systems. I found this page, which has helped me a lot. But I wonder if there are details I should know. I know enough assembler to write programs that will use windows in Linux using GTK+, but I want to be able to understand what I have to send to a function for it to be a valid input, so that it will be easier to make use of all C libraries. For interfacing between C and x86 assembler, I know what can be learned from this page, and little else. A: One of the most instructive ways to learn how to call C from assembler is to: * *Write a C program that calls the C function of interest *Compile it, and look at the assembly listing (gcc -S) This approach makes it easy to experiment by starting with something that is already known to work. You can change the C source and see how the generated code changes, and you can start with the generated code and modify it yourself. A: * *push parameter on the stack *call the function *clear the stack The links you have in your question show all these steps. A: The OS may define the calling standard (it pretty well must define the standard for invoking system calls), in which case you need only find where that is documents and read it closely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Objective-C JSON - Convert JSON object to native object? {"status": "FRE", "list": [{"make": "Toyota", "id": 1, "model": "camry", "engine": "Four Cylinder"}{"make": "Ford", "id": 3, "model": "focus", "engine": "Four Cylinder"}]} How do I extract each "car" JSON object and put it into a native object? I'm using SBJSON. Here is my current code, but it is only able to extract one car element, when I need to be able to iterate through each car object and save it: NSString *responseString = [request responseString]; NSString *responseDict = [responseString JSONValue]; NSArray *keys = [NSArray arrayWithObjects:@"id",@"make",@"model",@"engine", nil]; NSArray *objects = [NSArray arrayWithObjects:[responseDict valueForKeyPath:@"list.make"],[responseDict valueForKeyPath:@"list.model"],[responseDict valueForKeyPath:@"list.id"],[responseDict valueForKeyPath:@"list.engine"] , nil]; self.car = [[NSDictionary alloc]initWithObjects:objects forKeys:keys]; A: Instead of doing everything manually, use Jastor - https://github.com/elado/jastor You just need to create simple classes and initWithDictionary will do the entire assigning work for you. A: Try to reason like this.. when you do [[[request responseString] JSONValue] valueForKey:@"list"]]; it will return an array of list of your cars. Then you iterate each array and save it into your car element... Example: NSArray *arrayCar = [NSArray arrayWithArray:[[[request responseString] JSONValue] valueForKey:@"list"]]; for (NSDictionary *carDict in arrayCar) { Car car = [[Car alloc] init]; car.id = [carDict valueForKey:@"id"]; car.origin= [carDict valueForKey:@"make"]; ... ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7589794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove an attribute option in Magento? For example, I want to delete an unnesesary option for a customer's entity "gender" attribute. How can I do this programmatically (not from admin panel)? A: you can disable this attribute from system > configuration > customer > customer options > name and address options And you can change this programmatically like changing any other config value in Magento . You'll find the tutorial there http://inchoo.net/ecommerce/magento/how-to-programmatically-change-magentos-core-config-data/
{ "language": "en", "url": "https://stackoverflow.com/questions/7589796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inline if Statement not working For some reason, when I add the ternary if statement to this bit of code, a NullPointerException is thrown. I'm not sure quite why...any ideas? This is the method for jqGrid - returning the Json data. var gridModel = from entity in vendorList.AsQueryable() select new { VendorId = "<a href='/Admin/DetailsPlan/" + entity.VendorId + "'><img src='/Images/next_icon_sm.png' class='icon' alt='View Vendor' /></a>", VendorNm = entity.VendorNm, Phone = (entity.Phone.Length < 5) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(entity.Phone)) : entity.Phone, City = entity.City, State = entity.LkState.StateAbbr }; Can you not have a ternary if statement in that location? A: var gridModel = from entity in vendorList.AsQueryable() let unformattedPhone = entity.Phone??string.Empty select new { VendorId = "<a href='/Admin/DetailsPlan/" + entity.VendorId + "'><img src='/Images/next_icon_sm.png' class='icon' alt='View Vendor' /></a>", VendorNm = entity.VendorNm, Phone = (unformattedPhone.Length < 5) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(unformattedPhone)) : unformattedPhone, City = entity.City, State = entity.LkState.StateAbbr }; This may solve your problem. A: One question, is entity.Phone null? If so, that would be the cause. Side note: I have to say, that is an odd way of storing a phone number.. UPDATE The problem is with the "entity.Phone.Length" part. If Phone is null, then you can't access it's length property... hence the error. So you need to add a null test. Something like: Phone = ((entity.Phone != null) && (entity.Phone.Length < 5)) ? String.Format("{0:(###) ###-####}", Convert.ToInt64(entity.Phone)) : entity.Phone That way, if it is null you are just emitting a null value.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send http headers from servlet to app in another environment I need to send a request from a servlet to an application running in other environment (IIS) with certain information in custom headers. I know redirecting doesn't send the headers and getServletContext().getRequestDispatcher(url) is to be used in the servlet's context only. Has anybody made this work in some other way? I was thinking in using HttpURLConnection, but would it finally redirect the browser to the targeted app ? Thanks in advance A: You can't redirect from your servlet to the external server and keep the headers, and you can't forward the incoming request to other context. What you could do, is to use the HttpURLConnection (or other http client library such as HTTPClient) to make the request (with the custom headers you need) to the remote server and, once the operation is complete, redirect the user to the external site (customm headers are not set in this redirection). This is a little tricky, if you elaborate your question (what do you really need to do) we can probably think about other alternatives. A: AJAX? You can send some JavaScript code to the browser which sends a request to the ISS and handle (shows) its answer. It's possible to set http headers with XMLHttpRequest but it needs client side JavaScript coding and you have to find a way to send cross domain requests.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIViewController encodeWithCoder fails when view contains a UIButton with custom image Basically, my problem is exactly what it says in the title. When I try to encode a subclass of UIViewController, calling [super encodeWithCoder] gives an NSInvalidArgumentException. Specifically, I get -[UIImage encodeWithCoder:]: unrecognized selector sent to instance XxXXXXXX. The only image image in the view is on a UIButton, which is also supposed to conform to NSCoding, and the stack trace includes a call to [UIBUtton encodeWithCoder]. The button is created programmatically with [UIButton buttonWithType:UIButtonTypeCustom], and the image is set with setImage: forState:. I really have no idea what is going on here. Am I missing something obvious, or does UIButton just not really conform to NSCoding? A: I can't imagine why you would want to be archiving view objects within your app, but you probably need to add NSCoding support yourself by writing a category on UIImage. For details see: iPhone - Why does the documentation say UIImageView is NSCoding compliant? View objects support NSCoding because the view loading system uses it to load objects from Nib files. But the UINib class does some additional work that NSKeyedArchiver does not. If you just want to store state between launches, it's better to store data and not view state. Especially if you ever plan to update your app and make any changes whatsoever to the view layout. (This is the motivation behind Model/View/Controller separation.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7589806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why can't we have automatically deduced return types? Recently I was working a friend who wanted to make C++ more Haskell-y, and we wanted a function that's basically like this: auto sum(auto a, auto b) { return a + b; } Apparently I can't use auto as a parameter type, so I changed it to this: template<class A, class B> auto sum(A a, B b) { return a + b; } But that doesn't work either. What we eventually realized we need this: template<class A, class B> auto sum(A a, B b) -> decltype(a + b) { return a + b; } So my question is, what's the point? Isn't decltype just repeating information, since the compiler can just look at the return statement? I considered that maybe it's needed so we can just include a header file: template<class A, class B> auto sum(A a, B b) -> decltype(a + b); ... but we can't use templates like that anyway. The other thing I considered was that it might be easier for the compiler, but it seems like it would actually be harder. Case 1: With decltype * *Figure out the type of the decltype statement *Figure out the types of any return values *See if they match Case 2: Without decltype * *Figure out the types of any return values *See if they match So with those things in mind, what's the point of the trailing return type with decltype? A: but we can't use templates like that anyway. First, trailing return types aren't purely a template thing. They work for all functions. Secondly, says who? This is perfectly legal code: template<class A, class B> auto sum(A a, B b) -> decltype(a + b); template<class A, class B> auto sum(A a, B b) -> decltype(a + b) { } The definition of the template could be in the header. Or it could be in another file, so that you don't have to wade through pages and pages of function definitions when looking through an interface. C++ has to account for all possibilities. Restricting trailing return types to just function definitions means that you can't do something as simple as this: template<class A, class B> class Foo { auto sum(A a, B b) -> decltype(a + b); } template<class A, class B> auto Foo<A, B>::sum(A a, B b) -> decltype(a + b) { } And this is fairly common for many programmers. There's nothing wrong with wanting to code this way. The only reason lambdas get away without the return type is because they have to have a function body defined with the definition. If you restricted trailing return types to only those functions where the definition was available, you wouldn't be able to use either of the above cases. A: There is no technical reason why it is not possible. The main reason they haven't is because the C++ language moves very slowly and it takes a very long time for features to be added. You can nearly get the nice syntax you want with lambdas (but you can't have templacised arguments in lambdas, again for no good reason). auto foo = [](int a, double b) { return a + b; }; Yes, there are some cases where the return type could not be automatically deduced. Just like in a lambda, it could simply be a requirement to declare the return type yourself in those ambiguous cases. At the moment, the restrictions are just so arbitrary as to be quite frustrating. Also see the removal of concepts for added frustration. A: Well - time passed since the original question was asked and the answer now is that you can! Yes, it is true that the question is tagged C++11 - with which you still cannot do what the OP is asking for. But it's worthwhile to show what is doable with C++14 and later. Since C++14 this is valid: template<class A, class B> auto sum(A a, B b) { return a + b; } And since C++20 this is also valid: auto sum(auto a, auto b) { return a + b; } The following is the C++11 answer, kept here for historical reasons, with some comments from the future (C++14 and later): What if we have the following: template<class A, class B, class C> auto sum(A a, B b, C c) { if (rand () == 0) return a + b; // do something else... return a + c; } .. where a + b and a + c expressions yield different type of results. What should compiler decide to put as a return type for that function and why? This case is already covered by C++11 lambdas which allow to omit the return type as long as return statements can be deduced to the same type (NB standard quote needed, some sources claim only one return expression is allowed and that this is a gcc glitch). A note from the future (C++14 and on): the example above is still not valid, you may only have a single possible return type. However if there are different return types but the actual return type can be deduced at compile type, then we have two different functions, which is valid. The following for example is valid since C++17: template<class A, class B, class C> auto sum(A a, B b, C c) { if constexpr(std::is_same_v<A, B>) return a + b; else return a + c; } int main() { auto a1 = sum(1, 2l, 3.5); // 4.5 auto a2 = sum(1, 2, 3.5); // 3 } Back to the original C++11 answer, explaining why the requested syntax is not supported: A technical reason is that C++ allows the definition and declaration to be separate. template<class A, class B> auto sum(A a, B b) -> decltype(a + b); template<class A, class B> auto sum(A a, B b) -> decltype(a + b) { } The definition of the template could be in the header. Or it could be in another file, so that you don't have to wade through pages and pages of function definitions when looking through an interface. C++ has to account for all possibilities. Restricting trailing return types to just function definitions means that you can't do something as simple as this: template<class A, class B> class Foo { auto sum(A a, B b) -> decltype(a + b); } template<class A, class B> auto Foo<A, B>::sum(A a, B b) -> decltype(a + b) { } A note from the future (C++14 and on): you still cannot have a declaration with auto return type, if the definition is not available when the compiler sees the call. A: In a blog post from Dave Abrahams, he discusses a proposal for having this function syntax: []min(x, y) { return x < y ? x : y } This is based off of possible proposal for polymorphic lambdas. He has also started work here on updating clang to support this syntax.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "51" }
Q: PHP multidimensional array recursion problem Possible Duplicate: Walk array recursively and print the path of the walk Anyone can help me on this code? <?php function buildMenuWalk(&$array, &$depth, $currentDepth = 1) { # start new level html $html = ''; # walk till the depth defined on the config if($currentDepth > $depth) { return null; } # loop through all items in this level foreach($array as $key => &$value) { # if not in area map continue if(!is_numeric($key)) { continue; } # if no <li> has been created yet, open the <ul> $html .= empty( $html ) ? '<ul class="dropdown">' : ''; #extract the label from this level's array, designated by $labelKey $label = isset( $value['areaname'] ) ? $value['areaname'] : ''; # open an <li> $html .= '<li>'; # generate url $url = ''; if($currentDepth == $depth) { $url = ' href="'. $url .= '"'; } # construct content inside the <li> $html .= '<a' . $url .'>' . $label . '</a>'; # run the function again to grab children levels if(is_array($value)) { $html .= buildMenuWalk($value, $depth, $currentDepth + 1); } # close <li> $html .= '</li>'; } # close <ul> if was generated content on this level $html .= !empty( $html ) ? '</ul>' : ''; return $html; } $depth = 2; $config['content']['map'][1]['areaname'] = 'area_1'; $config['content']['map'][1][1]['areaname'] = 'block_1'; $config['content']['map'][2]['areaname'] = 'area_2'; $config['content']['map'][2][1]['areaname'] = 'block_1'; $config['content']['map'][2][2]['areaname'] = 'bloack_2'; echo buildMenuWalk($config['content']['map'], $depth); ?> If you check the code above, Im using to display a menu recursively ... If the script identify the menu reached the depth, will display href="" inside the tag. Inside this href I want add all parent areas on the recursion. For example: $config['content']['map'][2]['areaname'] = 'area_2'; $config['content']['map'][2][1]['areaname'] = 'block_1'; $config['content']['map'][2][2]['areaname'] = 'bloack_2'; When script reaches the bloack_2, I need display: <a href="area_2=2&block_2=2"> Since its a multidimensional array and can grow to like 4-5 dimension, the output href should count all these levels. For example area_2=1&block_10=5&sub_area_1=5&section_7=8 ... I probably need some array to store all href path during the recursion, but I cant figure how to do it. Thanks, PS: The script will be used to build a dropdown menu. The parent levels don't need to be linked, so print the tag will display the child menu. The last child, will be linked, but need contain all parent params so the results can be filtered. Link to the code running and returning values: http://codepad.org/iyrcdfQP A: Since this function is recursively calling itself, you'll have to refer to a global variable to keep track of the previous tree. So here is the code that'll do what I think you want it to do. All of you have to change is the #generate url section. # generate url $url = ''; if($currentDepth == $depth) { $url = " href=area=" . $GLOBALS['area'] . "&block=$key"; } else { $GLOBALS['area'] = $key; } A: Here is a modification of that same slice of code that makes the href= a little more like what you are describing, although it doesn't really make sense to me. # generate url $url = ''; if($currentDepth == $depth) { $url = " href=".$GLOBALS['area_name']."=".$GLOBALS['area']."&$label=$key"; } else { $GLOBALS['area'] = $key; $GLOBALS['area_name'] = $label; } A: I don't see why one would bother with recursoin and multiple dimensions in a world of 2 dimensions as the menu in a web page is! I would go for 2 dimensions only, the first dimension is to keep all elements (without any criteria) and the second to keep infos about the element: Check an example for yourself, you set which element to get the function displays it along with all ancestors and root elements of previous levels (as California is). <?php function buildMenuWalk($element,$menuElements) { for($i=0;$i<=$element;$i++) { //for a new level go to the next line if(!isset($menuElements[$i]['ancestors'])) { echo '<br>______________________________________</br>'; echo '<strong>',$menuElements[$i]['label'],'</strong> | '; } //if the element is reached display it along with ancestors if($i==$element) { //echo all the ancestores foreach($menuElements[$element]['ancestors'] as $value) { echo $menuElements[$value]['label'],' | '; } //display the element itself echo '<font color=red>',$menuElements[$element]['label'],' | </font>'; } } } //California $menuElements[0]=Array('url'=>'http://www.California.com','label'=>'California'); $menuElements[1]=Array('url'=>'http://www.San Diego.com','label'=>'San Diego','ancestors'=>Array(0)); $menuElements[2]=Array('url'=>'http://www.San Jose.com','label'=>'San Jose','ancestors'=>Array(0,1)); $menuElements[3]=Array('url'=>'http://www.San Francisco.com','label'=>'San Francisco','ancestors'=>Array(0,1,2)); $menuElements[4]=Array('url'=>'http://www.Fresno.com','label'=>'San Francisco','ancestors'=>Array(0,1,2,3)); $menuElements[5]=Array('url'=>'http://www.Sacramento.com','label'=>'Sacramento','ancestors'=>Array(0,1,2,3,4)); //Wyoming $menuElements[6]=Array('url'=>'http://www.Wyoming.com','label'=>'Wyoming'); $menuElements[7]=Array('url'=>'http://www.Cheyenne.com','label'=>'Cheyenne','ancestors'=>Array(6)); $menuElements[8]=Array('url'=>'http://www.Casper.com','label'=>'Casper','ancestors'=>Array(6,7)); $menuElements[9]=Array('url'=>'http://www.Laramie.com','label'=>'Laramie','ancestors'=>Array(6,7,8)); $menuElements[10]=Array('url'=>'http://www.Gillette.com','label'=>'Gillette','ancestors'=>Array(6,7,8,9)); $menuElements[11]=Array('url'=>'http://www.Rock Springs.com','label'=>'Rock Springs','ancestors'=>Array(6,7,8,9,10)); echo '<pre>'; buildMenuWalk(9,$menuElements); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7589810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How would I achieve a unique result using the Linq method syntax I have the following data in a table: e.g. data 0, 'Ford' 1, 'Toyota, Toyota' 2, 'BMW' 3, 'Porsche, Porsche' 4, 'BMW' I need to place this data in the following type List<Tuple<int, string>> carList so that the results within my list would appear as follows: 0, 'Ford' 1, 'Toyota' 2, 'BMW' 3, 'Porsche' 4, 'BMW' using the following pseudo code: while (SQLiteDataReader.Read()) { carList.Add ( new Tuple<int, string> ( SQLiteDataReader.GetInt32(0) , SQLiteDataReader.GetString(1).[Some extension method to produce unique items] ); ) } Note, when there are items with duplication (Toyota, Porsche) , the duplication will always be the same name. i.e you won't get something like 'Toyota, Ford'. Is there some extension method that would remove the duplication part? A: This should do the trick: SQLiteDataReader.GetString(1).Split(',').First().Trim() A: If you're looking to do the whole thing through a linq query, this should work. If you're just looking to fix your pseudocode, then scottm's solution should work. LinqDataContext db = new LinqDataContext(); List<Tuple<int, string>> results = db.Cars.AsEnumerable() .Select(c => Tuple.Create(c.id, c.Make.Split(',')[0].Trim())) .ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/7589812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JQM back button binds itself to every click event when it isn't targeted Using jQuery Mobile (jquery.mobile-1.0b3.min.js). If i apply a click event to a form, the back button seems to get the click event binding as well. It does this no matter how specifically targeted to an element the selector is. For example: Using this to set the back button: Copy code <div id="pagename-page" data-role="page" data-add-back-btn="true" data-back-btn-theme="b"> And this in a script file: Copy code $('#awards-details-page').live('pagecreate', function(event){ $('#awards-details-page input[name=submit]').bind('vclick', function() { console.log('I'm going to be hijacked by the back button.'); }); }); Clicking on the back button will produce the message in the console when tested in a browser. Every time you visit the page with the script, it will add another duplicate binding. Attempts to unbind the click event on the pagehide event worked with the targeted element, but back button's bindings persisted. Can anyone shed some light on this? Thank you in advance. A: dont use vclick you will ge ghost, they have improved CLICK so just use that also live is not bind... bind is to an element that exist, live is for all elements that have that shared property, before after and during. you past pages exist so you have a set of binded items now not just one for the page you are on. i would scrap the whole back button element and have your own clickable item, for this you can do your own back code and add attributes like data-backto = "#page1", you can then control better what happens when a back button is clicked, especially as android phones have there own back button too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .net JSON Date format As response from .net service I get this date format: /Date(1233323754523+0100)/ 1233323754523 is date in timestamp format, but I don't know what +0100 mean and how to generate this from java code? Thanks A: I assume that the timestamp is in UTC and the offset is the UTC offset of the desired local time. If the timestamp is in the given offset from UTC, you'd have to generate it slightly differently. A reliable way to generate this in Java would be using the Joda-Time library, which is much better than de default java.util.Date and java.util.Calendar classes. // A formatter that prints the timezone offset DateTimeFormatter fmt = DateTimeFormat.forPattern("Z"); // The current date+time in the system default timezone. DateTime dt = new DateTime(); // Create the result. String result = "/Date(" + dt.getMillis() + fmt.print(dt) + ")/"; It's a bit unfortunate that the DateTimeFormat does not have a way to output the milliseconds since epoch; that's what necessitates the dt.getMillis() string concatenation. To generate the same thing using the java.util classes would look something like this: // A formatter that prints the timezone offset SimpleDateFormat df = new SimpleDateFormat("Z"); // Current date+time in system default timezone. Calendar now = Calendar.getInstance(); // Don't forget this if you use a timezone other than system default: df.setTimeZone( now.getTimeZone() ); // Create the result String result = "/Date(" now.getTimeInMillis() + df.format(now.getTime()) +")/"; It's essentially the same as the Joda-Time example, but the bit where you have to copy the time zone from the calendar into the date formatter is a major source of bugs. A: The second number simply indicates that the DateTime value should be interpreted as a local date time (instead of UTC), the number itself is ignored. This is described in the Advanced Information / DateTime wire format section of the document at http://msdn.microsoft.com/en-us/library/bb412170.aspx. A: The question is a little out of date, but i think there's still some people out there hitting their heads against a wall because of that excellent date time format choice ;) Serialisation and deserialisation type adapter of a .NET Json formatted DateTime value in Java for Gson This worked for me now since around 2years. package x import java.lang.reflect.Type; import java.text.DecimalFormat; import java.util.Date; import java.util.TimeZone; import java.util.regex.Pattern; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; /** * Serialises and deserialises a string representing a date produced by a .NET web service. * * @author Diego Frehner */ public class TypeAdapterDate implements JsonSerializer<Date>, JsonDeserializer<Date> { /** Pattern for parsing date time values sent by a .NET web service. */ private static Pattern pattern = Pattern.compile("^/Date\\([0-9\\+-]*\\)/$"); private static DecimalFormat formatter = new DecimalFormat("#00.###"); private static final long HOUR_IN_MILLISECOND = 60L * 60 * 1000; private static final String minusSign = "-"; private static final String plusSign = "+"; @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { String value = json.getAsString(); // example .NET web service return value: /Date(1302847200000+0200)/ // milliseconds since midnight 1970 UTC + time zone offset of the server to UTC // GMT == UTC == UT it's all the same...afaik if (!pattern.matcher(value).matches()) { return null; } // get UTC millisecond value long utcMillisecond = Long.parseLong(value.substring(value.indexOf("(") + 1, value.indexOf(")") - 5)); // new Date(long) takes milliseconds since 1970 in UTC return new Date(utcMillisecond); } @Override public JsonElement serialize(Date arg0, Type arg1, JsonSerializationContext arg2) { Date date = (Date) arg0; int zoneOffsetMillisecond = TimeZone.getDefault().getOffset(date.getTime()); String sign = plusSign; if (zoneOffsetMillisecond < 0) { // negative offset sign = minusSign; zoneOffsetMillisecond *= -1; } int minute = (int) (zoneOffsetMillisecond % HOUR_IN_MILLISECOND); int hour = (zoneOffsetMillisecond / 1000 / 60 / 60); return new JsonPrimitive("/Date(" + date.getTime() + sign + formatter.format(hour) + formatter.format(minute) + ")/"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7589816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: agrep function in R I am trying to isolate the strings "24!!07!!10", "15!!08!!12", and "10!!08!!12" from the 4 lines of data below. > z LEGAL 1 MAP #1166 2 SE1/4 NE1/4 24!!07!!10 EX MAP #106 42.13 3 MAP 15!!08!!12 N1/2NW1/4 15!!8!!12 80.00 AC 4 BEG NW COR SAID SEC THEN E208' 10!!08!!12 NW1/4 EX TR AC 158.65~ Firstly, without the max.distance option the agrep function doesn't find any matches at all. Secondly, the option value=TRUE doesn't seem to give the actual values of the pattern matches and if indeed the output is the indices of the rows, the first row shouldn't really be a match at all. > pattern <-"[0-99]-[0-99]-[0-99]" > z1<-agrep(pattern ,z,ignore.case=TRUE, value=TRUE) > z1 character(0) > z1<-agrep(pattern,z,ignore.case=TRUE, value=TRUE, max.distance=22) > z1 [1] "c(2, 4, 3, 1)" I'd appreciate any help in figuring out what is going on. A: @Kent is right about your regular expression not matching what you describe as your pattern. In addition, agrep is for fuzzy matching in the linguistic sense and does not take regular expressions. You are looking for grep or something in that family, probably regexpr. Given your data z <- c("MAP #1166", "SE1/4 NE1/4 24!!07!!10 EX  MAP #106 42.13", "MAP 15!!08!!12 N1/2NW1/4 15!!8!!12 80.00 AC", "BEG NW COR SAID SEC THEN E208' 10!!08!!12 NW1/4 EX TR AC 158.65~") You can find the locations of the matches and extract them with pattern <- "[0-9][0-9]!![0-9][0-9]!![0-9][0-9]" locs <- regexpr(pattern, z) substr(z, locs, locs+attr(locs,"match.length")-1) If you want to use the other form of the regular expression, you can. You just need to double escape the backslashes in the string literal. pattern <- "\\d{2}!!\\d{2}!!\\d{2}" A: don't know R, but your pattern may be not correct. how about "\d{2}!!\d{2}!!\d{2}" or "[0-9][0-9]!![0-9][0-9]!![0-9][0-9]" ? A: Is suspect agrep in R doesn't support that kind of pattern. Anyway, you should probably use grep instead: z1 <- grep("\\d{2}!!\\d{2}!!\\d{2}", z, value=TRUE) A: Another solution is to use to try the stringr package require(stringr) pattern <- "\\d{2}!!\\d{2}!!\\d{2}" str_extract_all(z, pattern) and you get this : [[1]] character(0) [[2]] [1] "24!!07!!10" [[3]] [1] "15!!08!!12" [[4]] [1] "10!!08!!12"
{ "language": "en", "url": "https://stackoverflow.com/questions/7589817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update a widget from a service I'm trying to update a widget from a service... the service start a thread that execute this code AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(Worker.this); RemoteViews remoteViews = new RemoteViews(Worker.this.getPackageName(), R.layout.mywidget); ComponentName projectWidget = new ComponentName(Worker.this, MyWidget.class); remoteViews.setTextViewText(R.id.widgetstate, "update"); appWidgetManager.updateAppWidget(projectWidget, remoteViews); the onUpdate method just print a log, but this log is printed only when I create the widget, not everytime the thread cycles... where I'm wrong? Thanks in advance A: You're not wrong. You just update the widget without calling onUpdate(). It's just a convinience method that gets called in response to the ACTION_APPWIDGET_UPDATE broadcast by the system. You don't have to call it to update a widget, it also just works like you did here. ¹ To invoke it you can send the broadcast or call it by hand though, it's a good idea to keep the widget update functionality in one place from a code structure point of view to find things easily. ¹ Take a look at the AppWidgetProvider source, line 56. The whole AppWidgetProvider is just a BroadcastReceiver that does some work for you already - and it does start the update in the same way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a correct way to mask a 15 digit credit card number? 15 digit bank card numbers are formatted 0000-000000-00000[1]. If I show the last 4 digits, it becomes xxxx-xxxxxx-x0000 which looks slightly goofy. Is there a correct way to format a masked 15 digit number? (I expect we will not show more than the last 4 anyway, but if there is a standard, I want to know about it.) A: There is no standard really. The vast majority of sites display the last four with four X's in front them whether the credit card number is 15 or 16 digits so that would probably be the most recognizable to your users. But if you really want to format it so you show the actual structure of the card number then do it as xxxx-xxxxxx-x0000 despite the goofiness. Users may find showing an extra character (xxxx-xxxxxx-00000) is "unsafe" and I'm sure you don't want to give anyone an opportunity to complain or do a chargeback. A: PCI DSS v3.2.1, requirement 3: mask PAN. Last for digits represent card ID. First 4-6 digits represent bank iD. PCI DSS - Payment card industry Data security standard. PAN - Primary account number.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: XML Encoding error while writing it in to file I think I am following the right approach but I am still getting an encoding error: from xml.dom.minidom import Document import codecs doc = Document() wml = doc.createElement("wml") doc.appendChild(wml) property = doc.createElement("property") wml.appendChild(property) descriptionNode = doc.createElement("description") property.appendChild(descriptionNode) descriptionText = doc.createTextNode(description.decode('ISO-8859-1')) descriptionNode.appendChild(descriptionText) file = codecs.open('contentFinal.xml', 'w', encoding='ISO-8859-1') file.write(doc.toprettyxml()) file.close() The description node contains some characters in ISO-8859-1 encoding, this is encoding specified by the site it self in meta tag. But when doc.toprettyxml() starts writing in file I got following error: Traceback (most recent call last): File "main.py", line 467, in <module> file.write(doc.toprettyxml()) File "C:\Python27\lib\xml\dom\minidom.py", line 60, in toprettyxml return writer.getvalue() File "C:\Python27\lib\StringIO.py", line 271, in getvalue self.buf += ''.join(self.buflist) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe1 in position 10: ordinal not in range(128) Why am I getting this error as I am decoding and encoding with same standard? Edited I have following deceleration in my script file: #!/usr/bin/python # -*- coding: utf-8 -*- may be this is conflicting? A: Ok i have found a solution. When ever data is in other foriegn language you just need to defined the proper encoding in xml header. You do not need to describe encoding in file.write(doc.toprettyxml(encoding='ISO-8859-1')) not even when you are opening a file for writing file = codecs.open('contentFinal.xml', 'w', encoding='ISO-8859-1'). Below is the technique which i used. May be This is not a professional method but that works for me. file = codecs.open('abc.xml', 'w') xm = doc.toprettyxml() xm = xm.replace('<?xml version="1.0" ?>', '<?xml version="1.0" encoding="ISO-8859-1"?>') file.write(xm) file.close() May be there is a method to set default encoding in header but i could not find it. Above method does not bring any error on browser and all data display perfectly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to select element name, not value, using XSL/XSLT? We are using XSL to convert a XML file into a pipe-delimited format. <?xml version="1.0" encoding="UTF-8"?> <ns:tradedata xmlns:ns="http://schemas.com/enterprise/util/extractservice/v1"> <tradedata_item> <ORDER_ID>113632428</ORDER_ID> <CUSIP>31393FHA7</CUSIP> <TICKER>FHR</TICKER> <SEC_NAME>FHR 2527 SG</SEC_NAME> <ORDER_QTY>169249.6824</ORDER_QTY> </tradedata_item> <tradedata_item> <ORDER_ID>113632434</ORDER_ID> <CUSIP>31393G2C7</CUSIP> <TICKER>FHR</TICKER> <SEC_NAME>FHR 2531 ST</SEC_NAME> <ORDER_QTY>214673.0105</ORDER_QTY> </tradedata_item> <tradedata_item> <ORDER_ID>113632431</ORDER_ID> <CUSIP>527069AH1</CUSIP> <TICKER>LESL</TICKER> <SEC_NAME>ZZZ_LESLIE S POOLMART INC</SEC_NAME> <ORDER_QTY>365000.0000</ORDER_QTY> </tradedata_item> </ns:tradedata> We need the first line in the output to be the column headers, and everything else would be data, like this... ORDER_ID|CUSIP|TICKER|SEC_NAME|ORDER_QTY 1136324289|31393FHA7|FHR|FHR 2527 SG|169249.6824 1136324304|31393G2C7|FHR|FHR 2531 ST|214673.0105 We've got the XSL working to get the data, but we can't get the header to output correctly. We just select the first tradedata_item element, then iterate the element name and separate them using | characters. Here is the full XSL... <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl" version="1.0" xmlns="http://schemas.com/enterprise/util/extractservice/v1" xmlns:o="http://schemas.com/enterprise/util/extractservice/v1" > <!-- xsl:strip-space elements="*"/--> <xsl:output method="text" indent="no"/> <xsl:template match="/tradedata/tradedata_item[1]"> <xsl:for-each select="*"> <xsl:value-of select="local-name()"/>| </xsl:for-each> <xsl:text>&#10;</xsl:text> </xsl:template> <xsl:template match="/"> <xsl:for-each select="tradedata/tradedata_item"> <xsl:value-of select="ORDER_ID"/>|<xsl:value-of select="CUSIP"/>|<xsl:value-of select="TICKER"/>|<xsl:value-of select="SEC_NAME"/>|<xsl:value-of select="ORDER_QTY"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet> The output we're seeing is just data, no header... 113632428|31393FHA7|FHR|FHR 2527 SG|169249.6824 113632430|31393G2C7|FHR|FHR 2531 ST|214673.0105 113632431|527069AH1|LESL|ZZZ_LESLIE S POOLMART INC|365000.0000 113632434|38470RAD3|GRAHAM|ZZZ_GRAHAM PACKAGING CO|595000.0000 Please disregard any namespace inconsistencies; I had to obfuscate the xml and xsl for legal reasons. A: Try this : <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="text" indent="no"/> <xsl:template match="/"> <xsl:for-each select="tradedata/tradedata_item[1]/*"> <xsl:value-of select="concat(name(), '|')"/> </xsl:for-each> </xsl:template> </xsl:stylesheet> Output : ORDER_ID|CUSIP|TICKER|SEC_NAME|ORDER_QTY| It seems pretty simple to me. Maybe your error lies elsewhere. A: I tried your code.. I only changed the first template to match: <xsl:template match="//tradedata_item[1]"> and it worked for me, i.e. got the header names. A: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl ofi" version="1.0" xmlns="http://schemas.com/enterprise/util/extractservice/v1" xmlns:ofi="http://schemas.oppen.com/enterprise/util/extractservice/v1"> <xsl:output method="text" indent="no"/> <xsl:template match="tradedata_item[position()='1']"> <xsl:for-each select="self::*"> <xsl:for-each select="child::*[position()!='5']"> <xsl:value-of select="local-name(self::*)"/>| </xsl:for-each> <xsl:value-of select="local-name(child::*[position()='5'])"/> <xsl:text> </xsl:text> <xsl:value-of select="ORDER_ID"/>|<xsl:value-of select="CUSIP"/>|<xsl:value-of select="TICKER"/>|<xsl:value-of select="SEC_NAME"/>|<xsl:value-of select="ORDER_QTY"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:template> <xsl:template match="tradedata_item[position()&gt;1]"> <xsl:for-each select="self::*"> <xsl:value-of select="ORDER_ID"/>|<xsl:value-of select="CUSIP"/>|<xsl:value-of select="TICKER"/>|<xsl:value-of select="SEC_NAME"/>|<xsl:value-of select="ORDER_QTY"/> <xsl:text>&#10;</xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet>
{ "language": "en", "url": "https://stackoverflow.com/questions/7589831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Event Listener on Text Field I have a text input on a form that I need to check if the value has changed at anytime. Essentially the text input is a date field and I'm using a 3rd parties script to popup a calendar where you can select a date which is then set as the text field value. So here is my problem. Say when the form is loaded the text field already has a value of 1/1/11 if someone clicks on the field and changes it with the keyboard to 1/2/11 or anything else my event listener kicks off and executes the function I want. My problem is that if someone clicks the calendar icon and selects a date though it changes the value of the input field it doesn't kick off the event handler. I've tried using onchange event handler directly on the input box and an event listener for the input box and it appears both only pick up the change when focus on the field has changed. Here is the event listener script the way it sits now.. document.getElementById('anchor1x').addEventListener('change', function() { alert("date changed"); }, false); Is there something else I can do to check if the field value is changed be it by user input through direct typing or through the calendar select? A: Perhaps add an event listener to the icon as well? That way when its selected, it'll also fire.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: asp:TabContainer not styled after deployment, then just fixes itself? I have an asp:TabContainer on a form and after the app is re-deployed to the server, the tabs aren't styled. If I take the Webresource.axd URL and try to load it in the browser, I get a redirect to a login page, so it seems like an authentication problem, yet the rest of the app has already been logged in long before you get to the page with the tab control. A restart of the web server and even a reboot don't appear to affect it. Then, eventually the styles start working and do not stop working until another deployment, when it usually exhibits the same behavior. Is there some kind of caching or permissions issue going on? Here's the authentication from the web.config: <authentication mode="Forms"> <forms name=".ASPXAUTH" protection="All" timeout="2400" loginUrl="Default.htm"/> </authentication> A: The Problem is protection level(ALL). Make it CSS files are available to non protected pages. <location path="cssname.css"> <system.web> <authorization> <allow users="*"/> </authorization> </system.web> </location> Learn More about Setting authorization rules for a particular page or folder in web.config A: if u have changes the cssclass of the tab container, it will look like this.. if u want to completely change the look of tabcontainer u have to include the entire css of the tab container .tab { margin:5px 0px 5px 0px; } .tab .ajax__tab_header { font-family: arial,helvetica,clean,sans-serif; font-size: small; border-bottom: solid 5px #00B3B2; padding-left: 50px; } .tab .ajax__tab_header .ajax__tab_outer { background: url(../Images/sprite.png) #d8d8d8 repeat-x; margin: 0px 0.16em 0px 0px; padding: 1px 0px 1px 0px; vertical-align: bottom; border: solid 1px #a3a3a3; border-bottom-width: 0px; border-radius: 5px 5px 0px 0px; } .tab .ajax__tab_header .ajax__tab_tab { color: #000; padding: 0.35em 0.75em; margin-right: 0.01em; } .tab .ajax__tab_hover .ajax__tab_outer { background: url(../Images/sprite.png) #bfdaff repeat-x left -1300px; cursor: pointer; } .tab .ajax__tab_active .ajax__tab_tab { color: #fff; } .tab .ajax__tab_active .ajax__tab_outer { background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAADICAYAAAAp8ov1AAAAAXNSR0IArs4c6QAAAAZiS0dEAAAAAAAA+UO7fwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oJGA41KpTYroIAAACASURBVCjP7ZE7DsJADESfJiL37znNXoJLUNARa7Ni6Bw5AtFEqXAx8vj/wfZNwBBAakPAWukQEJUu1RGVLt9su4yo9eJ3t0FrDWyTg58HezlujFPE9lXAQ8BdQM93R9LtM2ve/vnB22tcF/DaTpItJwHKVWcBk4BLwlw1/nAUvAGm30u0udPq+QAAAABJRU5ErkJggg==") #00B3B2 repeat-x left -100px; } .tab .ajax__tab_body { font-family: verdana,tahoma,helvetica; font-size: 10pt; padding: 0.25em 0.5em; border: solid 1px #00B3B2; border-bottom:0px; border-right:0px; border-top-width: 0px; } now just include the cssclass for the tab container
{ "language": "en", "url": "https://stackoverflow.com/questions/7589839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: About generating sound waveform in an ActionScript 3 Bitmap I am generating Bitmap object to show the sound waveform of a loaded sound. The bitmap is 1024x120 and after it has been generated I shrink its size to 655x120. My problem is the player that loads the bitmap in task manager becomes 260MB heavy. I am also adding some gradients and I also cache it as bitmap, but if I remove this properties I dont get any big difference in size. I also can try to small its size but still I think the bitmap will be big. Any idea how to compress or whatever solution to solve this problem? thanks Here is some code These are the sound and Bitmap settigns of the function that generate the bitmap. public function generateBitmap(snd:Sound):void { samples = new ByteArray(); buffer = new BitmapData(1024, 120, false, backColor); screen = new Bitmap(buffer); rect = new Rectangle(0, 0, 1, 0); var left:Number; var right:Number; screen.x = 0; screen.y = 0; screen.width = 655; screen.height = 120; buffer.fillRect( buffer.rect, backColor ); Now I am doing some samples extraction var extract:Number = Math.floor ((snd.length / 1000) * 44100); playingTime = snd.length; ratio = playingTime / buffer.width; var lng:Number = snd.extract(samples, extract); samples.position = 0; step = samples.length / 4096; do { step-- ; } while ( step % 4 ); Follows the drawing method of the bitmap. for (var c:int = 0; c < 4096; c++) { rect.x = c / 4; left = samples.readFloat() * 25; right = samples.readFloat() * 25; samples.position = c * step; // left channel if (left > 0) { rect.y = 30 - left; rect.height = left; } else { rect.y = 30; rect.height = -left; } buffer.fillRect( rect, leftChColor ); // right channel if (right > 0) { rect.y = 80 - right; rect.height = right; } else { rect.y = 80; rect.height = -right; } buffer.fillRect( rect, rightChColor ); } screen.width = screenWidth; screen.height = screenHeight; addChild( screen ); } Here is a reference of the code I have used. Tried it without my stuff in the player and get 193MB of RAM just for the flash player. So the code needs I guess the code needs refinement. Any idea or othere method to do the same stuff without eating so much RAM? A: Before this line: buffer = new BitmapData(1024, 120, false, backColor); Add: if ( buffer ) { buffer.dispose(); buffer = null; } buffer = new BitmapData(1024, 120, false, backColor);
{ "language": "en", "url": "https://stackoverflow.com/questions/7589840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why doesn't this CSS :first-child selector work? I'm working on an Asp.Net MVC 3 project and have run into a brick wall on why this doesn't work like I think it should. My markup is: <fieldset> <input type="hidden" value="2"> <div class="editor-label"> <label for="Name"> Name</label> </div> ... </fieldset> My css is: .display-label, .editor-label { margin: 0.8em 0 0 0; font-weight: bold; display: inline; } fieldset > div:first-child { margin: 0; } All I want to do is make the first div in the fieldset have a margin of 0. I thought that the selector fieldset > div:first-child would apply the style to "the first child of a fieldset, whose type is a div", but apparently something is eluding me. I've tried this in IE9/FF/Chrome so it's not an old browser messing with my selectors. Thanks. A: fieldset > div:first-child means "select the first child element of a fieldset if it's a div". It does not mean "select the first div in the fieldset". The first child in this case is <input type="hidden" value="2">. To select that div without changing the HTML, you need to use fieldset > div:first-of-type. Unfortunately, while :first-child is widely supported, :first-of-type only works in IE9+ and other modern browsers. So, in this case, the best fix is to continue using fieldset > div:first-child, and simply move <input type="hidden" value="2"> so that's it's not the first child.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Which parser generator would be useful for manipulating the productions themselves? Similar to Generating n statements from context-free grammars, I want to randomly generate sentences from a grammar. What is a good parser generator for manipulating the actual grammar productions themselves? I want the parser generator to actually give me access to the productions (production objects?). If I had a grammar akin to: start_symbol ::= foo foo ::= bar | baz What is a good parser generator for: * *giving me the starting production symbol *allow me to choose one production from RHS of the start symbol ( foo in this case) *give me the production options for foo Clearly every parser has internal representations for productions and methods of associating the production with its RHS, but which parser would be easy to manipulate these internals? Note: the blog entry linked to from the other SO question I mentioned has some sort of custom CFG parser. I want to use an actual grammar for a real parser, not generate my own grammar parser. A: It should be pretty easy to write a grammar, that matches the grammar that a parser generator accepts. (With an open source parser genrator, you ought to be able to fetch such a grammar from the parser generator source code; they all then to have self-grammars). With that, you can then parse any grammar the parser generator accepts. If you want to manipulate the parsed grammar, you'll need an abstract syntax tree of same. You can make most parser generators build a tree, either by using built-in mechanisms or ad hoc code you add.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How is insertAdjacentHTML so much faster than innerHTML? About a month ago, Firefox 8 implemented the insertAdjacentHTML method, which was added to IE4 along with innerHTML. According to this benchmark, insertAdjacentHTML is usually an order of magnitude faster than innerHTML. I assume both call the same HTML parser, so why is the difference that dramatic? insertAdjacentHTML is a simple method call, whereas innerHTML is a getter/setter and there's probably a bit of overhead for that, but I would never imagine that much. A: work.innerHTML += "<span>test</span>"; is equivalent to work.innerHTML = work.innerHTML + "<span>test</span>";, i.e. each time it runs it has to serialise all the existing contents of work and then reparse the whole lot, plus the additional span. work.insertAdjacentHTML("BeforeEnd", "<span>test</span>"); is only parsing the one span each time and then attaching the small document fragment to the DOM. A: The innerHTML setter will have to remove all existing child nodes prior to adding new ones. Don't know if this is the only reason, but that's certainly a factor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Change C object instance to Python subclass Is it possible to change a class of a C object to a python subclass? I am using PyGTK, and I have a ListModel that I have wrapped my own class around, but I want to turn it into a TreeModelFilter. The directions tell me to create it by doing: class MyListStore(gtk.ListStore): def __init__(self, title): self.title = title liststore = MyListStore(gobject.TYPE_INT, gobject.TYPE_STRING) modelfilter = liststore.filter_new() So I thought I could just create: class MyFilteredListStore(gtk.TreeModelFilter): def __init__(self, title): self.title = title But I don't know how to use filter_new to use my class, instead of gtk.TreeModelFilter. A: Inheritance can be a very fluid concept in python. For starters, you should always use new style classes. To do that, make sure your classes should always inherit from "object". It's important to note that Classes must inherit from other classes, not instances of other classes, so your example really wouldn't work there. In fact, I don't really see the difference between inheriting from X or x1. Inheritance in python is closely tied to the "Method Resolution Order" (MRO). You can view an objects MRO using the inspect module. >>> import inspect >>> import pprint >>> >>> class X(object): ... pass ... >>> class Y(X): ... pass ... >>> >>> pprint.pprint(inspect.getmro(Y)) (<class '__main__.Y'>, <class '__main__.X'>, <type 'object'>) >>> The tuple at the end shows the order in which python will try to resolve method and attribute calls. You can modify the MRO at runtime by modifying a class's __bases__ attribute. >>> Y.__bases__ (<class '__main__.X'>,) >>> >>> class Z(object): ... pass ... >>> Y.__bases__ = tuple([Z]) >>> pprint.pprint(inspect.getmro(Y)) (<class '__main__.Y'>, <class '__main__.Z'>, <type 'object'>) >>> This can get complicated if any of your classes use multiple inheritance, or if you want to preserve certain parts of the inheritance tree but not others. A: The best way to handle this problem is not to subclass the TreeModel, but to assign a variable to the object that can be the ListStore or the TreeModelFilter. class MyListStore(object): def __init__(self, title, filter=None): self.title = title self._model = gtk.ListStore(gobject.TYPE_INT, gobject.TYPE_STRING) if filter_func: self._model = self.model.filter_new() self._model.set_visible_func(filter) I think this is the best way to get around this. Edit For anyone interested, I found the following to be helpful to keep from breaking old code. It acts like inheritance, without actually doing so: def __getattr__(self, name): 'Get the attribute from the model if possible.' if hasattr(self._model, name): return getattr(self._model, name) if isinstance(self._model, gtk.TreeModelFilter): if hasattr(self._model.get_model(), name): return getattr(self._model.get_model(), name)
{ "language": "en", "url": "https://stackoverflow.com/questions/7589861", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: capturing project/product whiteboard: recommendation webcam + webapp solution We are doing kanban and have a whiteboard with colored stickers. As sometimes the team is distributed (like home office) we need to have another visual access to that board. We want to do this with stationary webcam everybody can access. Our requirements: * *good quality picture *making stickers notes readable (description etc.), either by physical zoom or enlarging parts through high resolution *access to the camera by browser-webapp, alternatively instant-messaging *hardware/software setup compatible with linux OS Did somebody of you setup such a thing? What are your lessons learned? Having a physical wall with real notes is important. Going for another project-management webapplication is not an option for us. A: Have you considered using an electronic story board? I know it's not as good as the real deal, but with a distributed team that's the only viable option I think. A good post about that: http://agiletools.wordpress.com/2007/11/24/task-boards-telling-a-compelling-agile-story/ (middle to end of the page)
{ "language": "en", "url": "https://stackoverflow.com/questions/7589869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Like Meta Tags not showing correct image Possible Duplicate: How does Facebook Sharer select Images? I'm using javascript to set the metatags for og: values and the FB Debugger is telling me that I need to explicitly set the meta tags for URL, Title and Image. I am seeing the metatags show up correctly in Firebug - they are there, but FB and the Like button aren't seeing them for some reason. Here's the JS: function setMT(metaName, name, value) { var t = 'meta['+metaName+'='+name+']'; var mt = $(t); if (mt.length === 0) { t = '<meta '+metaName+'="'+name+'" />'; mt = $(t).prependTo('head'); } mt.attr('content', value); } and in the jQuery document ready I set the meta tags setMT('property', 'og:title', 'PAGE_TITLE'); setMT('property', 'og:url', 'CURRENT_URL'); setMT('property', 'og:image', 'IMAGE_URL'); etc. Anybody know if FB doesn't like my method? I can't set hard values for these meta tags, they are dynamically generated for on an e-commerce platform so I need to create the VARS in the template and use jQuery to pass them to the page content where I create the meta tags and prepend them to the HEAD of the document. Scratching my head a little on this one. A: Javascript is only working in the user's browser. Facebook open graph crawler (and debugger based on it) call your page server to server and don't interpret any javascript. Therefore they don't see your tags. You should set them dynamically using any server-side language like php or asp.net, etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make browser not to refresh full page when it goes to URL? I tried to understand - is it any method to ask browser not to refresh entire page when user clicks onto . Hash adding method is seen - I need another method, working with links without hashes. May be any headers should be sent ? Or something another ? I want to process GET queries returning only the part of HTML (or special js commands), not all page, and process it in AJAX-style. A: You can ajaxify your links through jquery. Something like this: $('a.ajax').click(function(ev){ ev.preventDefault(); var target=$(this).attr('data-target'); var url=$(this).attr('href'); $(target).load(url+' '+target); } This can be used in conduction with the following HTML: <div id="output"> Hello <a href="world.html" class="ajax" data-target="#output">World</a> <div> and inside world.html you would need to have: <div id="output"> Foo bar baz boo </div> In theory this should load content of the dif from "world" file into the div inside the first file, but I haven't tried it. I think it's what you need, because the regular link is still there, google will properly index this bypassing ajax and your users will be happy to see part of the page change. A: you could make it 'fake' links doing something like this: <span style="cursor:pointer;" onclick="loadPage('mypagename');">My Link</span> The function then would be: function loadPage(pageName){ // do ajax call here using pageName var } A: You cannot prevent navigation when a user clicks a hyperlink with a URL. Using a hash value to navigate or having your hyperlinks invoke JavaScript is generally the way to add navigation inside of a single page. However, if you're trying to convert an existing page that's not designed this way, you would have to use JavaScript to modify hyperlinks so they invoke Ajax. For example: var links = document.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { var oldUrl = links[i].getAttribute('href'); links[i].setAttribute('href', 'javascript:void(0)'); links[i].onclick = (function(url) { return function() { // Then you can do your AJAX code here } })(oldUrl); } I recommend that you don't do something like this, though, and rather create your page with an AJAX design in mind. A: Changing the url without using hashes can be achieved with the Html5 History API: http://html5demos.com/history Not supported by older browser though, so you must always have a fallback.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL update function, know which cell I want, how to find row I want to update a row like this: _id, AttributeA, AttributeB, AttributeC I need to find a row based on AttributeC so that I can update it, lets say the desired AttributeC contains value "X" How would this be done? I believe this would be done with a WHERE argument but can I get this whole statement spelled out? A: Something like UPDATE table SET AttributeB='value' WHERE AttributeA = 'X' This will update all rows where AttributeA = 'X' and set AttributeB to 'value', if there are more than 1. A: Start by looking at the UPDATE syntax. If you get stuck, show us what you've tried and we can help further A: update TableA set AttributeC = 'XXX' where AttributeC like "%X%"
{ "language": "en", "url": "https://stackoverflow.com/questions/7589882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get right page? I use htmlunit library for scrapping Yellowpages.com site. I want to type search term into and click on Find button. But after that I get 2 pages: http://www.yellowpages.com/ny/sport?g=NY&q=Sport and https://dealoftheday.yellowpages.com/join?ic=deal_pop-under_signup-v- First one is what I want, second one is popup. I have this code: public void getPage() throws FailingHttpStatusCodeException, MalformedURLException, IOException { WebClient webClient = new WebClient(); page = webClient.getPage("http://www.yellowpages.com"); HtmlTextInput searchInput = (HtmlTextInput) page.getElementById("search-terms"); searchInput.setText("Law"); HtmlSubmitInput button = (HtmlSubmitInput) page.getElementById("search-submit"); page = button.click(); System.out.println(page.getTitleText()); } This code prints: Deal of the Day on YP.com - Join But I want to print first page title, which is: NY Sport | Sport in NY - YP.com How to get first page? EDIT: After adding line webClient.setPopupBlockerEnabled(true), I got a lot of warnings and after that I got exceptions. Here is a part of console output: Exception in thread "main" ======= EXCEPTION START ======== EcmaError: lineNumber=[56] column=[0] lineSource=[null] name=[TypeError] sourceName=[http://i2.ypcdn.com/webyp/javascripts/home_packaged.js?13455] message=[TypeError: Cannot call method "blur" of null (http://i2.ypcdn.com/webyp/javascripts/home_packaged.js?13455#56)] com.gargoylesoftware.htmlunit.ScriptException: TypeError: Cannot call method "blur" of null (http://i2.ypcdn.com/webyp/javascripts/home_packaged.js?13455#56) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:601) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:537) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:538) at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:531) at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:906) at com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer.executeEventListeners(EventListenersContainer.java:164) at com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer.executeBubblingListeners(EventListenersContainer.java:223) at com.gargoylesoftware.htmlunit.javascript.host.Node.fireEvent(Node.java:686) at com.gargoylesoftware.htmlunit.html.HtmlElement$2.run(HtmlElement.java:885) at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:537) at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:538) at com.gargoylesoftware.htmlunit.html.HtmlElement.fireEvent(HtmlElement.java:890) at com.gargoylesoftware.htmlunit.html.HtmlElement.fireEvent(HtmlElement.java:865) at com.gargoylesoftware.htmlunit.html.HtmlForm.submit(HtmlForm.java:108) at com.gargoylesoftware.htmlunit.html.HtmlSubmitInput.doClickAction(HtmlSubmitInput.java:77) at com.gargoylesoftware.htmlunit.html.HtmlElement.click(HtmlElement.java:1263) at com.gargoylesoftware.htmlunit.html.HtmlElement.click(HtmlElement.java:1214) at com.gargoylesoftware.htmlunit.html.HtmlElement.click(HtmlElement.java:1177) at YellowPages.getPage(YellowPages.java:39) at YellowPages.main(YellowPages.java:22) Caused by: net.sourceforge.htmlunit.corejs.javascript.EcmaError: TypeError: Cannot call method "blur" of null (http://i2.ypcdn.com/webyp/javascripts/home_packaged.js?13455#56) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3772) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3750) at net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime.typeError(ScriptRuntime.java:3778) A: Sounds like a JS error. Disable JS: webClient.setJavaScriptEnabled(false); And what about? webClient.setThrowExceptionOnScriptError(false); Add webClient.getOptions() if using HtmlUnit 2.11+ A: Have you tried webClient.setPopupBlockerEnabled(true) Then you should get only one page A: Not tested, but I think you might iterate through the WebClient's top level windows (using WebClient.getTopLevelWindows()), call getEnclosedPage() and test if the title text of the page is the one you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: facebook app not redirecting when aurizing When I first authorize a user it goes and stays on the Canvas URL(my site) instead of redirecting back to the Canvas Page on facebook.How can I make sure once the user authorizes they go to the Canvas Page? $(function() { FB.init({ appId: 'myappid', status: true, cookie: true, xfbml: true, oauth: true }); FB.getLoginStatus(function(response){ if(!response.authResponse){ top.location.href="http://www.facebook.com/dialog/oauth?client_id=myid&redirect_uri=http://mysite/myapp" }else{ FB.api('/me',function(response){ uname = response.name; userid = response.id; $.post("signin.php", { name:uname,id:userid}, function(data) { }); }); } }); }); A: In your code, change the redirect_uri value from: http://mysite/myapp to: http://apps.facebook.com/appnamespace
{ "language": "en", "url": "https://stackoverflow.com/questions/7589888", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How dangerous is Django's built in test server when run remotely? Concerning the built in debugging server started with the manage.py runserver command, the Django docs state, "DON’T use this server in anything resembling a production environment." If I wanted to develop a Django application over ssh on a remote machine, would using Nginx as a proxy to a running Django debug server be a reasonable thing to do? Is the Django debug server insecure, or just not built to handle large amounts of traffic? A: From the Django docs: DO NOT USE THIS SERVER IN A PRODUCTION SETTING. It has not gone through security audits or performance tests. (And that's how it's gonna stay. We're in the business of making Web frameworks, not Web servers, so improving this server to be able to handle a production environment is outside the scope of Django.) So, that answers the latter two questions. As for the former, it depends on how your debug server is set up. If your server is exposed to the public Internet, doesn't have a firewall blocking port 8000, and you intend to use runserver with something other than the default 127.0.0.1 address, set up a more 'proper' application stack. If you're going to use nginx, why not just use the suggested FastCGI configuration so that your debug environment will be more similar to the future production environment? A: Modern web servers have all sorts of features, related to both security and performance, that the Django development server does not. It is a stripped-down, very basic, single-threaded server for the purposes of development. Hence why the docs say to not use it in a production setting. However, people get way to afraid of this statement. The key defining point is that it's for development. Whether that development takes place on your local machine or a remote VPS or an entire cluster is besides the point. If the server is publicly available, it will be open to hacking, breaches, DoS attacks, etc. But, if what's there isn't of any importance, just a development site running on dummy data, it doesn't matter. So, yes, you can use the development server on your remote server for development purposes. There's nothing at all wrong with that. My only caution would be to avoid using production data (such as using a dump from your production database to develop against) because that data could be compromised. Otherwise, it's no big deal. A: Is the Django debug server insecure, or just not built to handle large amounts of traffic? IT IS BOTH INSECURE AND NOT INTENDED FOR HEAVY TRAFFIC! It might take care of a few of the issues by hiding the testing server behind a proxy, but if you're going to that much trouble you've done about the same amount of work as you need to do it right... right being WSGI. Use mod_wsgi, gunicorn, or check this out for more bleeding-edge solution: http://bartek.im/blog/2012/07/08/simplicity-nginx-uwsgi-deployment.html. Whatever you do.... DON'T USE THE DJANGO TEST SERVER FOR PRODUCTION ENVIRONMENTS!
{ "language": "en", "url": "https://stackoverflow.com/questions/7589890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: In C, how to initialize a pointer-to-pointers from inside a function? Following this answer, I made a simple example to be sure I properly understood: #include <stdlib.h> #include <stdio.h> typedef struct { int x; } data; void fill_data (data *** ptr_all, int l) { int i = 0; *ptr_all = (data**) calloc(l, sizeof(data)); if ((*ptr_all) == NULL){ fprintf(stderr, "error: can't allocate memory"); abort(); } for (i = 0; i < l; i++) { data * d = (data*) calloc(1, sizeof(data)); if (d == NULL){ fprintf(stderr, "error: can't allocate memory for %i-th data", i+1); abort(); } d->x = i; (*ptr_all)[i] = d; } } int main(int argc, char *argv[]) { int i = 0, l = 5; data ** all = NULL; fill_data (&all, l); for (i = 0; i < l; i++) { printf("%i\n", all[i]->x); } return EXIT_SUCCESS; } However, after compiling and running it, I see that the first element is wrong: $ gcc -Wall test.c $ ~/bin/a.out 161276080 1 2 3 4 I can see that in my function fill_data I don't initialize ptr_all, but only *ptr_all, and this may be the cause of the problem. But how should I do? A: Change: *ptr_all = (data**) calloc(l, sizeof(data)); to: *ptr_all = (data**) calloc(l, sizeof(data*)); You're allocating l ints whereas you need to be allocating l pointers. You're almost certainly building and running this on a 64 bit OS (where sizeof(void *) > sizeof(int)), otherwise this bug would have remained dormant.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I preserve directory structure when compiling CoffeeScript? I am new to Coffeescript and I wonder where I should put them. Eg. I have my app folder: app/app.js tests/unit/all.js etc When I use the "coffee" runner on node.js to watch my files in the root folder it will generate js files to a folder I specify eg. js. So if the folder to be watched is looking like this: app/app.coffee tests/unit/all.coffee etc JS files will be generated to: js/app.js js/all.js etc As you can see I lose my js folder hierarchy. How are you supposed to retain your original folder hierarchy? Thanks A: I believe you want coffee -cwo js . That will compile app/foo.coffee to js/app/foo.js, and test/bar.coffee to js/test/bar.js. As long as you stick to passing folder names to the coffee command, rather than individual file names, directory structure will be preserved. A: It's not advised to do recursive watches, but for discussion on look here: https://github.com/jashkenas/coffee-script/issues/932
{ "language": "en", "url": "https://stackoverflow.com/questions/7589899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Rails devise registration How can I modify attributes of User instance before save in custom registrations controller, inherited from Devise::RegistrationsController? A: You gave the answer yourself. In your model do: class User < ActiveRecord::Base before_save :set_attributes def set_attributes // Change the attributes to what you like end end
{ "language": "en", "url": "https://stackoverflow.com/questions/7589907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "Cannot uninstall Language Pack 0 because it is not deployed" when attempting to uninstall-spsolution on sharepoint 2010 foundation I continue to get this error message "Cannot uninstall Language Pack 0 because it is not deployed" when running the uninstall-spsolution cmdlet. I've attempted a number of alternate syntaxes to no avail. (tried add -language 1033 for example) I see a few other similar issues on the web, but nothing specifically addressing my issue. I know the solution exists. not sure why the Language Pack issue is arising. (by the way...i can see my solution using Sharepoint manager 2010). I've tried a number of anyway, any help would be appreciated. thanks. (Note: was unable to upload image of error from powershell command shell due to site restriction). A: While I like the answer above and I think it would work some of the time, in my case I had to remove the Errored out WSP from the solution store and then re-add it and then install/deploy it again. After that my updates were working fine again. A: I'm also seeing this error in one of our farms when I run the Update-SPSolution commandlet. Recently, we updated the farm with foundation and server Service Pack 1, the associated server language packs and the June Cumulative update. By chance, is this the patch level of your farm? Interestingly, I have no trouble running Update-SPSolution in another farm patched to the same level. The bottom-line is that I don't think this is limited to Uninstall-SPSolution or Update-SPSolution. I just resolved the issue by doing the following: * *Checked the solution store and saw that the solution I was updating was not deployed *I attempted to deploy the solution and saw that it was stuck in the deployment stage *From services.msc I stopped and restarted the SharePoint 2010 Timer service and the SharePoint 2010 Administration service. I don't normally stop and start SharePoint services from Services, but that seemed to do the trick. I also don't know whether it's necessary to recycle both of these services. *I then returned to the command line and was able to successfully update the solution. Please let me know if this works for you. A: I had the same issue, I opened the manage solutions in central admin and there was an error message next to my solution. The error message was actually helpful, it directed me to solve the issue. I have added -force while installing the solution using power shell command then it worked fine. After that I deactivated and reactivated the feature just in case. A: I've got the same problem and restarting the services was not enough for me. Then, I solved doing: * *Retract and then Remove of the wsp from: Central Administration–>System Settings–> Manage farm solutions. *Then, from Powershell, I have canceled the Features with null scope (which were preventing me to install again the package succesfully): Get-SPFeature | ? { $_.Scope -eq $null } $feature = Get-SPFeature | ? { $_.Scope -eq $null } $feature.Delete() *And at the end I have installed again the wsp: Add-SPSolution -LiteralPath Path Install-SPSolution -Identity Name.wsp -WebApplication WebApplicationPath –GACDeployment Then it worked :) Update: I've just got this problem again, but this time there weren't features with null scope, so it has been enough just to add -Force while installing the wsp. A: I had the same issue and after redeploying solution it's gone.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589908", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Android - Save HTML 5 Canvas to png I have a webapp that uses an HTML 5 canvas to allow the user to draw. I need to save this to the sdcard as a png. I can get the base64 by using .toDataURL() but I can't figure out how to use that to save the file. I am using Phonegap, not sure if that can be used to help. Or maybe I could pass the data to Java and do it from there, but I'm not that familiar with Java. A: try Canvas2Image lib http://www.nihilogic.dk/labs/canvas2image/ A: I wrote a similar thing: https://github.com/jimdoescode/jqScribble Included in that repo is a PHP script for saving the base64 data as an actual image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting controls in a Telerik GridView cell Here's a concrete example of what I am attempting to do with the Telerik GridView control. Let's say I have an application that will read a delimited file (say CSV) which will have n columns. The value n can vary from file-to-file but is constant within a file. The application starts with an empty grid and adds columns as required to match the input file. The grid displays all data as strings in all cells. This works with either binding to a BindingList or putting the record (objects) into the GridView.Items list. Now, what I want to do is put a single row at the top of the grid (a row that will not scroll) that contains comboboxes. That is, at the top of each column, the first row contains a combobox. On the first pass, the combobox will only be a drop list, but on the next pass I will add another row with a set of comboboxes that will be editable. For now, let's only consider drop lists. The specific problem that I have is that I do not see how to set a specific type of control for a particular cell. Telerik provides a GridViewComboBoxColumn class that will define the behavior for an entire column but that's not what I need. Because of the variable number of columns, I think that the code-behind would be the place to work this magic. I may have to do something in the xaml but, since I've only been in WPF for a few months, nothing is jumping out at me. I've done something like this with the DataGridView and XtraGrid, but this one has me stumped. Pointers would be much appreciated. In response to Jonathan D's answer, I have taken the provided code and modified it to recognize when a cell on the 0th row is being edited. When this is the case, a drop list is presented when the user initiates an edit operation. using Telerik.Windows.Controls; using Telerik.Windows.Controls.GridView; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace LLamasoft.DataGuru.Plugin.Internal.ConfigurationUI { public class RadGridViewComboboxHeaderColumn : GridViewBoundColumnBase { public static readonly DependencyProperty SelectedStringProperty = DependencyProperty.Register("SelectedString", typeof(string), typeof(RadGridViewComboboxHeaderColumn), new PropertyMetadata(null)); public string SelectedString { get { return (string) GetValue(SelectedStringProperty); } set { SetValue(SelectedStringProperty, value); } } public override FrameworkElement CreateCellEditElement(GridViewCell cell, object dataItem) { // we need the row on which this cell lives GridViewDataControl gridViewDataControl = cell.ParentRow.GridViewDataControl; object currentEditItem = gridViewDataControl.Items.CurrentEditItem; int index = gridViewDataControl.Items.IndexOf(currentEditItem); FrameworkElement frameworkElement = null; if (index == 0) { BindingTarget = ComboBox.SelectedValueProperty; ComboBox comboBox = new ComboBox(); // seed some values, // this list should be set right after construction if static, otherwise via callback if dynamic comboBox.Items.Add(string.Empty); comboBox.Items.Add("apples"); comboBox.Items.Add("oranges"); if (!comboBox.Items.Contains(cell.Value)) { comboBox.Items.Add(cell.Value); } comboBox.SelectedValue = SelectedString; frameworkElement = comboBox; } else { BindingTarget = TextBox.TextProperty; TextBox textBox = new TextBox(); textBox.Text = SelectedString; frameworkElement = textBox; } frameworkElement.SetBinding(BindingTarget, CreateValueBinding()); return frameworkElement; } public override object GetNewValueFromEditor(object editor) { // ensure that the control will return the correct value when queried for it ComboBox comboBox = editor as ComboBox; if (comboBox != null) { // bound to comboBox.SelectedValue which carries the correct value } TextBox textBox = editor as TextBox; if (textBox != null) { // bound to textBox.Text which carries the correct value } return base.GetNewValueFromEditor(editor); } private Binding CreateValueBinding() { Binding valueBinding = new Binding(); valueBinding.Mode = BindingMode.TwoWay; valueBinding.NotifyOnValidationError = true; valueBinding.ValidatesOnExceptions = true; valueBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit; valueBinding.Path = new PropertyPath(this.DataMemberBinding.Path.Path); return valueBinding; } } } The good news is that this shows that any edit control can be used in any cell based on requirements. The bad parts are: 1) a dummy record has to be inserted at the 0th list position and must be maintained there, 2) the data is being stored back into the field on the 0th record and may require a different data type than is on the equivalent fields on the other records, and 3) the combobox is only shown when the cell is in the edit mode. The latter issue for me may not be an issue elsewhere. I want a visual cue that the user is expected to interact with the cells at the top of the columns. Using this method, there is no differentiating factor between the top row and the rest of the rows until the edit operation begins. My ideal solution would have the cells always show their comboboxes. One other issue that I find difficult to believe that I am facing is the fact that I cannot easily pin/freeze topmost rows. I want this line to always remain at the top after scrolling. There is no _grid.Rows[0].IsPinned = true functionality. Telerik has responded to my request for info and suggests that I use a template selector to determine how the cell is represented. (http://www.telerik.com/community/forums/wpf/gridview/need-just-first-row-in-grid-to-be-all-comboboxes.aspx#1820310). At this point, I turn my attention to testing that method. A: You want to create your own column using System.Windows; using System.Windows.Data; using Telerik.Windows.Controls; using Telerik.Windows.Controls.GridView; using System; namespace Inspect { public class DateTimePickerColumn : GridViewBoundColumnBase { public TimeSpan TimeInterval { get { return (TimeSpan) GetValue(TimeIntervalProperty); } set { SetValue(TimeIntervalProperty, value); } } public static readonly DependencyProperty TimeIntervalProperty = DependencyProperty.Register("TimeInterval", typeof(TimeSpan), typeof(DateTimePickerColumn), new PropertyMetadata(TimeSpan.FromHours(1d))); public override FrameworkElement CreateCellEditElement(GridViewCell cell, object dataItem) { this.BindingTarget = RadDateTimePicker.SelectedValueProperty; RadDateTimePicker picker = new RadDateTimePicker(); picker.IsTooltipEnabled = false; picker.TimeInterval = this.TimeInterval; picker.SetBinding(this.BindingTarget, this.CreateValueBinding()); return picker; } public override object GetNewValueFromEditor(object editor) { RadDateTimePicker picker = editor as RadDateTimePicker; if (picker != null) { picker.DateTimeText = picker.CurrentDateTimeText; } return base.GetNewValueFromEditor(editor); } private Binding CreateValueBinding() { Binding valueBinding = new Binding(); valueBinding.Mode = BindingMode.TwoWay; valueBinding.NotifyOnValidationError = true; valueBinding.ValidatesOnExceptions = true; valueBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit; valueBinding.Path = new PropertyPath(this.DataMemberBinding.Path.Path); return valueBinding; } } } That is how you create a custom column. If you modify the CreateCellEditElement Method it will let you create custom cells how you like. You should even be able to detect the row number
{ "language": "en", "url": "https://stackoverflow.com/questions/7589912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Automatically dismiss underling modal view I'm sharing this as it took me A while to figure out. This is if you need to get rid of a double stack of modal views IF it is pressent. if(self.parentViewController.parentViewController) [self.parentViewController.parentViewController dismissModalViewControllerAnimated:YES]; else [self dismissModalViewControllerAnimated:YES]; I have a view that sometimes gets called from a modal view. In that case I would need to get rid of both views at the same time. While dealing with the situation where it was the only modal view. This worked. A: As of xCode 4.2 this is no longer working, The new way to deal with this situation is: if(self.presentingViewController.presentingViewController) [self.presentingViewController.presentingViewController dismissModalViewControllerAnimated:YES]; else [self dismissModalViewControllerAnimated:YES]; As pointed out by @Hollance in a relevant thread of mine: iOS 5 SDK treating UIViews differently "There is a new property in iOS 5 named presentingViewController. The meaning of parentViewController got changed a bit with the new container view controller API, so it may not always be set when you think it is. That's what presentingViewController is now for."
{ "language": "en", "url": "https://stackoverflow.com/questions/7589914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to force html/css padding/margin on an element? How can I add/force bottom margin/padding to the following <a> element ? <p> <h31>Testing?</h31> <a style="margin-bottom: 200px">Create a new Entry</a> testing padding /*more stuff here...*/ Styles are very convoluted and the margin-bottom: 200px is not forcing the padding after the <a> element. A: The margin CSS property doesn't work as expected when the elements are inline. Add display:block, or display:inline-block (in your case) to enable margins on inline elements (such as anchors). The padding property is usually applied without trouble.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Filling multidimensionnal array in JavaScript I've a little problem in JavaScript. I need to get an array width date as keys and events as values. In PHP I would do something like this : $var = new array(); Loop $var[$date][] = $event; End loop Do you know what I mean ? Thanks, Regards A: In javascript, you can create a data structure like that this way: var events = { '2009-09-09': [], '2010-10-10': [], '2011-11-11': [] }; The events = { ... } is an object literal in javascript. Objects in javscript act very much like hashes with properties as keys, so this is essentially going to act as a hash keyed on dates. Each date is initialized with an empty array. And you can fill it up with events like this events[date].push(event); If you don't know the dates ahead of time, you can dynamically fill the hash. So, you'd start with just an empty hash: var events = {}; Then you'd check for the date key every time you go to add an event, like this: if (!(date in events)) events[date] = []; events[date].push(event); The date in events checks to see if the key exists, and the ! negates it. So if the date key does not exist, it initializes the date key with an empty array. Then it pushes the event for that date as normal. A: In Javascript key-value mappings are handled by Objects. An empty object is just {}. You can do this sort of thing like (note that var is a reserved word in Javascript so I can't copy your example exactly): var variable = {}; var date_list = [1,2,3]; var event_list = [4,5,6]; for (i in date_list){ var key = date_list[i]; var value = event_list[i]; variable[key] = value; } // variable now contains: {1:4, 2:5, 3:6} console.log(variable[1]); // prints 4 EDIT: That's the basic syntax. If you want to have an array for each key, just do something like that but with arrays instead of numbers in event_list. For example: my_dates = {'2011': [1,2,3], '2010': [6,7,8]} A: To add an element to a list you can use the push javascript method of array objects... events_by_date = {}; ... for (var i=0; i<events.length; i++) { if (!events_by_date[events[i].date]) { // This is the first event on this date // so create the list events_by_date[events[i].date] = []; } // Add the event to the list of events in that date events_by_date[events[i].date].push(events[i]); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7589920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: coldfusion using cfoutput with a variable in a variable name I've got multiple files that have are using the same template cfm files I have chunks of content of the pages in a template file content.cfm that I can retrieve through various variable names : content_home content_contact title_home title_contact I'd like to have an intermediary template file that can call the content_#id# and title_#id# based on the provided id. the id is defined with the template in home.cfm and contact.cfm The issue I'm having is that I cannot reference a variable using a variable as part of the name such as #content_#id## A: I don't quite understand the question (or indeed, that you're asking a question ;-) However are you just asking whether in parser.cfm you can do this: <cfinclude template="content_#page#.cfm"> ? Well: yes you can. Try it! BTW, I concur with the person who suggested you don't reinvent the wheel. Have a look at FW/1. It'll do all this stuff (and a lot more) for you. A: Abstracting from the purpose (using mature framework helps a lot) you can achieve referencing dynamic variables using structure notation: variables["content_" & id] for your case
{ "language": "en", "url": "https://stackoverflow.com/questions/7589921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error while getting properties types of large class in objective-C In Objective-c, I am trying to get properties of some Object that contains about 14 property using the following code: -(NSDictionary*) getPropertiesOfClass:(Class) clazz { NSMutableDictionary* dict = [NSMutableDictionary dictionary]; unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList(clazz, &outCount); for(i = 0; i < outCount; i++) { objc_property_t _property = properties[i]; const char *propName = property_getName(_property); if(propName) { const char *propType = getPropertyType(_property); NSString *propertyName = [NSString stringWithCString:propName encoding:NSUTF8StringEncoding]; NSString *propertyType = [NSString stringWithCString:propType encoding:NSUTF8StringEncoding]; [dict setValue:propertyType forKey:propertyName]; } } free(properties); return dict; } static const char *getPropertyType(objc_property_t property) { const char *attributes = property_getAttributes(property); char buffer[1 + strlen(attributes)]; strcpy(buffer, attributes); char *state = buffer, *attribute; while ((attribute = strsep(&state, ",")) != NULL) { if (attribute[0] == 'T') { return (const char *)[[NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] bytes]; } } return "@"; } But I got an exception (see below) However, When I try to use the same code to get the properties list of small objects (objects with 3 or 4 properties), the code works without any exceptions and get accurate results. So, How to handle this error!! Thanks. *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSConcreteData initWithBytes:length:copy:freeWhenDone:bytesAreVM:]: absurd length: 4294967294, maximum size: 2147483648 bytes' *** Call stack at first throw: ( 0 CoreFoundation 0x0101e5a9 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x01172313 objc_exception_throw + 44 2 CoreFoundation 0x00fd6ef8 +[NSException raise:format:arguments:] + 136 3 CoreFoundation 0x00fd6e6a +[NSException raise:format:] + 58 4 Foundation 0x00800b6b -[NSConcreteData initWithBytes:length:copy:freeWhenDone:bytesAreVM:] + 135 5 Foundation 0x00811801 -[NSData(NSData) initWithBytes:length:] + 72 6 solit 0x00033449 -[ObjectMapper(private) getPropertiesOfClass:] + 489 7 solit 0x00031fa5 -[ObjectMapper objectFromDictionary:object:] + 197 8 solit 0x000327b3 -[ObjectMapper objectFromDictionary:object:] + 2259 9 solit 0x00033913 -[NSDictionary(ObjectMapper) toObject:withTypes:] + 243 10 solit 0x00031474 -[JsonWSCaller call:types:error:] + 196 11 solit 0x0003f4c2 +[SummaryWSCaller getFastData:] + 354 12 solit 0x00006fd9 -[PartSearchResultView tableView:didSelectRowAtIndexPath:] + 233 13 UIKit 0x00110b68 -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] + 1140 14 UIKit 0x00106b05 -[UITableView _userSelectRowAtPendingSelectionIndexPath:] + 219 15 Foundation 0x0082079e __NSFireDelayedPerform + 441 16 CoreFoundation 0x00fff8c3 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 19 17 CoreFoundation 0x01000e74 __CFRunLoopDoTimer + 1220 18 CoreFoundation 0x00f5d2c9 __CFRunLoopRun + 1817 19 CoreFoundation 0x00f5c840 CFRunLoopRunSpecific + 208 20 CoreFoundation 0x00f5c761 CFRunLoopRunInMode + 97 21 GraphicsServices 0x012561c4 GSEventRunModal + 217 22 GraphicsServices 0x01256289 GSEventRun + 115 23 UIKit 0x000a7c93 UIApplicationMain + 1160 24 solit 0x00002289 main + 121 25 solit 0x00002205 start + 53 ) A: That's not related to the size of the class nor the number of properties. This is probably because you have a problem in your memory mgmt. When there are not too much properties, the memory used to retrieve the property name and types in the const char* variables are still there, but when you start having too much properties to loop thru, these memory zones are erased by new values, hence the crash. This is probably related to the fact that strsep is not reentrant too, so looping and using it multiple times uses the same internal char buffer each time. You should make your getPropertyType method directly return the NSData object instead of the const char* bytes, and use NSString's initWithData:encoding: method to build the string from it (or move this initWithData:encoding: call to getPropertyType directly and make this return an NSString object directly. This way you will avoid managing pointers to memory zones that are to be autoreleased soon. But your problem is probably that you forgot to check the validity of the attribute buffer and especially its length before trying to access the bytes in this buffer ! Especially you are using [NSData dataWithBytes:(attribute + 3) length:strlen(attribute) - 4] without checking that attribute is at least 4 characters long! That's why the call to dataWithBytes:length: (that internally calls initWithBytes:length:copy:freeWhenDone:bytesAreVM:) crash with a NSInvalidArgumentException, telling that you pass it an absurd length of 4294967294 (which is -2 if interpreted as signed integer)
{ "language": "en", "url": "https://stackoverflow.com/questions/7589923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PicklingError caused by p4a.calendar.interfaces.ICalendarSupport when migrating from 3.3.5 to 4.0.7 I am trying to migrate a Plone 3.3.5 installation to 4.0.7. Before migrating, it was decided that Plone4Artists Calendar should be removed. We followed the procedures proposed here http://plone.org/documentation/kb/cleaning-p4a, applying it for the following interfaces: from p4a.calendar.interfaces import ICalendarEnhanced from p4a.calendar.interfaces import IPossibleCalendar from p4a.calendar.interfaces import ICalendarConfig from p4a.calendar.interfaces import IEventProvider from p4a.calendar.interfaces import IEvent from p4a.calendar.interfaces import IBasicCalendarSupport from p4a.calendar.interfaces import ICalendarSupport Apparently, it works (except for the IPossibleCalendar interface, for which I get a "Can only remove directly provided interfaces." message). In order to remove that, we uninstalled the product (following good advice from here) Now, after moving the Data.fs from 3.3.5 to the 4.0.7 install, and trying to activate the migration at /Plone/@@plone-upgrade, I get the following traceback: Traceback (most recent call last): File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\plone-4.0.7-py2.6.egg\Products\CMFPlone\MigrationTool.py", line 175, in upgrade step['step'].doStep(setup) File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\products.genericsetup-1.6.3-py2.6.egg\Products\GenericSetup\upgrade.py", line 142, in doStep self.handler(tool) File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\plone.app.upgrade-1.0.7-py2.6.egg\plone\app\upgrade\v40\alphas.py", line 443, in migrateFolders transaction.savepoint(optimistic=True) File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\transaction-1.0.1-py2.6.egg\transaction\_manager.py", line 99, in savepoint return self.get().savepoint(optimistic) File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\transaction-1.0.1-py2.6.egg\transaction\_transaction.py", line 253, in savepoint self._saveAndRaiseCommitishError() # reraises! File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\transaction-1.0.1-py2.6.egg\transaction\_transaction.py", line 250, in savepoint savepoint = Savepoint(self, optimistic, *self._resources) File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\transaction-1.0.1-py2.6.egg\transaction\_transaction.py", line 647, in __init__ savepoint = savepoint() File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\zodb3-3.9.5-py2.6-win32.egg\ZODB\Connection.py", line 1128, in savepoint self._commit(None) File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\zodb3-3.9.5-py2.6-win32.egg\ZODB\Connection.py", line 606, in _commit self._store_objects(ObjectWriter(obj), transaction) File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\zodb3-3.9.5-py2.6-win32.egg\ZODB\Connection.py", line 640, in _store_objects p = writer.serialize(obj) # This calls __getstate__ of obj File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\zodb3-3.9.5-py2.6-win32.egg\ZODB\serialize.py", line 422, in serialize return self._dump(meta, obj.__getstate__()) File "d:\plone-4.0.7-teste-20110927\buildout-cache\eggs\zodb3-3.9.5-py2.6-win32.egg\ZODB\serialize.py", line 431, in _dump self._p.dump(state) PicklingError: Can't pickle <class 'p4a.calendar.interfaces.ICalendarSupport'>: import of module p4a.calendar.interfaces failed Please note that this is a test run: it is a bogus and clean Data.fs, and the only product involved is P4A.Calendar, which was installed (and uninstalled before moving the Data.fs to the 4.0.7 install) only at the 3.3.5 buildout. I also tried to follow the advice from here, and the SiteManager for the Plone object does not have any adapter or subscriber with the "p4a" string. The dict attribute from the global SiteManager does not report any occurrence of the "p4a" string either. Can anyone give me a light on this? Where should I look for "p4a.calendar.interfaces.ICalendarSupport" in the Data.fs?
{ "language": "en", "url": "https://stackoverflow.com/questions/7589928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How should I share Maven DepdendencyManagement from multiple sources? I have a Maven project multimodule project. Some of the modules create custom packaging for the libraries produced by the other modules. The packaging being used has its own suite of versioned dependencies that I need to play nice with. As an example: my parent POM might have an entry for e.g. commons-codec:commons-codec 1.4, my "core-lib" POM includes it as a dependency (sans explicit version), and I want to make sure my packaging module bundles in the right version. However, the specific type of custom packaging that I'm using also needs e.g. log4j:log4j 1.2.15, and I want to make sure that when my packaging module runs, it also bundles the correct log4j version. Here's the wrinkle: the example POM I'm working from for "project that makes {custom packaging}" uses a parent that's provided by the custom-packaging team. If I use their parent, I lose the version info for commons-codec. If I use my parent, I lose the version info for log4j. Now, ordinarily if I ask "how do I make A and B depend on the same version", you'd answer "make A and B have the same parent, and include a dependencyManagementsection in the parent". My problem is, I need A, B, and C to depend on the same version, but I don't have any control over C. I think this is what Maven "mixins" are meant to address, but of course they don't exist yet. In the meantime, what I've been doing is picking one parent, then copy-and-pasting the dependencyManagement section from the other POM, with a comment saying "make sure you keep this up to date". Obviously this is an ugly, ugly hack, but I haven't found another way to keep current with both sides. A: What about using the assembly plugin to pack up your artifact with all its dependencies and having your packaging module run on that instead? Then you're not trying any pom magic. It's just a matter of one project using the artifact from another project, like usual. A: For now, I'm going to accept the answer of "this is one of the really sucky things about Maven". Maybe this question can get updated when Maven 3.1 finally launches. A: Could you not activate multiple profiles which have their own dependency section pulling in the required libraries when enabled. This allows some nice flexibility due to the ways that profiles can be activated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Common lisp, undefined intersection function behaviour? According to CLHS entry for the INTERSECTION function (http://www.lispworks.com/documentation/HyperSpec/Body/f_isec_.htm): For every pair that satifies the test, exactly one of the two elements of the pair will be put in the result. My problem is that i need to know which one of the two elements of the pair will be put in the result, which matters when, for example :key #'car is used to extract the arguments to test against, since the cdr might be different. I would like to have a guarantee that either always the first or always the second element will be put in the result. Am I missing something or is this just unspecified behaviour, so I shouldnt use it for my case? A: intersection simply doesn't make the guarantee you want; it implements set-theoretic intersection with a lot of extras, but just not that extra. You'll have to roll your own.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Load Multiple Functions from a Single File in Matlab Possible Duplicate: Is it possible to define more than one function per file in MATLAB? Is it possible to load multiple functions from the same .m file in Matlab? I find it cumbersome to create a single file for each function for many small alias utility functions. I have already tried this tip which is allowed Octave, but not in my Matlab. I get the following error: ??? Error: File: /home/per/Documents/MATLAB/aliases.m Line: 6 Column: 1 Function definitions are not permitted in this context. My aliases.m file currently contains % Prevent Octave from thinking that this % is a function file: 1; function y = isvariable(x) %Return non-zero if x is a function. y = exist(x, 'var'); end function y = isfile(x) %Return non-zero if x is a function. y = exist(x, 'file'); end function y = isdir(x) %Return non-zero if x is a function. y = exist(x, 'dir'); end function y = isbuiltin(x) %Return non-zero if x is a function. y = exist(x) == 5; end A: I'm afraid that is not possible, each m-file contains exactly one MATLAB function (you can have nested or sub-functions, but they are not accessible outside of the file). If you are concerned about putting too much stuff on the global scope, think about OOP and namespaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Gson on Appengine I am trying to use Gson to parse a class for storing as a blob on Google Appengine. I have added the file gson-1.7.1.jar to my build path and the web-inf/lib folder. My app compiles fine, but when attempting to run, the program fails with an error on Gson g = new Gson(); The error message is: java.lang.NoClassDefFoundError: Lcom/google/appengine/repackaged/org/joda/time/DateTime; Has anyone found the same issue, or managed to get it to work? Any alternative JSON parsers that are known to work with appengine? A: GSon itself has no dependency on joda. Are you importing from repackaged? That's not supported. I'm using GSon 1.7.1 with SDK 1.5.4, and it works fine, but I don't have DateTimes represented in JSON. A: It seems to be a known issue: http://code.google.com/p/googleappengine/issues/detail?id=2388 Try to include Joda Time library under WEB-INF/lib but I don't think that solves your problem. I found Jackson better than Gson (performance, project activity, better docs, ...). Take a look at this related question that compares Jackson vs Gson.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When to "release" after setting a property/instance variable? We have a property declared: @property (retain) MyClass *myProperty; What is the difference between this one from Apple example Code: MyClass *aux = [[MyClass alloc] init]; myProperty = aux; [aux release]; and this one: myProperty = [[MyClass alloc] init]; Edited: The original code posted should have been this one: MyClass *aux = [[MyClass alloc] init]; self.myProperty = aux; [aux release]; It was an error of mine, but since many answers have covered the topic I have leave the original code. A: This is generally the right way to set a property to a new value you've created. MyClass *aux = [[MyClass alloc] init]; // new value retain count 1 self.myProperty = aux; // new value retain count 2; IMPORTANT: old value retain count decremented [aux release]; // new value retain count 1, correct since it's retained by self This is acceptable in the init method. myProperty = [[MyClass alloc] init]; // new value retain count 1; there was no old value since the object just init'ed The code you posted is wrong. MyClass *aux = [[MyClass alloc] init]; // new value retain count 1 myProperty = aux; // new value retain count 1 [aux release]; // new value retain count 0!! deallocated; myProperty points to invalid memory The following code is subtly wrong. self.myProperty = [[MyClass alloc] init]; // new value retain count 1 for alloc + 1 for assigned to retain property [self.myProperty release]; // normally new value retain count 1, correct However you might get into trouble if the accessors are written in a funny way, and the getter doesn't return the same object you passed into the setter. Perhaps it returns some sort of proxy object, for example. Then you would not be releasing the same object you alloc'ed. A: self.myProperty = [[MyClass alloc] init]; // this will leak myProperty = [[MyClass alloc] init]; // this will NOT leak The first line leaks because it is using the property setter to assign a new object and the property has a memory model of retain. So, in addition to the alloc in the assignment, you get a retain from the property's setter. However, the second line will not leak as it is not using the property's setter but the private variable behind it. Generally speaking, you want to use the setter everywhere except in init. Because property setters increase the retain count (for retain / copy memory models), it's not uncommon to see an autorelease in property assignments like: self.myProperty = [[[MyClass alloc] init] autorelease]; // Yeah, no leak now If you want to really wrap your head around it, an overridden setter might look something like this: - (void) setMyProperty:(MyClass*)newMyProperty { MyClass *oldValue = _myProperty; // replace retain with copy if you want copy to be memory model _myProperty = [newMyProperty retain]; [oldValue release]; // release last in case newMyProperty == oldValue [...] // super cool setter behavior here } A: Firs of all, just to clarify a little bit what declaring a property means I will explain it a little. When you declare a property, you are actually declaring two methods, a getter and a setter for that particular class attribute. When you declare a property as retain you are actually saying that when you set that property through the setter method, it will be retained. That basically means that its retain count will be incremented. In order to set the class attribute using the property declared, you can either use dot syntax, e.g. self.myProperty or the setter method, e.g. -(void)setMyProperty:(MyClass*)newMyClass, So, in your code, even though you are declaring a property, you are not making use of it because you are not using any of the methods stated above. Now, MyClass *aux = [[MyClass alloc] init]; myProperty = aux; [aux release]; * *You alloc a MyClass object, now that object has retain count of 1. *You assign it to your class attribute (w/o using the property) so the retain count is still 1. *You release that object so its retain count is 0 and it gets released. myProperty = [[MyClass alloc] init]; * *You alloc a MyClass object (it has retain count of 1) and assign it your class attribute myProperty. So, to sum up, in the first case you create and object in memory and then you dispose it, whereas in the second one you are creating it but it never gets disposed. A: In first case myProperty have retainCount 0. In second case myProperty have retainCount 1. If you will use self.myProperty = aux in first case then retainCount of aux and myProperty will be 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589948", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to clear specific marker with gmap3 I got a simple code that generate 10 different marker, actually i use : $("#test").gmap3( {action:'addMarker', name:'marker', latLng: (my lat & lng value)}, ... (10 times) }); In order to clear my marker i user {action:'clear', name:'marker'} but it remove my all 10 markers! How can i tell Gmap3 to remove a specific marker? I have see i can add a tag to my marker like : {action:'addMarker', name:'marker', latLng: (my lat & lng value), tag : "mytag"} but then when i put : {action:'clear', name:'marker', tag : "mytag"} it doen't remove my specific tagged marker any idea? thank's a lot A: Finally, i don't know why but Tag works perfectly well like this for exemple : `<script type="text/javascript"> $(function(){ $("#putain").gmap3(); $("#putain").gmap3({action:'addMarker', name:'marker', address: "paris", tag : "mytag-paris"}); $("#putain").gmap3({action:'addMarker', name:'marker', address: "new york", tag : "mytag-newyork"}); $("#putain").gmap3({action:'clear', name:'marker', tag:'mytag-paris'}); }); </script> ` in that case it remove specificaly the tagged "mytag-paris" marker and don't remove the tagged "tag-newyork" marker A: I would expect if you gave each marker a unique name, then when you call the 'clear' action, using that unique name would remove just the one you want to. A: I had a similar problem and utilizing your clue I found out what the issue was for me. In my case the problem was in addMarker logic. In my case query: {action:'addMarker', name:'marker', latLng: (my lat & lng value), tag : "mytag"} worked perfectly. However, when there was a map property in action, the gmap3 would fail to write tag to the marker. e.g: {action:'addMarker', name:'marker',map:{center:true}, latLng: (my lat & lng value), tag : "mytag"} In this case, gmap3 fails to copy the tag. I am not sure whether this is a bug or a feature. This error happens within getObject() function. A: It is an old post but in case someone is looking... I would simply use just the tag and leave out the name reference for removing one marker. Like this. {action:'clear',tag:'my-tag-name'}
{ "language": "en", "url": "https://stackoverflow.com/questions/7589953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to download file from filesystem in rails 3 I have a filesystem in my app where files are been uploaded via paperclip and i dont know how to download the uploaded files that have been saved in the file system. if i do something like this <%= link_to "Download", file.video.url %> it brings out the download dialog in mozilla but plays the video in google crome. When i hosted the app it behaves in another dimention, i checked my log file and i c this Started GET "/system/audios/3/original/03%20Breakdown.mp3?1317217561" for 41.206.12.58 at 2011-09-28 14:18:13 -0700 ActionController::RoutingError (No route matches [GET] "/system/audios/3/original/03%20Breakdown.mp3"): i dont know why this is hapenning.. is they a way i can do this by having a seprate download action.. if so i would like to know how. thank you(pls i am using paperclip for the upload) A: Have you considered using send_file? It allows you to specify that the file is an attachment. The send_file would be in your download action.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When to call YUI destroy? When should destroy be called? Does it ever get called automatically by YUI lifecycle? Does the page unload cause the YUI lifecycle to call destroy on all objects created during the page processing? I have been working under the assumption that I need to make all my own calls to destroy but that gets hairy when ajax calls replace sections of code that I had progressively enhanced. For example: <div id="replaceMe"> <table> <tr> <td>1</td> </tr> <tr> <td>2</td> </tr> </table> <script> YUI().use('my-lib', function(Y) { Y.mypackage.enhanceTable("replaceMe"); }); <script> </div> The my-lib module basically adds a click handler and mouseover for each row: YUI.add('my-lib', function(Y) { function EnhancedTable(config) { EnhancedTable.superclass.constructor.apply(this, arguments); } EnhancedTable.NAME = "enhanced-table"; EnhancedTable.ATTRS = { containerId : {}, onClickHandler : {}, onMouseoverHandler : {}, onMouseoutHandler : {} }; Y.extend(EnhancedTable, Y.Base, { _click : function(e) { //... submit action }, destructor : function() { var onClickHandler = this.get("onClickHandler"), onMouseoverHandler = this.get("onMouseoverHandler"), onMouseoutHandler = this.get("onMouseoutHandler"); onClickHandler && onClickHandler.detach(); onMouseoverHandler && onMouseoverHandler.detach(); onMouseoutHandler && onMouseoutHandler.detach(); }, initializer : function(config) { var container = Y.one("[id=" + this.get("containerId") + "]"); this.set("container", container); this.set("onMouseoverHandler", container.delegate("mouseover", this._mouseover, "tr", this )); this.set("onMouseoutHandler", container.delegate("mouseout", this._mouseout, "tr", this )); this.set("onClickHandler", container.delegate("click", this._click, "tr", this )); }, _mouseout : function(e) { e.currentTarget.removeClass("indicated"); }, _mouseover : function(e) { e.currentTarget.addClass("indicated"); } }); Y.namespace("mypackage"); Y.mypackage.enhanceTable = function(containerId) { var enhancedTable new EnhancedTable({containerId:containerId}); }; }, '0.0.1', { requires : [ 'base', 'node' ] }); The click handler would submit a request back to my application that would change the page. Do I need to remember all the enhancedTable objects and have an onunload handler call the destroy method of each? Or does the YUI framework take care of this? The last part of this quesiton is, I also have code outside of this that replaces the whole table by replacing the content of the <div id="replaceMe">. In doing so, the script would get re-run and augment the new <table> with a new EnhancedTable. Do I need to remember the old table, and destroy it before the new table clobbers it? A: Instead of setting handlers as attributes I'd store them all in an array like this: this._handlers = [ container.delegate("mouseover", this._mouseover, "tr", this ), container.delegate("mouseout", this._mouseout, "tr", this ), container.delegate("click", this._click, "tr", this ) ]; Then add a destructor method that does the following destructor : function() { new Y.EventTarget(this._handlers).detach(); } It accomplishes the same thing but with way less work on your part! Ideally instead of running this against each table you'd attach all your delegates to #replaceMe so that it wouldn't need to be recreated each time you changed the content, no matter where that happened from. YUI won't automatically call .destroy() for you on unload, it will clean up DOM subs though. The above is extra credit that's really only necessary if you are going to be destroying the object yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: iOS App Version Upgrade - Does Bundle content get deleted? Looking for some concrete detail on how version to version upgrade works in iOS, specifically what happens to bundle content that has been removed in the new version? For example, if version 1.0 has a file called "foo.png" in the bundle, but version 2.0 does not, does iOS remove the existing foo.png during upgrade? Or does it leave it there? Thanks, alex A: The way to think about it is this: * *The old bundle (executable, resources, etc) is completely removed. *The new bundle is plunked down in its place. *The app's file system outside the bundle is left untouched. All your app-stored data, documents, and user defaults stay exactly where the are. The new version of your app will wake up to find all that state still there and need to handle it correctly. But none of the old app bundle's resources are there, though-- you don't need to worry about seeing upgrades and versioning of those things. A: Upgrading removes all old files. You will only have the files that belongs to your target in the bundle after updating. This is actually crucial. Say you delete a nib. If it isn't actually deleted, it will still be initialized from simply being in the file system of the bundle. And you will probably not have IBOutlets etc in your view controller for connections in the xib you deleted. This will cause the application to crash when initializing the nib.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Flex 4 States -- "correct" syntax OK, can someone please tell me the REAL syntax for doing states in mxml in Flex 4??? I've seen both of the following (and implemented both) and don't know which way is "right" or preferred. In the <fx:Declarations> <fx:Declarations> ... <s:State name="state1" /> <s:State name="state2" /> <s:State name="state3" /> </fx:Declarations> <s:Button id="button1" ... /> ... <more components> OR "Top-most" level in a component <s:states> <s:State name="state1" /> <s:State name="state2" /> <s:State name="state3" /> </s:states> <s:Button id="button1" ... /> ... <more components> A: Probably the second one; but It depends what you're trying to do. This Syntax: <fx:Declarations> ... <s:State name="state1" /> <s:State name="state2" /> <s:State name="state3" /> </fx:Declarations> Creates three variables inside the component of the class State. It would be the same as doing something like this in ActionScript: var myState1 : State = new State(); var myState1 : State = new State(); var myState1 : State = new State(); When creating states on a component, you probably want to do more than just create a state. You want to assign the state as a state of the current component. That is what your second syntax actually does: <s:states> <s:State name="state1" /> <s:State name="state2" /> <s:State name="state3" /> </s:states> This creates three state variables as an array, and assigns them to the state property of the top level component. Conceptually like this in ActionScript: var myState1 : State = new State(); var myState1 : State = new State(); var myState1 : State = new State(); this.states = new Array(); this.states.push(myState1); this.states.push(myState2); this.states.push(myState3); It is entirely possible that the compiler does some magic on the first syntax to create those state instance and assign them to the states array, but I'm not sure. I've never seen anyone use that syntax before. I would expect both approach to compile. I would only expect the second approach to actually create states on a component that you can switch between.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589973", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL: glGenBuffer vs glGenBuffersARB What is the difference between the functions glGenBuffers()/glBufferData()/etc, and the functions with ARB appended to the function name glGenBuffersARB()/glBufferDataARB()/etc. I tried searching around but no one ever points out the difference, merely they just use one or the other. Also, is it common for either function to be unavailable on some computers? What's the most common way of getting around that kind of situation without falling back to immediate mode? A: glGenBuffers() is a core OpenGL function in OpenGL 1.5 and later; glGenBuffersARB() was an extension implementing the same functionality in earlier versions. Unless you're developing for an ancient system, there's no longer any reason to use the ARB extension.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: beforecopy event If you go to the Google Chrome developer tools then Scripts > Event Listener Breakpoints > Clipboard you will find the event beforecopy. Two questions: 1) What is it? 2) Why is it useful? A: Occurs before the selection is copied to the clipboard and before the oncopy event. * *In Internet Explorer, the onbeforecopy event occurs on the deepest element in the DOM hierarchy that contains the entire selection. *In Google Chrome and Safari, the onbeforecopy event occurs on the deepest element in the DOM hierarchy that contains the start point of the selection. The beforecopy event is supported by Internet Explorer and WebKit browsers (Safari and Chrome). http://help.dottoro.com/ljrlxaae.php and Wikipedia. A: This is occurring before items are sent to the clipboard. This is useful for sites that add their own footer, e.g. CNET adds the article at the end. Or places that want to transform the URL's. It just allows for more granular control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to read an inode table from an ext2 block group? In writing an ext2 driver for my hobby OS, I ran into a problem reading the inode table from a block group descriptor. The third field of the block group descriptor is the block ID of the inode table for that group. In my case for the root directory of my file system this comes back as 64. The superblock is located at block 1, which is 1024 bytes past the beginning of the volume. The block size is 1024 bytes, but my disk sector size is 512. So to access the superblock, I read from lba 2. The problem is when I try to read the inode table. If it's block id is 64, and my block size is 1024 and disk sector size is 512, wouldn't I read the inode table from disk sector 130? I do that, but nothing is there... What is the proper way to read an inode table given a valid block group descriptor? A: The block IDs in the block group descriptor table are all absolute, so block ID 64 is going to be stored at LBA 128 and 129 in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Effecient MySQL SELECT for text in columns in InnoDB I have a large large table (InnoDB) that essentially has a location name with the location's latitude and longitude. my query is something like SELECT columns FROM table WHERE latitude BETWEEN latMin AND latMax AND longitude BETWEEN longMin AND longMax AND location LIKE '%mcdonalds%' the only index is the primary index for the auto incrementing column. I would prefer to use InnoDB so FULLTEXT isn't an option One option I tried was adding indexes to the latitude and longitude, and doing SELECT id FROM table WHERE latitude BETWEEN latMin AND latMax AND longitude BETWEEN longMin AND longMax then i do $stringOfIds = implode(",",$result); SELECT columns FROM table WHERE id IN ($stringOfIds) AND location LIKE '%mcdonalds%' But it's not very scalable because the $result can have thousands of entries and takes too much memory For now, I have resorted to a full table scan (the first query above) but it takes 0.5-1 seconds per query so any help would be appreciated. Thanks A: The standard B-TREE index is not well suited to this sort of query. I'd recommend changing your design to use the geography type and then creating a SPATIAL index. You can then use this index with MBRContains to quickly find all the points that lie within your bounding box. Update: Creating a spatial index requires MyISAM as pointed out in the comments.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589979", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TortoiseGit shows clean directory as conflicted I have a git repository that I'm working on which I am using TortoiseGit to manage in Windows. Show modifications and diff show that there are no differences between working directory and head. However, a little red X shows up over one of my folders. Is there a way to reset the status of TortoiseGit? Are there differences I can't see? A: Assuming it's not a bug in Tortoise Git--I don't use it, so I don't know much about it--it depends what happened most recently. I think the most likely situation is that you ran into a merge conflict during a rebase and forgot to finish the rebase. If that's the case, you need to complete the rebase one way or another: git rebase --abort or git rebase --continue. A git status will give you a clue. If it shows that you're not on a branch, but you expect to be, then you're probably in the middle of a rebase. Edit: This guy claims it's a problem with the TortoiseGit cache in Windows. Try killing the TGitCache.exe process and restarting explorer. I remember a problem like this in TortoiseSVN back in the day... A: Close all Explorer windows (directory windows) Open Process explorer: Sort by name. Find TGitCache.exe. Click on it and press the END PROCESS button. Reopen the explorer and voilla.
{ "language": "en", "url": "https://stackoverflow.com/questions/7589991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Inverse filtering on OpenCV - accessing DFT values and multiplying DFT matrices I am trying to perform an inverse and a pseudo-inverse filtering in the frequency domain. However I am having trouble accessing DFT coefficients and multiplying DFT matrices afterwards, since I got complex numbers and, therefore, actually two matrices... Basically the inverse filtering performs F = G/H, where F is the restored image, G is the blurred image and H is the kernel that blurred the image. The pseudo-inverse needs to access the values in H, since if the value is near 0 it should be replaced in order to avoid problems in the restoration. For this we must change the H so that: H(u,v) = 1/H(u,v) if H(u,v) > threshold and = 0 otherwise I have a kernel1 (h_1), and the images imf (restored) and img (blurred). Here is the code: // compute the DFTs of the kernel (DFT_B) and the blurred image (DBF_A) cvDFT( dft_A, dft_A, CV_DXT_FORWARD, complexInput1->height ); cvDFT( dft_B, dft_B, CV_DXT_FORWARD, complexInput2->height ); // the first type is the inverse fitlering if (type == 1) { printf("...performing inverse filtering\n"); // dividing the transforms cvDiv(dft_A, dft_B, dft_C, 1); } // the second type is the pseudo-inverse filtering else { printf("...prepare kernel for pseudo-inverse filtering\n"); // will try to access the real values in order to see if value is above a threshold cvSplit( dft_B, image_Re1, image_Im1, 0, 0 ); // pointers to access the data into the real and imaginary matrices uchar * dRe1 = (uchar *)image_Re1->imageData; uchar * dIm1 = (uchar *)image_Im1->imageData; int width = image_Re1->width; int height = image_Re1->height; int step = image_Re1->widthStep; image_Re2 = cvCreateImage(cvGetSize(image_Re1), IPL_DEPTH_32F, 1); image_Im2 = cvCreateImage(cvGetSize(image_Im2), IPL_DEPTH_32F, 1); // pointers to access the data into the real and imaginary matrices // it will be the resulting pseudo-inverse filter uchar * dRe2 = (uchar *)image_Re2->imageData; uchar * dIm2 = (uchar *)image_Im2->imageData; printf("...building kernel for pseudo-inverse filtering\n"); for ( i = 0; i < height; i++ ) { for ( j = 0; j < width; j++ ) { // generate the 1/H(i,j) value if (dRe1[i * step + j] > threshold) { float realsq = dRe1[i * step + j]*dRe1[i * step + j]; float imagsq = dIm1[i * step + j]*dIm1[i * step + j]; dRe2[i * step + j] = dRe1[i * step + j] / (realsq + imagsq); dIm2[i * step + j] = -1 * (dIm1[i * step + j] / (realsq + imagsq)); } else { dRe2[i * step + j] = 0; dIm2[i * step + j] = 0; } } } printf("...merging final kernel\n"); cvMerge(image_Re2, image_Im2, 0, 0, dft_B); printf("...performing pseudo-inverse filtering\n"); cvMulSpectrums(dft_A, dft_B, dft_C, 1); } printf("...performing IDFT\n"); cvDFT(dft_C, dft_H, CV_DXT_INV_SCALE, 1); printf("...getting size\n"); cvGetSubRect(dft_H, &tmp3, cvRect(0, 0, img->width, img->height)); printf("......(%d, %d) - (%d, %d)\n", tmp3.cols, tmp3.rows, restored->width, restored->height); cvSplit( &tmp3, image_Re1, image_Im1, 0, 0 ); cvNamedWindow("re", 0); cvShowImage("re", image_Re2); cvWaitKey(0); printf("...copying final image\n"); // error is in the line below cvCopy(image_Re1, imf, NULL); I have an error on the last line: --- OpenCV Error: Assertion failed (src.depth() == dst.depth() && src.size() == dst.size()) in cvCopy, file /build/buildd/opencv-2.1.0/src/cxcore/cxcopy.cpp, line 466 I know it have to do with the size or depth but I don't know how to control. Anyway, I tried to show the image_Re1 and it is empty... Can anyone shed some light on it? A: Seems like you didn't initialize your imf picture! cvCopy needs a initialized matrix do a: IplImage* imf= cvCreateImage(cvGetSize(image_Re1), IPL_DEPTH_32F, 1); first and I think it'll work. Also, you don't free the image space in this code (cvReleaseImage(&image))
{ "language": "en", "url": "https://stackoverflow.com/questions/7589999", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ARM v4 Returning the value stored in r0 from a C function making a SWI call I've got a function as follows: int foo() { asm("swi 1"); } The underlying handler for swi 1, places the return value correctly into r0, I want foo() to correctly return this value. ARM-ELF-GCC warns about control reaching the end of a non-void function for the above. ARM-ELF-GCC still warns with the following: int foo() { asm("swi 1"); return; } I've instead resorted to the following: int foo() { int ret_val; asm("swi 1"); asm("mov %[v], r0" : [v]"=r"(ret_val) :: "r0", "r3" ) return ret_val; } Is there a more elegant way of getting GCC to return the value in r0 without resorting to the above? Thanks. A: Try this (works on gcc): int foo() { register int ret_val __asm__("r0"); __asm__ __volatile__ ("swi 1" : "=r"(ret_val)); return ret_val; } A: if you are going to use assembler...then...use assembler. .globl foo foo: swi i mov pc,lr
{ "language": "en", "url": "https://stackoverflow.com/questions/7590007", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Get .val() on keydown *not* keyup I'm writing a library that amends a widget to a text area, so I need to detect when the user starts typing something: this.$input.bind('keydown keyup', function() { if (this.$input.val() == …) { … } } The .val() only updates when keyup is triggered. That's too much of a delay. I want to know the state of the input box on keydown. Do you know of a library that improves .val()? A: too late? can't imagine a scenario where 10ms would make that much of a difference, but you could always examine the event args and get the char from there. or try keypress. edit: there's also the input event that gets fired as soon as the input changes (before keyup, but after the value changes); A: The only way to determine the character at keydown/keypress is by using the event.keyCode or event.which property (where event is an object, passed as a first argument to the event listener function). Swap your events for the keypress event. This event listener is fired while the key is pressed down. keydown and keyup are only fired once. During the keydown/keyup event, multiple characters could have been added. A: Found a seemingly perfect solution. Uses aforementioned HTML5 oninput with onpropertychange fallbacks for IE. Brilliant. Fantastic. Other happy words. A: For a keypress (ex. the "a" key), the keydown event is triggered before the "a" is appended to the text input. You could detect the event type, and whether the .keyCode (or .which) event property was a key in the printable range, and attempt to predict what .val() might return after the keyup event, but this is a bad idea. this.$input.bind('keydown keyup', function(e) { var val = this.$input.val(); if (e.type == 'keydown') { // Here is where you would check to see if e.keyCode was a printable // character. Note that key codes differ from ASCII codes. For // example, the "a" key will return key code 65, which is actually // the ASCII code for "A", so you would need to check for the presence // of shift keys and such. Again, this is a bad idea :) val += String.fromCharCode(e.keyCode); } if (val == …) { … } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do these Android location options affect the LocationManager isProividerEnabled method? I'm trying to figure out the location services options under Android 2.3.3 on my Verizon Droid X, I have 3 options: * *Google location services *Standalone GPS services *VZW location services Enabling or disabling Google location services causes the following to return true or false respectivly. myLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) Enabling or disabling Standalone GPS services causes the following to return true or false respectivly. myLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) Enabling or disabling VZW location services seems to have no affect on the isProviderEnabled method. If this option is the only one enabled, then the isProviderEnabled method always returns false regardless if using NETWORK_PROVIDER or GPS_PROVIDER. The way I understand this is: * *Google location services = WiFi MACID location *Standalone GPS services = GPS location *VZW location services = nothing except something special to Verizon (like Navigator) Is this assumption correct? If so, where does AGPS and CellID come into play? A: "Each kind of location service is being used not only to help their applications bring you the most relavent information, but to assist the network in improvements based on your individual experience. Google wants to know where you are to answer your questions of 'Coffee shops near my location' and various other things. Verizon uses your path from tower to tower to tower as you travel to make someone else's (or your) trips through the same area more efficient. If while driving up a highway you are on tower A and tower B, C, and D are all coming in to range, but your phone always goes for C...in the future, tower A can just tell your phone to look for tower C rather than have it search blindly. There's a lot more detail behind the scenes, but that's the general idea." see reference link below for more details http://www.droidforums.net/forum/motorola-droid-x2/159360-location-security-settings-questions.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7590014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Avoid multiple columns in printing FlowDocument I am writing code to print from a FlowDocument. PrintDialog printDialog = new PrintDialog(); bool? result = printDialog.ShowDialog(); if (result == true) { FlowDocument fd = new FlowDocument(); fd.Blocks.Add(new Paragraph(new Run(String.Format("Message:\r\n{0}\r\n", txtMessage.Text)))); fd.PageHeight = printDialog.PrintableAreaHeight; fd.PageWidth = printDialog.PrintableAreaWidth; printDialog.PrintDocument((fd as IDocumentPaginatorSource).DocumentPaginator, "print test"); } This code will print multiple columns in one page. How to avoid this? A: I figured out. I need to set the ColumnWidth of FlowDocument. fd.PagePadding = new Thickness(50); fd.ColumnGap = 0; fd.ColumnWidth = printDialog.PrintableAreaWidth; A: In case, there is no printDialog involved (e.g. Writing a XML-File), this solution worked for me: .PagePadding = New Thickness(50) .ColumnGap = 0 .PageWidth = 21 * 96 / 2.54 .PageHeight = 29.7 * 96 / 2.54 .ColumnWidth = .PageWidth - .PagePadding.Left - .PagePadding.Right
{ "language": "en", "url": "https://stackoverflow.com/questions/7590022", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: when to use the various sort methods of NSArray? The doco explains what the NSArray sort methods are, but is anyone able to give a bullet point say on when/why you'd use a particular method? i.e. under what circumstances in you code would you use method XXX over method YYY. For: * *sortedArrayUsingComparator *sortedArrayUsingDescriptors *sortedArrayUsingFunction:context *sortedArrayUsingSelector A: See Collection Programming Topics: Sorting Arrays for more general information. If you're looking at the class reference documentation, be sure to check out the "Companion guides" that are listed for more practical, real-world advice on how the classes work. Basically, sortedArrayUsingSelector: and sortedArrayUsingFunction:context: have been around since 10.0/iOS 2.0. They're not as flexible as the other methods which came later. If you have an array of relatively simple objects, like NSNumbers or NSStrings, you could use [numbers sortedArrayUsingSelector:@selector(compare:)] to easily sort the objects. If, on the other hand, you have a more complex model object that has multiple properties, such as age, name, date, NSSortDescriptors work well. Those were added in OS X 10.3/iOS 2.0. The allow you to do something like first sort by age, then by name, and then by date.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python non-ascii characters I have a python file that creates and populates a table in ms sql. The only sticking point is that the code breaks if there are any non-ascii characters or single apostrophes (and there are quite a few of each). Although I can run the replace function to rid the strings of apostrophes, I would prefer to keep them intact. I have also tried converting the data into utf-8, but no luck there either. Below are th error messages I get: "'ascii' codec can't encode character u'\2013' in position..." (for non-ascii characters) and for the single quotes class 'pyodbc.ProgrammingError'>: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server] Incorrect syntax near 'S, 230 X 90M.; Eligibilty.... When I try to encode string in utf-8, I instead get the following error message: <type 'exceptions.UnicodeDecodeError'>: ascii' codec can't decode byte 0xe2 in position 219: ordinal not in range(128) The python code is included below. I believe the point in the code where this break occurs is after the following line: InsertValue = str(row.GetValue(CurrentField['Name'])). # -*- coding: utf-8 -*- import pyodbc import sys import arcpy import arcgisscripting gp = arcgisscripting.create(9.3) SQL_KEYWORDS = ['PERCENT', 'SELECT', 'INSERT', 'DROP', 'TABLE'] #SourceFGDB = '###' #SourceTable = '###' SourceTable = sys.argv[1] TempInputName = sys.argv[2] SourceTable2 = sys.argv[3] #--------------------------------------------------------------------------------------------------------------------- # Target Database Settings #--------------------------------------------------------------------------------------------------------------------- TargetDatabaseDriver = "{SQL Server}" TargetDatabaseServer = "###" TargetDatabaseName = "###" TargetDatabaseUser = "###" TargetDatabasePassword = "###" # Get schema from FGDB table. # This should be an ordered list of dictionary elements [{'FGDB_Name', 'FGDB_Alias', 'FGDB_Type', FGDB_Width, FGDB_Precision, FGDB_Scale}, {}] if not gp.Exists(SourceTable): print ('- The source does not exist.') sys.exit(102) #### Should see if it is actually a table type. Could be a Feature Data Set or something... print(' - Processing Items From : ' + SourceTable) FieldList = [] Field_List = gp.ListFields(SourceTable) print(' - Getting number of rows.') result = gp.GetCount_management(SourceTable) Number_of_Features = gp.GetCount_management(SourceTable) print(' - Number of Rows: ' + str(Number_of_Features)) print(' - Getting fields.') Field_List1 = gp.ListFields(SourceTable, 'Layer') Field_List2 = gp.ListFields(SourceTable, 'Comments') Field_List3 = gp.ListFields(SourceTable, 'Category') Field_List4 = gp.ListFields(SourceTable, 'State') Field_List5 = gp.ListFields(SourceTable, 'Label') Field_List6 = gp.ListFields(SourceTable, 'DateUpdate') Field_List7 = gp.ListFields(SourceTable, 'OBJECTID') for Current_Field in Field_List1 + Field_List2 + Field_List3 + Field_List4 + Field_List5 + Field_List6 + Field_List7: print(' - Field Found: ' + Current_Field.Name) if Current_Field.AliasName in SQL_KEYWORDS: Target_Name = Current_Field.Name + '_' else: Target_Name = Current_Field.Name print(' - Alias : ' + Current_Field.AliasName) print(' - Type : ' + Current_Field.Type) print(' - Length : ' + str(Current_Field.Length)) print(' - Scale : ' + str(Current_Field.Scale)) print(' - Precision: ' + str(Current_Field.Precision)) FieldList.append({'Name': Current_Field.Name, 'AliasName': Current_Field.AliasName, 'Type': Current_Field.Type, 'Length': Current_Field.Length, 'Scale': Current_Field.Scale, 'Precision': Current_Field.Precision, 'Unique': 'UNIQUE', 'Target_Name': Target_Name}) # Create table in SQL Server based on FGDB table schema. cnxn = pyodbc.connect(r'DRIVER={SQL Server};SERVER=###;DATABASE=###;UID=sql_webenvas;PWD=###') cursor = cnxn .cursor() #### DROP the table first? try: DropTableSQL = 'DROP TABLE dbo.' + TempInputName + '_Test;' print DropTableSQL cursor.execute(DropTableSQL) dbconnection.commit() except: print('WARNING: Can not drop table - may not exist: ' + TempInputName + '_Test') CreateTableSQL = ('CREATE TABLE ' + TempInputName + '_Test ' ' (Layer varchar(500), Comments varchar(5000), State int, Label varchar(500), DateUpdate DATETIME, Category varchar(50), OBJECTID int)') cursor.execute(CreateTableSQL) cnxn.commit() # Cursor through each row in the FGDB table, get values, and insert into the SQL Server Table. # We got Number_of_Features earlier, just use that. Number_Processed = 0 print(' - Processing ' + str(Number_of_Features) + ' features.') rows = gp.SearchCursor(SourceTable) row = rows.Next() while row: if Number_Processed % 10000 == 0: print(' - Processed ' + str(Number_Processed) + ' of ' + str(Number_of_Features)) InsertSQLFields = 'INSERT INTO ' + TempInputName + '_Test (' InsertSQLValues = 'VALUES (' for CurrentField in FieldList: InsertSQLFields = InsertSQLFields + CurrentField['Target_Name'] + ', ' InsertValue = str(row.GetValue(CurrentField['Name'])) if InsertValue in ['None']: InsertValue = 'NULL' # Use an escape quote for the SQL. InsertValue = InsertValue.replace("'","' '") if CurrentField['Type'].upper() in ['STRING', 'CHAR', 'TEXT']: if InsertValue == 'NULL': InsertSQLValues = InsertSQLValues + "NULL, " else: InsertSQLValues = InsertSQLValues + "'" + InsertValue + "', " elif CurrentField['Type'].upper() in ['GEOMETRY']: ## We're not handling geometry transfers at this time. if InsertValue == 'NULL': InsertSQLValues = InsertSQLValues + '0' + ', ' else: InsertSQLValues = InsertSQLValues + '1' + ', ' else: InsertSQLValues = InsertSQLValues + InsertValue + ', ' InsertSQLFields = InsertSQLFields[:-2] + ')' InsertSQLValues = InsertSQLValues[:-2] + ')' InsertSQL = InsertSQLFields + ' ' + InsertSQLValues ## print InsertSQL cursor.execute(InsertSQL) cnxn.commit() Number_Processed = Number_Processed + 1 row = rows.Next() print(' - Processed all ' + str(Number_Processed)) del row del rows A: James, I believe the real issue is that your are not using Unicode accross the board. Try to do the following: * *Make sure that your input file that you are using to populate the DB is in UTF-8 and that you are reading it with the UTF-8 encoder. *Make sure your DB is actually storing the data as Unicode *When you retrieve data from the file or from the DB or want to manipulate strings (with the + operator for instance) you need to make sure that all parts are proper Unicode. You can NOT use the str() method. You need to use unicode() as Dave pointed out. If you define strings in your code use u'my string' instead of 'my string' (otherwise it is not considered unicode). Also, please provide us the full stack trace and the exception name. A: I'm going to use my psychic debugging skills and say you are trying to str()ify something and getting an error with the ascii codec. What you really should do is to use the utf-8 codec instead like this: insert_value_uni = unicode(row.GetValue(CurrentField['Name'])) InsertValue = insert_value_uni.encode('utf-8') A: Or you can take the view that only ASCII is allowed and use the awesomely named Unicode Hammer A: In general you want to convert to unicode on data input, and convert to the desired encoding on output. So it will be easier to find your problem if you do this. This means changing all strings to unicode, 'INSERT INTO ' to u'INSERT INTO '. (Notice the "u" before the string) Then when you send the string to be executed convert to the desired encoding, "utf8". cursor.execute(InsertSQL.encode("utf8")) # Where InsertSQL is unicode Also, you should add the encoding string to the top of your source code. This means adding the encoding cookie to one of the first two lines of the file: #!/usr/bin/python # -*- coding: <encoding name> -*- If your pulling data from a file to build your string you can uses codecs.open to auto convert from a specific encoding to unicode on load. A: When I converted my str() to unicode, that solved the problem. A simple answer, and I appreciate everyone's help on this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7590030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Append a word between empty element How can by jquery know that if between a element is empty append between same element word "there is not"? <div>Ok</div> <div>No</div> <div></div> // i want append between this div "there is not" that is empty. Like: <div>there is not</div> <div>Hello</div> A: Try - $("div:empty").append("there is not"); Demo - http://jsfiddle.net/St8sV/ A: More verbose form: $('div').each(function() { if ($(this).html() == '') { $(this).html('there is not'); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7590032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }