text
stringlengths
8
267k
meta
dict
Q: git branches and running programs I am running a program in a git repository on a linux server. This program periodically calls another program in that repository. If I do a git checkout 'otherbranch' in the middle of execution will it suddenly start calling the version of that program in the other branch? I'm new to git and don't understand the intricacies yet. How does git affect things like program execution? A: When you do git otherbranch, the program in the other branch is checked out. And most of the time, if the call has not happened yet, the calling program will call the new program. It might depend on the nature of the calling program though. And IMO this has nothing to do with Git. Git doesn't affect program execution. The program does. All git controls is what content is there in the filesystem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In PHP, how do I make a mySQL select query that contains both quotation marks and apostrophes? I'm getting data into my database without any problem using mysql_real_escape_string. So an entry in the database might be: 1/4" Steve's lugnuts So that's perfectly in the database. Now I want to search for that exact thing. But, it will mess up at either the " or the ' (I've tried a number of things, and it always messes up somewhere). Here's what I have now: (user_input comes from a form on the previous page) $user_input=mysql_real_escape_string($_REQUEST['user_input']); $search_row=mysql_query("SELECT * FROM some_table WHERE some_column LIKE '%$user_input%' "); while($search = mysql_fetch_array($search_row)) {stuff happens} echo "<form action='search_results.php' method='post'>"; echo "<input name='user_input' type='text' size='50' value='" . $user_input. "'>"; echo "<input type='submit' value='Lookup Parts' />"; echo "</form>"; But the problem is, I can't seem to get anything but errors. The search field (which is supposed to populate with what they already put in) just has: 1/4\" Steve\ What am I doing wrong? A: The search field (which is supposed to populate with what they already put in) just has 1/4\" Steve\ of course it has! You misplaced your escaping. mysql_real_escape_string is for SQL only! but you're using it's result for the html. While for the HTML you have to use completely different way of escaping. So, make it $user_input=mysql_real_escape_string($_REQUEST['user_input']); $search_row=mysql_query("SELECT * FROM some_table WHERE some_column LIKE '%$user_input%' "); while($search = mysql_fetch_array($search_row)) {stuff happens} $user_input =htmlspecialchars($_REQUEST['user_input'],ENT_QUOTES); // here it goes echo "<form action='search_results.php' method='post'>"; echo "<input name='user_input' type='text' size='50' value='$user_input'>"; echo "<input type='submit' value='Lookup Parts' />"; echo "</form>"; also note that there is no use in echoing such large chunks of HTML. Just close PHP tag and then write pure HTML: ?> <form action='search_results.php' method='post'> <input name='user_input' type='text' size='50' value='<?=$user_input?>'> <input type='submit' value='Lookup Parts' /> </form> Looks WAY more clear, readable and convenient A: Well, your problem is proper quoting. Your problem is that you need different quoting for MySQL and for HTML, and you probably could also have magic_quotes_gpc set! When quoting, you always quote text for some particular output, like: * *string value for mysql query *like expression for mysql query *html code *json *mysql regular expression *php regular expression For each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn't be made at the input into PHP, but at the particular output! Which is the reason why features like magic_quotes_gpc are broken (assure it is switched off!!!). So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me) * *mysql_real_escape_string($str) *mysql_real_escape_string(addcslashes($str, "%_")) *htmlspecialchars($str) *json_encode() - only for utf8! I use my function for iso-8859-2 *mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}')) - you cannot use preg_quote in this case because backslash would be escaped two times! *preg_quote() EDIT: Regarding your original question - if you correct your quoting, you can then of course use any characters in the strings, including the single and double quotes. A: Print your sentece "SELECT * FROM some_table WHERE some_column LIKE '%$user_input%' " to see what it is doing (and escaping). Not a solution but take a look to mysqli or pdo (http://stackoverflow.com/questions/548986/mysql-vs-mysqli-in-php), they have utilities for prepared statements. A: don't know if it helps for sure, but shouldn't you escape for the query and another time for the html? $query = sprintf("SELECT * FROM some_table WHERE some_column LIKE '%s' ", mysql_real_escape_string($user_input)); echo "<input name='user_input' type='text' size='50' value='".htmlentities($user_input)."'>"; edit you maybe don't want to change (escape) your input ($user_input) everytime you submit ..although if its only ' and " thats affected it might not matter anyway
{ "language": "en", "url": "https://stackoverflow.com/questions/7518096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Extract MS Word document chapters to SQL database records? I have a 300+ page word document containing hundreds of "chapters" (as defined by heading formats) and currently indexed by word. Each chapter contains a medium amount of text (typically less than a page) and perhaps an associated graphic or two. I would like to split the document up into database records for use in an iPhone program - each chapter would be a record consisting of a title, id #, and content fields. I haven't decided yet if I would want the pictures to be a separate field (probably just containing a file name), or HTML or similar style links in the content text. In any case, the end result would be that I could display a searchable table of titles that the user could click on to pull up any given entry. The difficulty I am having at the moment is getting from the word document to the database. How can I most easily split the document up into records by chapter, while keeping the image associations? I thought of inserting some unique character between each chapter, saving to text format, and then writing a script to parse the document into a database based on that character, but I'm not sure that I can handle the graphics in this scenario. Other options? A: To answer my own question: Given a fairly simply formatted word document * *convert it to an Open Office XML document *write a python script to parse the document into a database using the xml.sax python module. Images are inserted into the record as HTML, to be displayed using a web interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I force a c++ class method to accept only a handful of integer literals? There is a class I'm refactoring which currently has a method: void resize(size_t sz) In the current codebase, sz is always 0,1,2,or 3. The underlying class is changing from dynamic allocation to a preallocated array of maxsize==3. How can I get a build time error if someone tries to resize to sz>3 ? It is easy enough to add a runtime check. But I'd rather get a compile-time check that fails sooner. I don't want to change any existing code that makes calls with an integer literal that is in-bounds ,e.g.: x.resize(2) should still compile as is. But if someone comes along and tries to x.resize(4) or x.resize(n) it should fail to compile or link. I was thinking about a template specialized on int that is undefined for anything other than {0,1,2,3}. But I'm not sure quite how to make it do what I want within the confines of standard c++. edit: I should elaborate on my thoughts of using the template. I am quite willing to change the declaration of the resize function. I am not willing to change the calling code. e.g. I was thinking something like void resize( ConstructedFromLiteral<0,3> sz) or void resize( ConstructedFromLiteral<0> sz) void resize( ConstructedFromLiteral<1> sz) void resize( ConstructedFromLiteral<2> sz) void resize( ConstructedFromLiteral<3> sz) A: There's no way you can get a compile-time check for a run-time value. Imagine if you said, resize(read_some_number_from_disk()); How is the compiler supposed to check that? However, you can make the function a template, since template parameters are known at compile time: class Foo { template <unsigned int N> void resize() { static_assert(N < 4, "Error!"); //... } //... }; If you don't have static asserts, you can rig up your own static-assert class that'll fail to compile: template <bool> struct ecstatic_assert; // no definition! template <> struct ecstatic_assert<true> { } ; Usage: ... resize ... { ecstatic_assert<N < 4> ignore_me; /* ... */ } A: I'd use static_assert to check this at compile time: struct foo { template <int N> void resize() { static_assert(N >= 0 && N < 4); } }; You get static_assert builtin in C++11, but it's easy enough to implement in C++03 too. Compared to specialisations it saves you from some quite tedious code duplication. A: You can't do it. You can't keep function calls to resize as is, and check n at compile time since its a runtime value. You will need to refactor your code in order to get a compile time error (for instance std/boost static_assert). A: You could make four public inlined specialized templates for ints {0, 1, 2, 3}. These would be simple one-line functions that call a private normal, generic function for any int. EDIT: For the naysayers who say it can't be done using specialized templates (why the downvotes?): class Demo { private: template<int MyInt> void PrivateFunction() { cout << MyInt << endl; } public: template<int MyInt> void PublicFunction(); template<> void PublicFunction<0>() { PrivateFunction<0>(); } template<> void PublicFunction<1>() { PrivateFunction<1>(); } template<> void PublicFunction<2>() { PrivateFunction<2>(); } template<> void PublicFunction<3>() { PrivateFunction<3>(); } }; Try calling Demo::PublicFunction<4>() and you'll get a linker error. Accomplishes the same thing and useful if you don't have / don't want to make a static_assert. As others mentioned, not so easy to check the value of a parameter... A: I don't like this answer for hopefully obvious reasons, but it does satisfy your stated requirements: struct x { void true_resize(int n) { } template <int N> void template_resize(); }; template<> void x::template_resize<0>() { true_resize(0); } template<> void x::template_resize<1>() { true_resize(1); } template<> void x::template_resize<2>() { true_resize(2); } template<> void x::template_resize<3>() { true_resize(3); } #define resize(x) template_resize<x>(); int main () { x x; x.resize(2); x.resize(4); } In case it isn't obvious, the #define doesn't obey C++ scope rules, and so ruins the name resize for all other uses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to quit or exit slave JWindow that was created from a master JWindow in Java? How can i exit only they new MainGame that i created from Main? Where Main is having an original layer of game. And the MainGame was a dialog window (such as modal windows). Main.java: (main code) public class Main extends JWindow { private static JWindow j; public static MainGame mp; public static void main(String[] args) { new Thread(new Runnable() { public void run() { mp = new MainGame(); mp.runit(); //mp.stopit(); } }).start(); j = new Main(); j.setVisible(true); } } MainGame.java: (this was extended by Main, and i would like to quite this only). public class MainGame extends JWindow { private static JWindow j; public MainGame() { // some GUI ... } public static void runit() { j = new MainGame(); j.setVisible(); } } A: 1) better would be implements CardLayout, as create Top-Level Container for new Window, then you'll only to switch betweens Cards 2) don't create lots of Top-Level Container on Runtime, because there are still in JVM memory untill current instance exist, * *create required number of and re-use that, to avoiding possible memory lacks *then you have to call setVisible(false) and setVisible(true) *JWindow missed methods for setting setDefaultCloseOperation(Whatever); 3) if you'll create constructor public JWindow(Frame owner), then you'll call directly SwingUtilities.getAccessibleChildrenCount() and SwingUtilities.getWindowAncestor() import javax.swing.*; import java.awt.*; public class Testing { private JFrame f = new JFrame("Main Frame"); private JWindow splashScreen = new JWindow(); public Testing() { splashScreen = new JWindow(f); splashScreen.getContentPane().setLayout(new GridBagLayout()); JLabel label = new JLabel("Splash Screen"); label.setFont(label.getFont().deriveFont(96f)); splashScreen.getContentPane().add(label, new GridBagConstraints()); splashScreen.pack(); splashScreen.setLocationRelativeTo(null); splashScreen.setVisible(true); new Thread(new Runnable() { @Override public void run() { readDatabase(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } }).start(); } public void readDatabase() { //simulate time to read/load data - 10 seconds? try { Thread.sleep(2000); } catch (Exception e) { e.printStackTrace(); } } public void createAndShowGUI() { JLabel label = new JLabel("My Frame"); label.setFont(label.getFont().deriveFont(96f)); f.add(label); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.pack(); f.setVisible(true); System.out.println("JFrame getAccessibleChildrenCount count -> " + SwingUtilities.getAccessibleChildrenCount(f)); System.out.println("JWindow getParent -> " + SwingUtilities.getWindowAncestor(splashScreen)); splashScreen.dispose(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { Testing t = new Testing(); } }); } } A: I did not go really into your design. but there is 'j.dispose();'. this should work. here is the java documentation. notice: * *dispose(); - deletes the window from memory. *setVisibilty(false); - just hides it from the screen. *You can override the 'dispose()' function to do some stuff while the widow is closing (updating scores if its a game) but at the end of the overriden function you have to call 'super.dispose();' so the function of the class Window is called. A: And the MainGame was a dialog window But thats not what your code uses. You use a JWindow. You should be using a JDialog for a modal window. Then you just dispose() the window.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Continous animation after clicking the next button using Easyslider 1.7 Does anybody who has ever used this know how to get the slides to continue scrolling after clicking the next button? Currently if you click on 'next' button, they stay on that slide. My jQuery skills are slightly below average and I can't figure out myself if there is an easy way of doing it. Any help would be grand :) Easyslider is a jQuery plugin, Here is the JS: (function($) { $.fn.easySlider = function(options){ // default configuration properties var defaults = { prevId: 'prevBtn', prevText: 'Previous', nextId: 'nextBtn', nextText: 'Next', controlsShow: true, controlsBefore: '', controlsAfter: '', controlsFade: true, firstId: 'firstBtn', firstText: 'First', firstShow: false, lastId: 'lastBtn', lastText: 'Last', lastShow: false, vertical: false, speed: 800, auto: true, pause: 3000, continuous: true, numeric: false, numericId: 'controls' }; var options = $.extend(defaults, options); this.each(function() { var obj = $(this); var s = $("li", obj).length; var w = $("li", obj).width(); //var h = $("li", obj).height(); var clickable = true; obj.width(w); //obj.height(h); obj.css("overflow","hidden"); var ts = s-1; var t = 0; $("ul", obj).css('width',s*w); if(options.continuous){ $("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px")); $("ul", obj).append($("ul li:nth-child(2)", obj).clone()); $("ul", obj).css('width',(s+1)*w); }; if(!options.vertical) $("li", obj).css('float','left'); if(options.controlsShow){ var html = options.controlsBefore; if(options.numeric){ html += '<ol id="'+ options.numericId +'"></ol>'; } else { if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>'; html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>'; html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>'; if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>'; }; html += options.controlsAfter; $(obj).after(html); }; if(options.numeric){ for(var i=0;i<s;i++){ $(document.createElement("li")) .attr('id',options.numericId + (i+1)) .html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>') .appendTo($("#"+ options.numericId)) .click(function(){ animate($("a",$(this)).attr('rel'),true); }); }; } else { $("a","#"+options.nextId).click(function(){ animate("next",true); }); $("a","#"+options.prevId).click(function(){ animate("prev",true); }); $("a","#"+options.firstId).click(function(){ animate("first",true); }); $("a","#"+options.lastId).click(function(){ animate("last",true); }); }; function setCurrent(i){ i = parseInt(i)+1; $("li", "#" + options.numericId).removeClass("current"); $("li#" + options.numericId + i).addClass("current"); }; function adjust(){ if(t>ts) t=0; if(t<0) t=ts; if(!options.vertical) { $("ul",obj).css("margin-left",(t*w*-1)); } else { $("ul",obj).css("margin-left",(t*h*-1)); } clickable = true; if(options.numeric) setCurrent(t); }; function animate(dir,clicked){ if (clickable){ clickable = false; var ot = t; switch(dir){ case "next": t = (ot>=ts) ? (options.continuous ? t+1 : ts) : t+1; break; case "prev": t = (t<=0) ? (options.continuous ? t-1 : 0) : t-1; break; case "first": t = 0; break; case "last": t = ts; break; default: t = dir; break; }; var diff = Math.abs(ot-t); var speed = diff*options.speed; if(!options.vertical) { p = (t*w*-1); $("ul",obj).animate( { marginLeft: p }, { queue:false, duration:speed, complete:adjust } ); } else { p = (t*h*-1); $("ul",obj).animate( { marginTop: p }, { queue:false, duration:speed, complete:adjust } ); }; if(!options.continuous && options.controlsFade){ if(t==ts){ $("a","#"+options.nextId).hide(); $("a","#"+options.lastId).hide(); } else { $("a","#"+options.nextId).show(); $("a","#"+options.lastId).show(); }; if(t==0){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); } else { $("a","#"+options.prevId).show(); $("a","#"+options.firstId).show(); }; }; if(clicked) clearTimeout(timeout); if(options.auto && dir=="next" && !clicked){; timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); }; }; }; // init var timeout; if(options.auto){; timeout = setTimeout(function(){ animate("next",false); },options.pause); }; if(options.numeric) setCurrent(0); if(!options.continuous && options.controlsFade){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); }; }); }; })(jQuery); Demo of what I'm working with: http://cssglobe.com/lab/easyslider1.7/01.html A: I got it to work by modifying the easyslider1.7.js file. Line 195 you have if(options.auto && dir=="next" && !clicked){ timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); }; I added an else statement as follows if(options.auto && dir=="next" && !clicked){ timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); } else { if(clicked && options.auto && !options.numeric) { timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); }; }; Might not be the most elegant solution (I'm not a javascript or jQuery expert) but it seems to work, although only for the left and right arrows, not the controls. A: I was coming from a contribution from Cameron and just edit the condition (remove !clicked): if(options.auto && dir=="next" || dir=="prev"){ timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); }; A: I have the solution to auto continuous slide with numeric control: Go to line 107 and change: this: animate($("a",$(this)).attr('rel'),true); to this: animate(parseInt($("a",$(this)).attr('rel')),true); Then, add the following in line 202: } else { if(clicked && options.auto && options.numeric) { timeout = setTimeout(function(){ animate("next",true); },diff*options.speed+options.pause); }; }; That fixes the problem! Cheers! A: The entire fixed code: (function($) { $.fn.easySlider = function(options){ // default configuration properties var defaults = { prevId: 'prevBtn', prevText: 'Previous', nextId: 'nextBtn', nextText: 'Next', controlsShow: true, controlsBefore: '', controlsAfter: '', controlsFade: true, firstId: 'firstBtn', firstText: 'First', firstShow: false, lastId: 'lastBtn', lastText: 'Last', lastShow: false, vertical: false, speed: 800, auto: false, pause: 2000, continuous: false, numeric: false, numericId: 'controls' }; var options = $.extend(defaults, options); this.each(function() { var obj = $(this); var s = $("li", obj).length; var w = $("li", obj).width(); var h = $("li", obj).height(); var clickable = true; obj.width(w); obj.height(h); obj.css("overflow","hidden"); var ts = s-1; var t = 0; $("ul", obj).css('width',s*w); if(!options.vertical) $("li", obj).css({'float':'left','width':w}); if(options.continuous){ $("ul", obj).prepend($("ul li:last-child", obj).clone().css("margin-left","-"+ w +"px")); $("ul", obj).append($("ul li:nth-child(2)", obj).clone()); $("ul", obj).css('width',(s+1)*w); }; if(options.controlsShow){ var html = options.controlsBefore; if(options.numeric){ html += '<ol id="'+ options.numericId +'"></ol>'; } else { if(options.firstShow) html += '<span id="'+ options.firstId +'"><a href=\"javascript:void(0);\">'+ options.firstText +'</a></span>'; html += ' <span id="'+ options.prevId +'"><a href=\"javascript:void(0);\">'+ options.prevText +'</a></span>'; html += ' <span id="'+ options.nextId +'"><a href=\"javascript:void(0);\">'+ options.nextText +'</a></span>'; if(options.lastShow) html += ' <span id="'+ options.lastId +'"><a href=\"javascript:void(0);\">'+ options.lastText +'</a></span>'; }; html += options.controlsAfter; $(obj).after(html); }; if(options.numeric){ for(var i=0;i<s;i++){ $(document.createElement("li")) .attr('id',options.numericId + (i+1)) .html('<a rel='+ i +' href=\"javascript:void(0);\">'+ (i+1) +'</a>') .appendTo($("#"+ options.numericId)) .click(function(){ animate(parseInt($("a",$(this)).attr('rel')),true); }); }; } else { $("a","#"+options.nextId).click(function(){ animate("next",true); }); $("a","#"+options.prevId).click(function(){ animate("prev",true); }); $("a","#"+options.firstId).click(function(){ animate("first",true); }); $("a","#"+options.lastId).click(function(){ animate("last",true); }); }; function setCurrent(i){ i = parseInt(i)+1; $("li", "#" + options.numericId).removeClass("current"); $("li#" + options.numericId + i).addClass("current"); }; function adjust(){ if(t>ts) t=0; if(t<0) t=ts; if(!options.vertical) { $("ul",obj).css("margin-left",(t*w*-1)); } else { $("ul",obj).css("margin-left",(t*h*-1)); } clickable = true; if(options.numeric) setCurrent(t); }; function animate(dir,clicked){ if (clickable){ clickable = false; var ot = t; switch(dir){ case "next": t = (ot>=ts) ? (options.continuous ? (t+1) : ts) : (t+1); break; case "prev": t = (t<=0) ? (options.continuous ? (t-1) : 0) : (t-1); break; case "first": t = 0; break; case "last": t = ts; break; default: t = dir; break; }; var diff = Math.abs(ot-t); var speed = diff*options.speed; if(!options.vertical) { p = (t*w*-1); $("ul",obj).animate( { marginLeft: p }, { queue:false, duration:speed, complete:adjust } ); } else { p = (t*h*-1); $("ul",obj).animate( { marginTop: p }, { queue:false, duration:speed, complete:adjust } ); }; if(!options.continuous && options.controlsFade){ if(t==ts){ $("a","#"+options.nextId).hide(); $("a","#"+options.lastId).hide(); } else { $("a","#"+options.nextId).show(); $("a","#"+options.lastId).show(); }; if(t==0){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); } else { $("a","#"+options.prevId).show(); $("a","#"+options.firstId).show(); }; }; if(clicked) clearTimeout(timeout); if(options.auto && dir=="next" && !clicked){; timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); } else { if(clicked && options.auto && !options.numeric) { timeout = setTimeout(function(){ animate("next",false); },diff*options.speed+options.pause); }; if(clicked && options.auto && options.numeric) { timeout = setTimeout(function(){ animate("next",true); },diff*options.speed+options.pause); }; }; }; }; // init var timeout; if(options.auto){; timeout = setTimeout(function(){ animate("next",false); },options.pause); }; if(options.numeric) setCurrent(0); if(!options.continuous && options.controlsFade){ $("a","#"+options.prevId).hide(); $("a","#"+options.firstId).hide(); }; }); }; })(jQuery);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518112", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# Downloading website into string using C# WebClient or HttpWebRequest I am trying to download the contents of a website. However for a certain webpage the string returned contains jumbled data, containing many � characters. Here is the code I was originally using. HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "GET"; req.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US))"; string source; using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream())) { source = reader.ReadToEnd(); } HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(source); I also tried alternate implementations with WebClient, but still the same result: HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); using (WebClient client = new WebClient()) using (var read = client.OpenRead(url)) { doc.Load(read, true); } From searching I guess this might be an issue with Encoding, so I tried both the solutions posted below but still cannot get this to work. * *http://blogs.msdn.com/b/feroze_daud/archive/2004/03/30/104440.aspx *http://bytes.com/topic/c-sharp/answers/653250-webclient-encoding The offending site that I cannot seem to download is the United_States article on the english version of WikiPedia (en . wikipedia . org / wiki / United_States). Although I have tried a number of other wikipedia articles and have not seen this issue. A: Using the built-in loader in HtmlAgilityPack worked for me: HtmlWeb web = new HtmlWeb(); HtmlDocument doc = web.Load("http://en.wikipedia.org/wiki/United_States"); string html = doc.DocumentNode.OuterHtml; // I don't see no jumbled data here Edit: Using a standard WebClient with your user-agent will result in a HTTP 403 - forbidden - using this instead worked for me: using (WebClient wc = new WebClient()) { wc.Headers.Add("user-agent", "Mozilla/5.0 (Windows; Windows NT 5.1; rv:1.9.2.4) Gecko/20100611 Firefox/3.6.4"); string html = wc.DownloadString("http://en.wikipedia.org/wiki/United_States"); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(html); } Also see this SO thread: WebClient forbids opening wikipedia page? A: The response is gzip encoded. Try the following to decode the stream: UPDATE Based on the comment by BrokenGlass setting the following properties should solve your problem (worked for me): req.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate"; req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; Old/Manual solution: string source; var response = req.GetResponse(); var stream = response.GetResponseStream(); try { if (response.Headers.AllKeys.Contains("Content-Encoding") && response.Headers["Content-Encoding"].Contains("gzip")) { stream = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress); } using (StreamReader reader = new StreamReader(stream)) { source = reader.ReadToEnd(); } } finally { if (stream != null) stream.Dispose(); } A: This is how I usually grab a page into a string (its VB, but should translate easily): req = Net.WebRequest.Create("http://www.cnn.com") Dim resp As Net.HttpWebResponse = req.GetResponse() sr = New IO.StreamReader(resp.GetResponseStream()) lcResults = sr.ReadToEnd.ToString and haven't had the problems you are.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Cgi-bin scripts get run without a user? I'm running a binary that requires a license key to reside in the user's home directory. I'm making a cgi script that calls upon this binary and everything is happy when I execute the script from the command line using sudo -u www-data binary. However, when I run the cgi script from the web, the binary can't find the license key. The apache error log states: License key "(null)/.key" not found., referer: Does this mean that cgi scripts are executed without any user attached for security reasons? And how can I make cgi scripts be run as www-data so the binary knows to look in the appropriate home directory? Unfortunately, There is no command line flag to specify the key location. A: Take a look at suexec for apache2, with that, you'll be able to run cgi as a specified user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Calling an AJAX function declared as a VAR, using Applescript I am trying to run a javascript code inside a page using Applescript. The AJAX function was declared in javascript using something like this var myFunction = function () { // bla bla... here goes the code... } I have tried this in Applescript: do JavaScript "document.myFunction()" but the code is not running. any clues? thanks. A: Global variables are created as properties of the global object (window, for web browsers). Thus window.myFunction would be the proper reference. However, you don't need to specify the global object. The key is that you must specify in AppleScript the target tab or document. For example: tell application "Safari" do JavaScript "myFunction()" in current tab of window 1 end tell
{ "language": "en", "url": "https://stackoverflow.com/questions/7518121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with fill() method Here is my JavaScript code: function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill(); context.arc(startX + 50, startY, 3, 0, Math.PI*2, true); context.stroke(); } Show(outputcpu, 50, 50); Show(outputio, 70, 50); I have expect some thing like: o-o o-o. But not sure why I get: o-o-o-o. How to remove the center stroke? (I want to remove the second line o-o*-*o-o) A: beginPath will seperate your calls: http://jsfiddle.net/CmuT7/1 var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); function Show(output, startX, startY) { context.beginPath(); context.arc(startX, startY, 3, 0, Math.PI * 2, true); context.fill(); context.arc(startX + 50, startY, 3, 0, Math.PI * 2, true); context.stroke(); } Show('', 50, 50); Show('', 70, 70); A: You need to use moveTo() or beginPath() function to avoind line between those arcs. function Show(output, startX, startY){ var c = document.getElementById("myCanvas"); var context = c.getContext("2d"); context.arc(startX, startY, 3, 0, Math.PI*2, true); context.fill(); context.moveTo(startX +50, startY); context.arc(startX + 50, startY, 3, 0, Math.PI*2, true); context.stroke(); } Show(outputcpu, 50, 50); Show(outputio, 70, 50);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java generics in inheritance in Android My intention is to set create a class with this type of inheritance: public class BaseActivity<T> extends <T extends Activity> but of course this inheritance syntax doesn't compile. Any alternative suggestion where I can arbitrarily select a Tab or Map Activity to be the base of other Activity classes whose override behavior is necessary? A: You can't do that, but you can do: public class BaseActivity<T extends Activity> extends Activity That's not exactly what I think you mean to express, but perhaps close?
{ "language": "en", "url": "https://stackoverflow.com/questions/7518127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 2.3.8 Redirecting: redirect_to back or default results in infinte log-in loop map.connect "/session", :controller => "sessions", :action => "new" so, I decided to add the above line to my routes, because sometimes, the user may end up on /session somehow... but when I did that, after I try logging in, the redirect_back_or_default('/') bit in sessions/create sends me back to /sessions instead of the previous url I actually tried to go to. le code: def redirect_back_or_default(default) if not session[:return_to] =~ /session/ redirect_to(session[:return_to] || default) else redirect_to(default) end session[:return_to] = nil end
{ "language": "en", "url": "https://stackoverflow.com/questions/7518135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use the AsyncCTP with an TFS APM Method (Query.Begin/EndQuery)? Would like to try using AsyncCTP with TFS. Currently have a long running method that calls RunQuery on a TFS Query instance. Query exposes the APM methods BeginQuery() and EndQuery(). As I understand it, the recommended approach to wrap these using AsyncCTP is something like: (example from docs) Task<int>.Factory.FromAsync(stream.BeginRead, stream.EndRead, buffer, offset, count, null); Further, have wrapped it in an extension method as in the docs so my actual method looks like: public static Task<WorkItemCollection> RunQueryAsync(this Query query) { if (query== null) throw new ArgumentNullException("Query"); return Task<WorkItemCollection>.Factory.FromAsync(query.BeginQuery, query.EndQuery, null); } ...but this fails to compile. Getting an "invalid argument" intellisense error that, frankly, I can't really understand because the types and format look correct. One possible issue might be that the Query APM methods expect an ICanceleableAsyncResult whereas the Task factory is expecting an IAsyncResult -- but looking at the TFS API, ICanceleableAsyncResult is a specialization of IAsyncResult. Not sure whether i'm doing it wrong or its just not possible. Would love to be able to do it the AsyncCTP way but may have to go back to the APM pattern -- ugh! A: Update: My Nito.AsyncEx library now includes a TeamFoundationClientAsyncFactory type, which can be used instead of rolling your own implementation below. The TFS API is not strictly following the APM pattern because it does not take a state parameter, and this is preventing the built-in TaskFactory.FromAsync from working. You'll have to write your own FromAsync equivalent, which can be done using TaskCompletionSource: using System; using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.Client; public static class TfsUtils<TResult> { public static Task<TResult> FromTfsApm(Func<AsyncCallback, ICancelableAsyncResult> beginMethod, Func<ICancelableAsyncResult, TResult> endMethod, CancellationToken token) { // Represent the asynchronous operation by a manually-controlled task. TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>(); try { // Begin the TFS asynchronous operation. var asyncResult = beginMethod(Callback(endMethod, tcs)); // If our CancellationToken is signalled, cancel the TFS operation. token.Register(asyncResult.Cancel, false); } catch (Exception ex) { // If there is any error starting the TFS operation, pass it to the task. tcs.TrySetException(ex); } // Return the manually-controlled task. return tcs.Task; } private static AsyncCallback Callback(Func<ICancelableAsyncResult, TResult> endMethod, TaskCompletionSource<TResult> tcs) { // This delegate will be invoked when the TFS operation completes. return asyncResult => { var cancelableAsyncResult = (ICancelableAsyncResult)asyncResult; // First check if we were canceled, and cancel our task if we were. if (cancelableAsyncResult.IsCanceled) tcs.TrySetCanceled(); else { try { // Call the TFS End* method to get the result, and place it in the task. tcs.TrySetResult(endMethod(cancelableAsyncResult)); } catch (Exception ex) { // Place the TFS operation error in the task. tcs.TrySetException(ex); } } }; } } You can then use it in extension methods as such: using System.Threading; using System.Threading.Tasks; using Microsoft.TeamFoundation.WorkItemTracking.Client; public static class TfsExtensions { public static Task<WorkItemCollection> QueryAsync(this Query query, CancellationToken token = new CancellationToken()) { return TfsUtils<WorkItemCollection>.FromTfsApm(query.BeginQuery, query.EndQuery, token); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to work with GXT Grid? I have a DTO object with fields: public class EmpDTO extends BaseModel implements java.io.Serializable { private short empno; private EmpDTO emp; private DeptDTO dept; private String ename; private String job; I try output this class in the grid: List<ColumnConfig> configs = new ArrayList<ColumnConfig>(); ColumnConfig clmncnfgEname = new ColumnConfig("ename", "ename", 150); configs.add(clmncnfgEname); ListStore<EmpDTO> store = new ListStore<EmpDTO>(); EmpDTO empDTOtmp = new EmpDTO(); empDTOtmp.setEname("Name"); store.add(empDTOtmp); Grid<EmpDTO> grid = new Grid<EmpDTO>(store, new ColumnModel(configs)); mainContentPanel.add(grid); But i see empty grid with out error. How to fix this? A: Do you have to use BaseModel? Rather than extending BaseModel why not implement BeanModelTag? public class EmpDTO implements BeanModelTag { Otherwise make sure setEname looks like this: public void setEname(String ename) { set("ename",ename); } And getEname looks like this: public String getEname() { return (String)get("ename"); } A: Go through this link ... I think you might be missing out on some key steps to setup a grid. http://zawoad.blogspot.com/2009/08/how-to-create-simple-grid-using-gxtext.html It shows through simple steps on how to create a GXT based grid and helped me out a lot. Also personally I have had this issue on some occasions. Make sure your DTO fields have been correctly mapped to the Grid column config. This might be the problem. I would recommend you to go through the above post and cross check your grid implementation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Choose sorting type in flash.net.FileReferenceList browse method It is possible in the open file dialog of flash.net.FileReferenceList to specify the file sorting order, ie the equivalent to make in Windows File Explorer "Arrange icons by"? A: The short answer: No. The FileReference.browse (to select a single file) and the fileReferenceList.browse (to select multiple files). There is no hook to the underlying file system to sort the dialog entries.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SeekBar minHeight and maxHeight by code Does anybody know how to set the minimum and the maximum SeekBar's height by code? I want to reproduce the same behavior as the following XML's excerpt: <SeekBar android:minHeight="6dip" android:maxHeight="6dip" ... /> A: I do not know if there is a code for it. I achieve this creating an xml with the maximum height and other attributes and inflating the seekBar in its definition: In XML: <?xml version="1.0" encoding="utf-8"?> <SeekBar xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:progressDrawable="@drawable/custom_player_seekbar_background" android:paddingTop="10px" android:paddingBottom="10px" android:thumb="@drawable/bt_do_player" android:paddingLeft="30px" android:paddingRight="30px" android:minHeight="6dip" android:maxHeight="6dip" android:layout_height="wrap_content" android:layout_centerVertical="true"/> And in the java code: volumeSeekBarPL = (SeekBar) getLayoutInflater().inflate(R.layout.custom_seek_bar, null);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: iphone:UIWebview gradient background with CSS possible? I want to give gradient to UIwebview's background which I load as: [self.webView loadHTMLString:customHtml baseURL:nil]; but this html line does not give the effect, anyone knows how to do this better or can fix this css? [customHtml appendString:[NSString stringWithFormat:@"%@ ", @" <body style='background-color:#4b95bf; webkit-gradient(linear, left top, left bottom, from(#55aaee), to(#003366));'>"]]; A: The CSS is incorrect webkit-gradient() is not a property, rather it -webkit-gradient() is a value. Rather the HTML should contain: [customHtml appendString:[NSString stringWithFormat:@"%@ ", @" <body style='background-color:#4b95bf; background-image:-webkit-gradient(linear, left top, left bottom, from(#55aaee), to(#003366));'>"]]; Note the - before the webkit-gradient and the background-image:
{ "language": "en", "url": "https://stackoverflow.com/questions/7518159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript Date object always printed in America/New_York timezone? I have a time-stamp in milliseconds (Unix time / time from Epoch) sent from my server, which uses Joda-time and always the constant timezone "America/New_York". On my client, I also want to guarantee time is displayed according to the America/New_York timezone. I've relied on the MDN Date documentation, and have decided it's easiest to instantiate my Date objects using the new Date(milliseconds) constructor. Now the hard part: I want to be able to print the time for clients that are using my site outside the America/New_York timezone. I know I can getTimezoneOffset from a Date object, so now I'm considering performing arithmetic on that object based on the offset and relying on the server to tell me if I'm in DST or not. Using this method from the Joda Time library. I'd like a solution that works in IE8 as well as the modern browsers. Any thoughts? Are there any small utilities that already accomplish this in a standard way? // dateTimeAsString is sent from the server (via JSON) as a String // dateTimeAsString example: "1311387300000" var dateTimeAsInt = parseInt(dateTimeAsString,10); var dateTimeInNY = new Date(dateTimeAsInt); // My current offset is 240 var nyOffset = dateTimeInNY.getTimezoneOffset(); // Somewhere out west var dateTimeInTexas = new Date(dateTimeAsInt); var isDST = false; // sent from server // What I want to do, this is not legal JavaScript dateTimeInTexas.printWithOffset(isDST,nyOffset); A: Browsers don't have timezone information. They able to display only in UTC and in current OS timezone. Even it's not guaranteed that a client has any knowledge about "America/New_York" timezone (e.g. a poor, weak mobile device). If you want display dates in a particular timezone, the easiest way it convert it to a formatted string and transfer it as a string, not milliseconds. If you need to do some calendar calculations on the client side, you are unlucky... You have to do it manually. BTW, you cannot use timezoneOffset as is, because it could be different for particular dates, DST is important too. So, first of all. What do you want to do with dates on the client side?
{ "language": "en", "url": "https://stackoverflow.com/questions/7518165", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there any relation between WCF and HttpWebRequest What is the specialty of WCF? Does WCF have any relation to HttpWebRequest, WebClient, etc? What is the main functionality of WCF? If there is a relationship between WCF and HttpWebRequest, how can I use them together? A: WCF is Windows Communication Foundation. It is a framework for composing data-driven services. These could be web services, but they don't have to be. You're probably best off reading this: * *Windows Communication Foundation is... A: WCF is meant for designing and deploying distributed applications under service-oriented architecture (SOA) implementation. WCF is designed using service oriented architecture principles to support distributed computing where services have remote consumers. Clients can consume multiple services; services can be consumed by multiple clients. Services are loosely coupled to each other. Services typically have a WSDL interface (Web Services Description Language) that any WCF client can use to consume the service, regardless of which platform the service is hosted on. WCF implements many advanced Web services (WS) standards such as WS-Addressing, WS-Reliable Messaging and WS-Security. With the release of .NET Framework 4.0, WCF also provides RSS Syndication Services, WS-Discovery, routing and better support for REST services.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Regular Expression - Python - Remove Leading Whitespace I search a text file for the word Offering with a regular expression. I then use the start and end points from that search to look down the column and pull the integers. Some instances (column A) have leading white-space I do not want. I want to print just the number (as would be found in Column B) into a file, no leading white-space. Regex in a regex? Conditional? price = re.search(r'(^|\s)off(er(ing)?)?', line, re.I) if price: ps = price.start() pe = price.end() A B Offering Offer 56.00 55.00 45.00 45.55 65.222 32.00 A: You could use strip() to remove leading and trailing whitespaces: In [1]: ' 56.00 '.strip() Out[1]: '56.00' A: '^\s+|\s+$' Use this to regular expression access leading and trailing whitespaces. A: If you want to remove only the leading white spaces using regular expressions, you can use re.sub to do that. >>> import re >>>re.sub(r"^\s+" , "" , " 56.45") '56.45'
{ "language": "en", "url": "https://stackoverflow.com/questions/7518172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Change the time interval of a Timer here is my question: Is it possible to increase the scheduledTimerWithTimeInterval:2 for example of "3" after 10 seconds in ViewDidLoad for example. E.g., from this: [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(createNewImage) userInfo:nil repeats:YES]; to this: [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(createNewImage) userInfo:nil repeats:YES]; thank you sorry for my english I french :/ A: Reschedule the timer recursively like this: float gap = 0.50; [NSTimer scheduledTimerWithTimeInterval:gap target:self selector:@selector(onTimer) userInfo:nil repeats:NO]; -(void) onTimer { gap = gap + .05; [NSTimer scheduledTimerWithTimeInterval:gap target:self selector:@selector(onTimer) userInfo:nil repeats:NO]; } ======== Or according to How can I update my NSTimer as I change the value of the time interval Invalidate it with: [myTimer invalidate]; Then create a new one with the new time. You may have to set it to nil first as well. myTimer = nil; myTimer = [NSTimer scheduledTimerWithTimeInterval:mySlider.value target:self selector:@selector(myMethod) userInfo:nil repeats:YES]; A: Use setFireDate: to reschedule the timer. You'll need to keep track of the timer in an ivar. For example: @property (nonatomic, readwrite, retain) NSTimer *timer; @synthesize timer=timer_; - (void)setTimer:(NSTimer *)aTimer { if (timer_ != aTimer) { [aTimer retain]; [timer_ invalidate]; [timer_ release]; timer_ = aTimer; } - (void)dealloc { [timer_ invalidate]; [timer_ release]; } ... self.timer = [NSTimer scheduledTimerWithTimeInterval:...]; ... self.timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:3]; // reschedule for 3 seconds from now
{ "language": "en", "url": "https://stackoverflow.com/questions/7518180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Perl: IPC::Shareable and SWIG'ed C++ object don't agree For a certain Perl project of mine I need several Perl processes to share some resources, located in a C++ library. (Don't ask, it's not the core of this question, just the context.) Thus I am trying to delve my way into two "new" fields in this context: IPC::Shareable, and wrapping C++ using SWIG. It seems I am doing something wrong there, and that is what I would like to ask about. On the C++ side, I wrote a small test class Rectangle with an empty constructor, a set and a size member function. Then I wrapped the class in a SWIG-generated Perl package example. On the Perl side, I tried if the SWIG module works as expected: use example; my $testrec = new example::Rectangle; $testrec->set( 6, 7 ); print $testrec->size() . "\n"; This prints "42", as it should. Then I tried to test my way into using IPC::Shareable. I wrote two Perl scripts, one "server" and one "client", to test the resource sharing. The "server": use IPC::Shareable; use example; # v_ for variable, g_ for (IPC) glue my $v_array; my $v_rect; my %options = ( create => 'yes', exclusive => 0, mode => 0644, destroy => 'yes' ); tie $v_array, 'IPC::Shareable', 'g_array', { %options } or die; tie $v_rect, 'IPC::Shareable', 'g_rect', { %options } or die; $v_array = [ "0" ]; $v_rect = new example::Rectangle; $v_rect->set( 6, 7 ); while ( 1 ) { print "server array: " . join( " - ", @$v_array ) . "\n"; print "server rect: " . $v_rect->size() . "\n"; sleep 3; } The "client": use IPC::Shareable; use example; # v_ for variable, g_ for (IPC) glue my $v_array; my $v_rect; my %options = ( create => 0, exclusive => 0, mode => 0644, destroy => 0 ); tie $v_array, 'IPC::Shareable', 'g_array', { %options } or die; tie $v_rect, 'IPC::Shareable', 'g_rect', { %options } or die; my $count = 0; while ( 1 ) { print "client array: " . join( " - ", @$v_array ) . "\n"; print "client rect: " . $v_rect->size() . "\n"; push( @$v_array, ++$count ); $v_rect->set( 3, $count ); sleep 3; } Starting first the "server", then the "client", I get this output for the "server": server array: 0 server rect: 42 server array: 0 - 1 server rect: 42 server array: 0 - 1 - 2 server rect: 42 And this output for the "client": client array: 0 client rect: 0 client array: 0 - 1 client rect: 3 client array: 0 - 1 - 2 client rect: 6 So apparently, the array reference gets shared allright, but the client doesn't "see" the example::Rectangle of the server, but works on a (zero-initialized) piece of rogue memory, which in turn the server knows nothing about... I have a suspicion that I have to do something to $v_rect to make this work properly, but I am not solid enough in OO Perl to know what. Anyone to the rescue? A: What you are trying to do will not work. You will have to bite the bullet and do some form of message passing instead. I don't quite remember how exactly SWIG wraps the C(++)-level objects for Perl, but it's most likely the usual, admittedly horrible "pointer in integer slot" strategy. In this setup, it will allocate a C(++) object and store a pointer to it in a Perl scalar. The Perl object will be a blessed reference to this scalar. The C(++) object will be freed explicitly by the destructor of the Perl class when all references to the Perl object have gone away. A more modern technique for this would be something like what the XS::Object::Magic module allows you to do. But the details of the wrapper aren't even that important. What matters is that the object is opaque to Perl! With ties, IPC::Shareable uses somewhat out-of-fashion and frankly fragile technology anyway. It may or may not work well for your Perl objects. But when you share the Perl object, the C(++) object will NOT be shared. How could it? Perl knows nothing about it. And it can't possibly. What you should do instead is think about the problem in terms of message passing and serialization. In order to serialize your C(++) objects, you'll want to allow for some cooperation from the C side of things. Have a look at the hooks that the Storable module provides for serializing objects. As far as message passing/queuing goes, I have enjoyed working with ZeroMQ, which gives you a simple socket-like interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: reusing junit tests in Android I have a library whose Junit 3 tests I'd like to reuse on Android. The problem is that these tests depend on files being present (test data). For Android this means that some setup code needs to call getContext().getAssets() and dump the asset files to the sdcard, where they will be picked up by the tests. The problem is: where do I put this setup code? I can't put it in the test's setup, as it inherits from TestCase (and anyway that would mean its no longer portable). I can't put it in the AllTests suite, as that inherits from TestSuite. Since its a Junit project there's no Activity whose onCreate I can hook. A: The solution is to make a custom InstrumentationTestRunner. Override onCreate, where custom setup logic can be stored. For example: public class InstrumentationTestRunner extends android.test.InstrumentationTestRunner { @Override public void onCreate(Bundle arguments) { setUpTests(); super.onCreate(arguments); } protected void setUpTests() { // .... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Loading csv file to MySQL DB with blank "columns" with INSERT I'm trying to write a php script that will load a tab-delimited CSV file into a MySQL database table so that I can set up a cron job to automate the process. PROBLEM: The problem is that the CSV file contains many blank "columns" including blank column titles. GOAL: What I want to do is load all columns into my database table EXCEPT for the columns that contain no column titles even if the data fields are blank. As an added condition, there are certain columns that I simply don't want, even if they contain titles. For instance, for the sake of argument, my csv file contains the following: ID [tab] NAME [tab] [tab] [tab] LOCATION [tab] FAX [tab] PHONE [end] 111 [tab] Billy [tab] [tab] [tab]Seattle [tab] [tab] 111-111-1111 [end] 112 [tab] Bob [tab] [tab] [tab] Atlanta [tab] 111-111-1112 [tab] 111-111-1114 [end] Notice in the sample above that not only are some of the columns missing titles, but some of the data fields are empty for columns that are titled. As an example, in my database table, I have the following column titles: ID | NAME | LOCATION | PHONE < - notice that I don't want the FAX column at all. I can't use LOAD DATA INFILE, so I'm assuming that I need to do everything through an INSERT function through php. I know some php, but can't do what I'm asking above. Please help. A: Use the PHP function fgetcsv(): if (($handle = fopen('filename.csv', 'r')) !== FALSE) { while (($data = fgetcsv($handle, 10000, "\t")) !== FALSE) { print_r($data); // here you get one row -> array with all fields // here you can build a SQL insert query } fclose($handle); } A: Something like the following using file() and str_getcsv() might work: $file = file('csv.csv'); $cols = str_getcsv(array_shift($file), "\t"); foreach ($file as $line) { $cells = str_getcsv($line, "\t"); $set = array(); for ($i = 0; $i < sizeof($cols); $i++) { $set[] = "`{$cols[$i]}` = '{$cells[$i]}'"; } $sql = "INSERT INTO `table` SET " . implode(',', $set); mysql_query($sql); } A: The fgetcsv() function has a bug that omits empty fields. https://bugs.php.net/bug.php?id=46463
{ "language": "en", "url": "https://stackoverflow.com/questions/7518188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MSBUILD - block until a file exists on an ftp server? As part of a build process .. I would like to block the build until a file gets created (exists) remotely at an ftp location, after which I would continue the build. (Preferably with somekind of time out limit). Suggestions? Is this even possible using only the standard msbuild task and/or extensionPack/communitytask? A: Your best bet is to build a small custom exe (you can even compile it as a build step) that polls for the file you are looking for. Then you use the PreBuild target, or a custom target in a pre-build step to verify that the file exists. <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Target Name="WaitOnFTP"> <Exec Command="MyFTPWaiter.exe"/> </Target> </Project> Other more MSBuild oriented suggestions are to remake that exe as a custom task, or even an inline task in MSBuild 4.0. FWIW, I've encountered a similar solution done by a peer who didn't want large binaries used by integration tests in version control and he required the use of a custom downloader in the build to get the files from a SMB share. It worked well enough. Custom Tasks Inline Tasks
{ "language": "en", "url": "https://stackoverflow.com/questions/7518190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CakePHP how to pass error data from the Model back to Controller In some special cases where just logging an error isn't enough I would like to pass an error array or a custom error string from a Model to the calling Controller in order to send that data to me in an email. I thought about just sending an email from the Model itself but I have read somewhere that it angers the MVC best practices gods. I looked around the CakePHP API and didn't find anything that looks like what I need so I'm asking here to see if I missed anything. Edit: I'm doing some special processing in the beforeSave() method. Thanks! Jason A: Haha, going forward - in CakePHP 2.0 - the Email class will be a first-class citizen and not a component. As such, I wouldn't worry about angering the MVC gods by sending email from (god-forbid) models or shells or other useful places. You do have to jump through a few hoops though: // we will need a controller, so lets make one: App::import('Core', 'Controller'); $controller =& new Controller(); // lets grab the email component App::import('Component', 'Email'); $email =& new EmailComponent(); // give it the reference to the controller $email->initialize($controller); // off we go... $email->from = 'Name <noreply@example.com>'; $email->replyTo = 'noreply@example.com'; $email->sendAs = $format; $email->to = $destination; $email->subject = $subject; // oh, this is why we needed the controller $email->template = $template; $controller->set(compact('items', 'subject')); // done. $sent = $email->send();
{ "language": "en", "url": "https://stackoverflow.com/questions/7518193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Assign a different font size to some text in a div + vetical align in table? sorry to combine two questions into one but I'm having trouble finding and answer to two even when I think it should be simple. When I set the font size for a table like this: table.tablesorter { font-family:arial; font-size: 16px; width: 100%; text-align: center; border-spacing: 0px; Then when I create tags that look something like this: h6 { font-size: 0.875em; color: #9a5353; font-weight: 500; } Why doesn't the font size in the table decrease? The reason why I'm asking this is because I want two different fonts in one column, one for the header and one for the text below. Is this possible? Also can I vertically align this text? Thank you :)) Here's what a row looks like :) <tr onclick="alert('Bob Squarepants')"> <td><IMG src="posters/poster1.png"></td> <td><h6>Venue Name</h6><BR>Some event</td> <td>General, Hip Hop</td> <td>$4.00</td> <td>$1.00</td> <td>$1.00</td> <td>$2.00</td> </tr> A: Because the tag H6 is reserved its font size as it is a header tag, you will need to define the font size in the H6 tag as also the table tag for each. To vertical align there are some options you can take, to center the text in the cell you could apply even padding around the cell. There is also some css styles you may use; vertical-align: top/middle/bottom; Where you choose whichever one you want. You could also try this... line-height: **px; Where ** is your desired line height, and lastly if your H6 is wrapped in another fixed sized div you could try... margin: auto 0; text-align: center; This would do the trick just play around with it :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a simple way (in Cocoa/iOS) to queue a method call to run once in the next run loop? UIView has a setNeedsDisplay method that one can call several times within the same event loop, safe in the knowledge that the redrawing work will happen soon, and only the once. Is there a generic mechanism for this sort of behaviour Cocoa? A way of of saying, "Queue a selector as many times as you like, when it's time, the selector will run once & clear the queue." I know I could do this with some kind of state tracking in my target, or with an NSOperationQueue. I'm just wondering if there's a lightweight approach I've missed. (Of course, the answer may be, "No".) A: [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(doTheThing:) object:someObject]; [self performSelector:@selector(doTheThing:) withObject:someObject afterDelay:0]; This is not exactly how UIView is doing it because setNeedsDisplay simply sets a flag and the internal UIView mechanism makes sure to call drawRect: after setting up the drawing environment, but this is a generic way and doesn't require any special state tracking in your class. A: setNeedsDisplay is not a good example of what you're describing, since it actually does run every time you call it. It just sets a flag. But the question is good. One solution is to use NSNotificationQueue with NSNotificationCoalescingOnName. Another solution is to build a trampoline to do the coalescing yourself. I don't have a really good blog reference for trampolines, but here's an example of one (LSTrampoline). It's not that hard to build this if you want to coalesce the messages over a period of time. I once built a trampoline with a forwardInvocation: similar to this: - (void)forwardInvocation:(NSInvocation *)invocation { [invocation setTarget:self.target]; [invocation retainArguments]; [self.timer invalidate]; self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timeout invocation:invocation repeats:NO]; } This actually coalesces all messages to the object over the time period (not just matching messages). That's all I needed for the particular problem. But you could expand on this to keep track of which selectors are being coalesced, and check your invocations to see if they match "sufficiently." To get this to run on the next event loop, just set timeout to 0. I keep meaning to blog about trampolines. Required shilling: My upcoming book covers trampolines in Chapter 4 and Chapter 20.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Making a $_GET search URL (containing a term) SEO safe without affecting search results? I have an existing PHP/MySQL search for my website (which is in production at the moment). Visitors can search the website via a $_GET form (by entering the search term). The $_GET URL looks like -> http://localhost/search/the term (the reason I'm using $_GET is so the search results can be easily directed too. Also because I have pagination on the search php file which is where $_GET['term'] becomes usefull (accross the various pages)). I'm using mod_rewrite for SEO friendly URLs accross the whole site, so I'm worried that having the search URL like this would affect the consistent SEO URL flow of the website...because the visitor could easily enter non alpha-numeric characters.... Appreciate all responses. A: Visitors can search the website via a $_GET form. That's all right. BUT search engines DO NOT use your forms! So, there is nothing to worry about.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Exclude repeated modulus values I have an event firing that shows progress in a video: _currentPosition = 3.86 seconds _currentPosition = 4.02 seconds _currentPosition = 4.16 seconds etc. What I'm trying to do is to send a notification to the server every five seconds, to indicate progress. I can round the seconds down to nearest integer using Math.floor. Then I can use modulus to get every fifth second. What I'm not seeing is how not to send a repeat for (e.g.) 5, since 5.02, 5.15, 5.36 etc. will all qualify. I want something like the following, which is executing in a quickly-firing event, similar to enterframe. But I'm not sure how or where to do the test for _sentNumber, where to declare it, where to reset it... var _sentNumber:int; //_currentPosition is the same as current time, i.e. 5.01, 5.15, etc. var _floorPosition:int = Math.floor(_currentPosition); //returns 5 if(_floorPosition % 5 == 0) //every five seconds, but this should only happen // once for each multiple of 5. { if(_floorPosition != _sentNumber) //something like this? { sendVariablesToServer("video_progress"); } _sentNumber = _floorPosition; Thanks. A: It looks like you're almost there. I'd just put the _sentNumber declaration inside the if statement: var _sentNumber:int = 0; private function onUpdate(...args:Array):void // or whatever your method signature is that handles the update { //_currentPosition is the same as current time, i.e. 5.01, 5.15, etc. var _floorPosition:int = Math.floor(_currentPosition); //returns 5 if(_floorPosition % 5 == 0 && _floorPosition != _sentNumber) //every five seconds, but this should only happen once for each multiple of 5. { sendVariablesToServer("video_progress"); _sentNumber = _floorPosition; } } A: private var storedTime:Number = 0; private function testTime( ):void{ //_currentPosition is the same as current time, i.e. 5.01, 5.15, etc. if( _currentPosition-5 > storedTime ){ storedTime = _currentPosition sendVariablesToServer("video_progress"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XPath dealing with intermixed content How to extract the text of such an element via XPath: <document> some text <subelement>subelement text</subelement> postscript </document> The XPath expression: /document returns document node text and all its subnodes text: some text subelement text postscript While the XPath expression: /document/text() returns just the first text node: some text that is, "postscript" is missing. Question Is there a way to get the text of all text nodes that are immediate sons of <document>? Postscript Very focused Example, in case you want to test yourself, copy into a main method and fix the imports. DocumentBuilder dbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); String xml = "<?xml version='1.0' encoding='UTF-8'?>" + "<document>" + "some text into document" + " <subelement>" + " some text into SUBelement" + " </subelement>" + "POSTSCRIPT" + "</document>"; //i'm forced to use an InputSource because parse doesn't take readers directly :-( Document doc = dbuilder.parse(new InputSource(new StringReader(xml))); //usual way to get an xpath XPath xp = XPathFactory.newInstance().newXPath(); System.out.println(xp.evaluate("/document", doc)); System.out.println(xp.evaluate("/document/text()",doc)); A: Just tested xp.evaluate("/document/text()",doc, XPathConstants.NODESET) indeed returns all text children but you are executing xp.evaluate("/document/text()", doc, XPathConstants.STRING) which seems to only convert the first node in the node set to String. So maybe you need to find another way to convert the NodeSet to String. A: This will get you all of the text children. In general, relying on toString() or the methods that try to return String representations will lead to tears when dealing with DOM. It's always safer to "do it fully/do it right." NodeList list = (NodeList) xp.evaluate("/document/text()", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { System.out.println(list.item(i).getNodeValue()); } A: XPath /document/text() will return all child text nodes of document element. In your example: some text and postscript. I think (I don't know Java classes) System.out.println automatically converts node-set to string representation, in this case it simply returns 1st node. A: While the XPath expression: /document/text() returns just the first text node: some text into document that is, "postscript" is missing. The XPath expression above returns all text node children of /document, but the XPath.evaluate() method, with no 3rd argument converts its result to a string. In the process, it apparently acts like <xsl:value-of> in that it only converts the first node in the result node-set. To print the value of all text node children, supply XPathConstants.NODESET as the 3rd argument to XPath.evaluate(). This will give you the nodeset of text nodes as a NodeList. Then you can loop through them and print each one. Or you could try passing the NodeList directly to println(), and see what it prints. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Twitter Authentications in C# web service? Here is my scenario: I have a mobile application, which will call a method in C# webservice, which will have 2 parameters, TwitterUsername and TwitterPassword. Now in that web service method, I have to authenticate the user with these username and password for twitter and then there a further process to store the data (all four credentials - Consumerkey, ConsumerSecret, AccessToken & AccessTokenSecret) in one of the sql tables and the last identity generated has to be returned. Can anyone please help me regarding twitter in webservice.. it would be a great help for me. Thanks in advance, Shailen Ok, that I got from the your links provided. Now I have username, password, consumerkey and consumersecret in my webservice. So, how can I get remaining two values for AccessToken and AccessTokenSecret without redirecting to any other page from webservice? As, response.Redirect gives error in webservice. thanks. A: I don't think you can authenticate users with a Username and Password anymore: From Twitter: We announced in December of 2009 the deprecation of Basic Auth. Its removal date from the platform is set for June 2010. We announced towards the end of June 2010 that we have postponed this until August 16th 2010. The only way to authenticate now is using oAuth: https://dev.twitter.com/docs/auth/oauth/faq Read this article for more info: https://dev.twitter.com/docs/auth/moving-from-basic-auth-to-oauth Basic Authentication is a liability. By storing logins and passwords, a developer takes on additional responsibilities for the secure storage of those credentials; the potential harm to users if login credentials are leaked or abused is very high. Because many users utilize the same password across many sites, the potential for damage does not necessarily stop with their Twitter account.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Segmentation Fault with Large Input I know segmentation fault means that the process has attempted to access certain memory that it's not allowed to. I'm running some program written by others using C++. And when my input is large (around 1GB), there'll be a segmentation fault even though I requested 30GB memory; while when input size is quite small, it goes well. So what shall I do? Is it because there's not enough memory? I'm really kind of a newbie without much knowledge of C++. I don't even know which part of the code controls memory allocation. Thanks to BLender, line from the debugging is: Program received signal SIGSEGV, Segmentation fault. 0x0000003fbd653174 in _IO_vfscanf_internal () from /share/bin/intel/cc/10.1.015/lib/tls/x86_64/libc.so.6 A: even I request 30GB memory Do you have 30GB of memory? I really doubt it. The answer depends on the function of the program. If the program reads and processes data without memory (i.e., the data that was read before doesn't influence the processing of the data being read), you can load the file in chunks. But without details, I can't say much more. Debug your program. When you compile it, enable debugging: g++ -g -o program -Wall program.cpp And use gdb to debug it: gdb program (gdb) run And the line number and function that caused the segfault should show up. A: Your code calls malloc several times, but never free, so it uses quite a lot of memory. And it never checks for an out-of-memory condition... My suggestion is that you change all the calls to malloc to something like: size_t total_memory = 0; void *my_malloc(size_t sz) { void *res = malloc(sz); total_memory += sz; if (res == NULL) { printf("Too much memory eaten: %zu\n", total_memory); abort(); } return res; } #define malloc(x) my_malloc(x) And see what happens. A: Most likely they have a fixed-sized buffer in there, and your "large input"s are too large to fit inside it. C++ does not check these things by default (if they had used nice checked data structures from the STL perhaps, but clearly they didn't do that). A: Try running the program in a debugger, but first make sure it is compiled with debugging information (-g). Run it with the data it segvaults on. It may be that your program tries to allocate large amount of memory with a call to malloc or new and assign it to a pointer, doesn't check if that was successful and then tries to access the memory (via the pointer) which was supposed to be allocated. You would see where it happens by examining stack trace after the segmentation violation in the debugger. That should give you a clue which part of the program should be modified so e.g. it doesn't read in the whole input file but only a chunk of it, in a loop.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gwt XMLParser Failed to parse error not well formed I am using GWT and want to parse an xml file, but I get this 'Failed to parse error: not well formed'. I am following the exact steps from: http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsXML.html I am using the same xml email message and has been saved to a local directory (c:/email_message.xml), so its well formed, and the message its giving me is incorrect. Here is what I got so far: try { String xmlString = "c://email_message.xml"; Document xmlDoc = XMLParser.parse(xmlString); } catch (DOMException e) { Window.alert(e.getCause()); } Thanks in advance. Help. A: XMLParser.parse expects the xml as a string, not the file path to the xml. Load the file into a string and then pass that into parse and you should be good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MySQL: Selecting unique values from col1 of a table and summing the values in their respective col2s I have a list of multiple clip ids e.g. 1,2,3,3,3,3,4,4,4,5,5,5 and in the second column, i have a duration in frames - each clip only has one duration - what query can i write to add up all the durations for each unique clip? It's been stumping me for a while Currently SELECT SUM(framecount) FROM myTbl returns a really high clip duration (as many clips are being counted twice). e.g. I have 5 clips in my system, with a duration of 10,20,30,40,50 but each clip may appear in the list i'm talking about above 20 times each. Thanks! A: I believe you want to use the GROUP BY function: SELECT clip_id, sum(framecount) FROM myTbl GROUP BY clip_id
{ "language": "en", "url": "https://stackoverflow.com/questions/7518238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why is my data moving around after a F5 refresh in Firefox? I have a webpage with 4 tables. Each row contains two text boxes with numeric values. The textboxes are populated with data from the server. But,something strange happens. If I add data to a row, say row 1. Then Refresh the page...two values are moved down 6 rows. I looked at the data created on the server, it definitly does not come from the server. Also, the HTML doesn't show this data either. For example, <input id="itemTypeRow6" class="ItemType" type="text" data-uniqueid="Some ID" value=""> value="", but looking at the webpage, the text displays 2. (The value I input before I hit refresh). I do have some jQuery running, but as far as I can remember nothing happens on this page on document.ready except various event binding. How can this happen? (Firefox [v4.0.1] only, does not occur in IE7) This only happens when I do an F5 refresh. If I go up to the address bar and hit <Enter> it does not happen. I use <!DOCTYPE html> header A: Firefox tries to preserve form values across regular (not hard) reload. In fact, all browsers do this. The particular algorithm Firefox uses for this doesn't work very well in the face of DOM changes; it uses the positions of nodes in the DOM when the page is unloading to save the state, but the positions when the page is loading to restore it. So to the extent that those do not match up, you'll get weird behavior....
{ "language": "en", "url": "https://stackoverflow.com/questions/7518239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: insert multiple rows same time A PHP script is generating the following table panel based on the data from a mysql DB. Each cell of the table contains a checkbox which sets the access to some 'areas'. The name of my checkboxes are following a certain rule: u[user_id]a[area_name] and I was thinking to get all the $_POST's which are set and to save them in the data base with their values. The number of the areas are fixed, but the number of the users varies by days. The table in which I have to save the status of the table is: user_id, current_date, area1, area2, area3, area4, area5, .. area25. The problem is that I don't know how to save this table into the database. At this moment I do an insert for each user and I think it has to better solution because this takes too much time. <form name="foo" method="post" action="saveme.php" /> <table><tr> <td>name</td><td>area1</td><td>area2</td><td>area3</td><td>area4</td> </tr> <tr> <td>John Smith</td> <td><input type="checkbox" value="12" name="u1a1" checked /></td> <td><input type="checkbox" value="13" name="u1a2" /></td> <td><input type="checkbox" value="16" name="u1a3" /></td> <td><input type="checkbox" value="21" name="u1a4" checked /></td> </tr> </table><input type="submit" value="Save" /> </form> A: I think this should do the trick. However, when I see fields like 'area1, area2, ... area25' - I have a tendency to think there may be a better solution. Perhaps the table should have the fields 'user_id, current_date, area_id, area' instead? $users = array(); foreach ($_POST as $key => $value) { $matches = null; if (preg_match('/^u(\d+)a(\d+)$/', $key, $matches)) { $user_id = $matches[1]; $area_id = $matches[2]; if (!isset($users[$user_id))) { $users[$user_id] = array_fill(1, 25, 0); } $users[$user_id][$area_id] = mysql_real_escape_string($value); } } $values = array(); foreach ($users as $user_id => $areas) { $values[] = '(' . $user_id .', now(), '. implode(', ', $areas) .')'; } if ($values) { $sql = 'INSERT INTO user_areas (user_id, current_date, area1, area2, area3, area4, area5, area6, area7, area8, area9, area10, area11, area12, area13, area14, area15, area16, area17, area18, area19, area20, area21, area22, area23, area24, area25) VALUES ' . implode(', ', $values); // execute $sql query } A: May be you need mysqli multiquery. Build query dynamically. Here an example straight from PHP manual. http://php.net/manual/en/mysqli.multi-query.php <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } $query = "SELECT CURRENT_USER();"; $query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5"; /* execute multi query */ if ($mysqli->multi_query($query)) { do { /* store first result set */ if ($result = $mysqli->store_result()) { while ($row = $result->fetch_row()) { printf("%s\n", $row[0]); } $result->free(); } /* print divider */ if ($mysqli->more_results()) { printf("-----------------\n"); } } while ($mysqli->next_result()); } /* close connection */ $mysqli->close(); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7518240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there an option to turn a jQueryUI button into one that automatically disables itself when clicked? I want to prevent someone from clicking this button twice and triggering two form submissions which could result in duplicate payments on the server: $("#SUBMIT_PAYMENT").button( { label: "SUBMIT PAYMENT", text: true }); Is there an option to make a jQueryUI button automatically disable itself after it is clicked? A: I don't have much experience with UI, but this might work: $("#SUBMIT_PAYMENT").button( { label: "SUBMIT PAYMENT", text: true }).one('click', function() { $(this).button('disable'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7518243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: One function to detect NaN, NA, Inf, -Inf, etc.? Is there a single function in R that determines if a value is NA, NaN, Inf, -Inf, or otherwise not a well-formed number? A: You want is.finite > is.finite(NA) [1] FALSE > is.finite(NaN) [1] FALSE > is.finite(Inf) [1] FALSE > is.finite(1L) [1] TRUE > is.finite(1.0) [1] TRUE > is.finite("A") [1] FALSE > is.finite(pi) [1] TRUE > is.finite(1+0i) [1] TRUE
{ "language": "en", "url": "https://stackoverflow.com/questions/7518245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "49" }
Q: viewing specific people who have shared/liked a page on facebook & retweeted I'm planning to run a promotion on my site that will require me to know EXACTLY who has "shared" specific pages on my site on facebook and retweeted the page on twitter. The most I've been able to find so far is a way to get the count of people as opposed to the actual names of the individuals who's shared the pages. Does anyone know of a way to * *Get a listing of the SPECIFIC people that have shared a page from my site on facebook? *Get a listing of the SPECIFIC people that have retweeted a page from my site on twitter? A: No specific way, but here's a manageable/complex way. As for twitter, you can you can use Yahoo! Pipes. Set up a feed with regex patterns matching some key strings in your tweet and run the pipe. The data returned would be tweets that match, from there you can get the User ID's. I'm blank as regards to Facebook. NOTE :: Search retweets are preceeded by RT Hope you can implement this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Buttons in a listcell XUL Is there a way to get buttons in a listcell to work in XUL? I'm not sure what is stopping it from running. The XUL looks like : <listitem id = "1"> <listcell label = "OK Computer"/> <listcell label = "Radiohead"/> <listcell label = "1997"/> <listcell label = "Platinum"/> <listcell label = "5/5"/> <listcell label = "Alternative Rock"/> <button label = "Edit" oncommand= "alert('Hello World');"/> <button label = "Delete" oncommand = "deleteItem();"/> </listitem> The button works fine outside of the list but my mouse pointer doesn't even recognize it as a button (by changing to a hand pointer) when it's in the list. Any ideas? A: Buttons and other control elements can be used in a standard listitem, it is not required to use richlistbox or tree. The magic trick is the allowevents attribute. You might also want to wrap the buttons in a listcell itself so they get their own column. <listitem id="1" allowevents="true"> <listcell label="OK Computer"/> <listcell label="Radiohead"/> <listcell label="1997"/> <listcell label="Platinum"/> <listcell label="5/5"/> <listcell label="Alternative Rock"/> <listcell> <button label="Edit" oncommand="alert('Hello World');"/> <button label="Delete" oncommand="deleteItem();"/> </listcell> </listitem> A: You need to put the buttons inside the list cell: <listcell> <button label="Edit" oncommand="alert('Hello World');"/> </listcell> A list cell can either have the default contents (which is what you get if you simply add a label attribute and no contents) or anything you want - but for the latter you actually have to put the contents into the <listcell> tag explicitly. Edit: Actually, the more important problem is that <listbox> is rather restricted concerning its contents, it is mostly limited to plain text. Which is why the more generic <richlistbox> widget has been developed. It doesn't support tabular content however.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: to launch a Dialog from a Service, should I use Activity or View? Say I'm running a service and need to pop out a dialog. As we know, it's impossible to launch a dialog directly from a service, therefor we need to launch and activity ( or view ) and then have it launch our dialog. The dialog, as well as the activity launching it, should NOT obstruct whatever is below it, i.e. what's on screen should not turn gray and any buttons, that are outside of the dialog, should still be clickable. Can this be achieved with using an activity or would the activity block the view under it anyway? If so, guess I would have to use a view... since I haven't worked with views before, what would be the right way to initialize it, so that it won't obstruct whatever is under it? Thanks! A: You could have it launch as an activity using the Dialog theme: http://developer.android.com/guide/topics/ui/themes.html (see heading: Apply a theme to an Activity or application) Although, no matter what you will probably obstruct the user in some way ;-). This method should only show a minimal dialog box instead of taking up the whole screen though A: Can this be achieved with using an activity No. would the activity block the view under it anyway? Yes. If so, guess I would have to use a view A view normally is hosted by an activity. A service cannot just create some random view and put it on the screen. You can attempt to use a Toast with a custom View for a modeless "dialog", but I am uncertain if a service-constructed View will work with that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Getting undefined via ajax JSON when I check the log from Console using chrome browser, I keep getting sideType is undefined. It is not returning data to sideType variable. when I put console.log(sideType); in the sideGroupData() function - it work fine without problem. Code: function sideGroupData(GroupID) { $.getJSON("group_data.php",{GroupID:GroupID}, function(j){ return j; }); } function reloadProduct(productID) { $.post("product.php", { productID:productID }, function(data) { var sideType = sideGroupData(123); console.log(sideType); }); } reloadProduct(999); A: the sidegroupdata() function call will return immediately - it'll trigger the ajax request and keep on executing. That means sideType is being assigned a null value, because sideGroupData doesn't actually explicitly return anything after the ajax call section. Is there any reason you're doing an ajax request WITHIN an ajax request? Wouldn't it make more sense to modify the product.php page to return a data structure containing both that product ID AND the 'sidegroupdata' included in a single response? A: It's because you're running your call in a closure. The ajax call is being made asynchronously, which means that your code continues moving even though you're making an ajax call: function setVar () { var retVal = 1; $.ajax(..., function(data){ retVal = data; //retVal does NOT equal data yet, it's still waiting }); return retVal; //will return 1 every time because code doesn't wait for ajax } var someVar = setVar(); // will be 1 If you want to return that value, include a callback function to run when the data is returned, and run it with the data supplied, like so: function sideGroupData(GroupID, callback){ $.getJSON('group_data.php', {GroupID: GroupID}, callback); } function reloadProduct(productID) { $.post("product.php", { productID:productID }, function(data) { sideGroupData(123, function(sideType){ console.log(sideType); }); }); } or, just make the call inside the function itself: function reloadProduct(productID, groupId) { var prod, sideType; $.post("product.php", { productID:productID }, function(data) { prod = data; $.getJSON('group_data.php', {GroupID: groupId}, function(json){ sideType = json; // you now have access to both 'prod' and 'sideType', do work here }); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python text search question I wonder, if you open a text file in Python. And then you'd like to search of words containing a number of letters. Say you type in 6 different letters (a,b,c,d,e,f) you want to search. You'd like to find words matching at least 3 letters. Each letter can only appear once in a word. And the letter 'a' always has to be containing. How should the code look like for this specific kind of search? A: Let's see... return [x for x in document.split() if 'a' in x and sum((1 if y in 'abcdef' else 0 for y in x)) >= 3] split with no parameters acts as a "words" function, splitting on any whitespace and removing words that contain no characters. Then you check if the letter 'a' is in the word. If 'a' is in the word, you use a generator expression that goes over every letter in the word. If the letter is inside of the string of available letters, then it returns a 1 which contributes to the sum. Otherwise, it returns 0. Then if the sum is 3 or greater, it keeps it. A generator is used instead of a list comprehension because sum will accept anything iterable and it stops a temporary list from having to be created (less memory overhead). It doesn't have the best access times because of the use of in (which on a string should have an O(n) time), but that generally isn't a very big problem unless the data sets are huge. You can optimize that a bit to pack the string into a set and the constant 'abcdef' can easily be a set. I just didn't want to ruin the nice one liner. EDIT: Oh, and to improve time on the if portion (which is where the inefficiencies are), you could separate it out into a function that iterates over the string once and returns True if the conditions are met. I would have done this, but it ruined my one liner. EDIT 2: I didn't see the "must have 3 different characters" part. You can't do that in a one liner. You can just take the if portion out into a function. def is_valid(word, chars): count = 0 for x in word: if x in chars: count += 1 chars.remove(x) return count >= 3 and 'a' not in chars def parse_document(document): return [x for x in document.split() if is_valid(x, set('abcdef'))] This one shouldn't have any performance problems on real world data sets. A: Here is what I would do if I had to write this: I'd have a function that, given a word, would check whether it satisfies the criteria and would return a boolean flag. Then I'd have some code that would iterate over all words in the file, present each of them to the function, and print out those for which the function has returned True. A: words = 'fubar cadre obsequious xray' def find_words(src, required=[], letters=[], min_match=3): required = set(required) letters = set(letters) words = ((word, set(word)) for word in src.split()) words = (word for word in words if word[1].issuperset(required)) words = (word for word in words if len(word[1].intersection(letters)) >= min_match) words = (word[0] for word in words) return words w = find_words(words, required=['a'], letters=['a', 'b', 'c', 'd', 'e', 'f']) print list(w) EDIT 1: I too didn't read the requirements closely enough. To ensure a word contains only 1 instance of a valid letter. from collections import Counter def valid(word, letters, min_match): """At least min_match, no more than one of any letter""" c = 0 count = Counter(word) for letter in letters: char_count = count.get(letter, 0) if char_count > 1: return False elif char_count == 1: c += 1 if c == min_match: return True return True def find_words(srcfile, required=[], letters=[], min_match=3): required = set(required) words = (word for word in srcfile.split()) words = (word for word in words if set(word).issuperset(required)) words = (word for word in words if valid(word, letters, min_match)) return words A: I agree with aix's general plan, but it's perhaps even more general than a 'design pattern,' and I'm not sure how far it gets you, since it boils down to, "figure out a way to check for what you want to find and then check everything you need to check." Advice about how to find what you want to find: You've entered into one of the most fundamental areas of algorithm research. Though LCS (longest common substring) is better covered, you'll have no problems finding good examples for containment either. The most rigorous discussion of this topic I've seen is on a Google cs wonk's website: http://neil.fraser.name. He has something called diff-match-patch which is released and optimized in many different languages, including python, which can be downloaded here: http://code.google.com/p/google-diff-match-patch/ If you'd like to understand more about python and algorithms, magnus hetland has written a great book about python algorithms and his website features some examples within string matching and fuzzy string matching and so on, including the levenshtein distance in a very simple to grasp format. (google for magnus hetland, I don't remember address). WIthin the standard library you can look at difflib, which offers many ways to assess similarity of strings. You are looking for containment which is not the same but it is quite related and you could potentially make a set of candidate words that you could compare, depending on your needs. Alternatively you could use the new addition to python, Counter, and reconstruct the words you're testing as lists of strings, then make a function that requires counts of 1 or more for each of your tested letters. Finally, on to the second part of the aix's approach, 'then apply it to everything you want to test,' I'd suggest you look at itertools. If you have any kind of efficiency constraint, you will want to use generators and a test like the one aix proposes can be most efficiently carried out in python with itertools.ifilter. You have your function that returns True for the values you want to keep, and the builtin function bool. So you can just do itertools.ifilter(bool,test_iterable), which will return all the values that succeed. Good luck
{ "language": "en", "url": "https://stackoverflow.com/questions/7518255", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JAX-RS unrmashalling with @XmlIDREF I have been looking into this issue for hours now, probably simple but I don't get it anymore: I have an entity (Param) which is rendered to json via jax-rs. The entity references another entity (Step). When writing / reading json, I dont want to see the whole step-entity but merely its id, so I use this code : @Entity @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Param implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue long id; @Column(name = "KEYNAME") String key; String value; @XmlIDREF Step step; } Works perfectly for marshalling. So any GET-request shows me something the following: {id: 1, key: "a", value: "b", step: 53 } But when I post some param to the server, it cant map back the numeric id to a step-entity. I need to provide the unmarshaller with a custom IDResolver. But how can I configure the unmarshaller???? The Jax-RS servlet is doing the marshalling for me. My code looks like that: @Path("param") public class ParamRepresentation { /** * Retrieves representation of an instance of ParamRepresentation * @return an instance of Param */ @GET @Produces("application/json") @Path("{ID}") public Param getJson(@PathParam("ID") long id) { return (Param) ctr.find(id, Param.class); } @PUT @Path("{ID}") @Consumes("application/json") @Produces("application/json") public SuccessMessage updateStep(@PathParam("ID") long id, Param p) { ctr.update(p); ParamSuccessMessage sm = new ParamSuccessMessage(); sm.setSuccess(true); sm.setParam(p); return sm; } } so how can i configure the unmarshaller ????? A: I think you've misunderstood the purpose of IDREF in XML schemas. It's there to allow you to refer to another element that is marked as an ID (i.e., with an @XmlID annotation in JAXB) in the same document. You can't use it to refer to an ID elsewhere in the world; for that you'd use a URI (possibly with a fragment identifier part). To do those in JAXB, you use: @XmlElement // You might be able to omit this part; it's here for clarity @XmlSchemaType(name = "anyURI") public URI exampleField; You then need to work out whether the URI refers to something you know (i.e., resolve the URI and see if it points into yourself) and deal with the fragment identifier. Or do the more common trick of just using a string and don't worry about trying to magically hook everything up in the binding layer. (That works rather well in practice.) A: I've done a similar thing using Jersey and xml representations. I used an xml adapter to symmetrically map between the complete child element and the partial (just id) element. I would annotate the Step entity in your Param entity as follows: //javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter @XmlJavaTypeAdapter(PartialStepEntityAdapter.class) Step step You would then need to define both the partial Step entity and the Adapter. The PartialStep would be identical to your original step class, but with just the id field. The PartialStepEntityAdapter would map a Step to a PartialStep when marshalling and a PartialStep to a Step when unmarshalling: //javax.xml.bind.annotation.adapters.XmlAdapter public class PartialStepEntityAdapter extends XmlAdapter<PartialStep, Step> { @Override public Step unmarshal(PartialStep partialStep) throws Exception { Step step = new Step(); step.setId(partialStep.getId()); return step; } @Override public PartialStep marshal(Step step) throws Exception { PartialStep partialStep= new PartialStep(); partialStep.setId(step.getId()); return partialStep; } } Hope that's some help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Web application account confirmation security flow I have a question about security flow of confirmation link. I have a website on which you have to fill your email address and password after filing these information my app sends an email with a secure link to user email address. After clicking on confirmation email user automatically gets logged inside the application. Now question : Is there a security risk to auto login user on clicking of confirmation link ? A: Is there and security risk to auto login user on clicking of confirmation link? Yes and no. It depends on what is in the link. What I would do is I would have two field in database activate_code, that is randomly generated and is_activated which is defaulted to 0. Then I will send a link to activation code and another email with activation link. Once at activation link, user will fill code and account will be activated. redirect him to login page. Do not send user emails or any other information. just send random codes or something similar That is my cent! A: Yes there is a security concern, as Gumbo points out. Since the user has provided an email & password, why not require he be logged in to access his confirmation page?
{ "language": "en", "url": "https://stackoverflow.com/questions/7518258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to deploy an app to another ipad without usb connection? Is it possible to deploy an app on a friend's ipad for testing without the app being on the app store yet. My friend is far away so cannot connect to my mac via usb. A: If the UDID of your friends iPad is added to your developer account and you compiled the app with an Ad-Hoc distribution profile, you can just use the Product -> Export Menu Item in Xcode and email him the .ipa File. He can use iTunes to drop the file onto his iPad. Another good solution to distribute beta versions of your software to testers and get feedback is Testflight App A: Here's a link to a similar question: how do you beta test an iPhone app. Their question references iPhone, but the process should be the same for iPad. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to represent a tree, where each child could be under multiple parents I'm looking for a best way to represent a set of structural data. I'm designing a product picker. It will ask user some questions to narrow down to the set of products. i.e. 1st question: "What's the product Group?" Answer: Group1 In Group1, available Product Categories are (pick one): Category1 Category2 Category4 Answer: Category4 In Category4 for Group1, available Types are: Type3 Type5 Answer: Type5 For Type5, in Category4, in Group1 available Product Chacteristics are... etc. So each new question shows list based not only on the previous answer, but on all the answers before. (i.e. some Types available in category4 would be different if that Category4 was in Group2). It's like a tree, where each child could be under multiple parents. There may be up to 10 such levels. What's the most efficient structure to store this hierarchy? A: Without any extra knowledge of the problem and the different distributions, here is what you should do: Each node will have an n-dimensional array of bits stored in it, where n is its level (Groups are level 0). Then, when you reach level i, you will look over all nodes in that level, and for each one see if the bit that fits the current history is on or off. (There are no pointers or such between the nodes, nodes are just a convenient name I'm using). The dimensions of the arrays in each level would be the total size of the previous levels, e.g. in Types level (level 2), you would have 2-dimensional arrays, with the dimensions (# Groups)*(# Categories). Example: To know whether or not Type5 should appear in Category4, Group1, you would go to its array in the cell [1][4], and if it is on (1) then it should appear, otherwise (0) it shouldn't. If you are using a language that allows pointer arithmetics (like c/c++), you can slightly optimize the matrix access by maintaining the offset you need to go to, since it always starts the same: [1], [1][4], [1][4][5], ..., but this should come at a much later time, when everything already works properly. If later on you get to know more details about your problem, such as that most of these connections do or don't exist, then you could think about using sparse matrices, for example, instead of regular ones.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MSI keeps installing older version when called with silent argument I am having a very annoying problem. I have an application with a setup project included in the solution that builds a .msi. I use VS 2008. I have incremented the version of the setup project - selected the project in solution explorer, pressed F4, and incremented version, and modified "Manufacturer" and "Author" fields. I then rebuilt the application and the setup project also afterwards. The most bizarre thing happens then: when I run the resulting .msi file in a non-silent manner, it installs the latest version in the correct C:\Program Files (x86)[Manufacturer]\ path. But when I call the setup file from the application code, with the silent arguments: processStartInfo.Arguments = "/i " + "\"" + file + "\"" + "/qn"; ...then it installs the previous version (the one before incrementing the setup project version) and also it installs it in the old manufacturer path. Is the .msi setup file storing two versions inside it that hold different variables/ setup properties?! I am stumped and very annoyed, I have now lost four hours on this issue. I have deleted temp files. I have verified the correct .msi is in the correct path a dozen times. I need to force the .msi to consider the updated setup properties when installing with silent argument as well. Here is the code from the application that calls the setup: private static void RunSetupFile() { string file = Path.Combine(Utils.GetAppTempPath(), Utils.ApplicationUpdate_SetupFileName); ProcessStartInfo psi = new ProcessStartInfo(Path.Combine(Environment.SystemDirectory, "msiexec.exe")); psi.WindowStyle = ProcessWindowStyle.Hidden; psi.Arguments = "/i " + "\"" + file + "\"" + "/qn"; psi.UseShellExecute = true; psi.Verb = "runas"; try { Process process = Process.Start(psi); } catch (System.ComponentModel.Win32Exception) { } } And below is the code that calls the above method, perhaps here is the culprit: public static void InitializeAppUpdate() { DownloadNewSetupVersionFromServer(); RunSetupFile(); Utils.CloseApplication(); } Thank you for any idea. Let me know if I should provide more details. A: The log seems ok and I'm pretty sure the problem is not caused by the package. The only causes I can think of are an incorrect path or an incorrect MSI file. Based on your code I assume you're trying to handle some sort of update, perhaps with a downloaded MSI file. Try debugging your application to see what path is stored in file variable. Right before executing Process.Start go to that path and check the MSI: * *open it with Orca *select Property table *check the Manufacturer and ProductVersion properties Perhaps it's the old MSI file and not the new one. If it isn't, try running the command line manually with and without /qn right before Process.Start.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Parsing specific elements of a String in Java I want to read Object from string expression. eg: I have following string: (3:2,1) or (3:null,1) now I want to read Object1=3; Object2=2; Object3=1 or Object1=3; Object2=null; Object3=1. How can I read it in Java. A: Perhaps, this is what you want: String s[] = inputString.substring(1, inputString.length() - 2)split(","); // inputString is your string expression Object object3 = s[1]; String s1[] = s[0].split(":"); Object object1 = s1[0]; Object object2 = s1[1]; If you want null instead of the string "null", you could add a check as this : Object object2 = s1[1].equals("null") ? null : s1[1]; and similarly convert (parse) to integer if you want: Object object2 = s1[1].equals("null") ? null : new Integer(s1[1]); A: I am usually not a big fan of regular expressions, but this is a perfect example of where the proper application of a regular expression is simpler and most importantly easier to maintain than other String manipulation based solutions. import java.util.regex.Matcher; import java.util.regex.Pattern; public class Parser { public static void main(final String[] args) { final String s1 = "(3:2,1)"; final String s2 = "(3:null,1)"; final Pattern p = Pattern.compile("\\((\\d+):(\\d+|null),(\\d+)\\)"); final Matcher m1 = p.matcher(s1); m1.matches(); System.out.format("Object1=%s; Object2=%s; Object3=%s", m1.group(1), m1.group(2), m1.group(3)); System.out.println(); final Matcher m2 = p.matcher(s2); m2.matches(); System.out.format("Object1=%s; Object2=%s; Object3=%s", m2.group(1), m2.group(2), m2.group(3)); } } As per your requirements the expected output looks like Object1=3; Object2=2; Object3=1 Object1=3; Object2=null; Object3=1 A: you can parse the string with substring http://www.roseindia.net/help/java/s/java-substring.shtml i would think u could do object1 = string but really you would normally do object1.variable = string otherwise its not an "object" its a "string object" A: String str = "3:2,1"; String str2 = "3:null,1"; // first case Object[] objects = str.split(":|,"); System.out.println(Arrays.asList(objects)); // second case Object[] objects2 = str2.split(":|,"); System.out.println(Arrays.asList(objects2));
{ "language": "en", "url": "https://stackoverflow.com/questions/7518276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problem with redirecting I have a problem with ASP.NET. I have button on ex. index.aspx which redirect us to index2.aspx, but before that, first page - index.aspx - was reloaded. I don't need it because function in "load" is running again. How to solve that problem? A: Use a link instead of a button, if you want that the user goes directly to the new page. A button will always cause a PostBack and fire the Click event of the button, so you can deal with the user input. You can also make sure the code in the Load event of the Page is not executed on PostBacks: protected void Page_Load(object sender, EventArgs e) { if(!IsPostBack) { // your page initialization code } } But as I said, the proper way to go is a Link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: How to Play sound when UIScrollView is scrolling in iphone sdk? I have a scroll view that can be scrolled to the sides (only up and down, not left and right). I want to play a short sound, whenever the scroll view is moved Y pixels to either side. How can this be done? Code samples will be greatly appreciated...and thanks in Advance. Thanks,
{ "language": "en", "url": "https://stackoverflow.com/questions/7518284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Correct storage for large relational data-set I need to store a large set of what is, in my mind (although I'm used to SQL), relational data. Basically consider storing a large subset of ClueWeb (4 TB). There are documents, sentences, and extractions--as well as properties of each. A major use case is running fulltext searches over the extractions. Running fulltext searches over extractions is easily and effectively implemented using Lucene. However, semantically extractions are parts of sentences, which are parts of documents. Sentences and documents also have their own attributes, but when I store my extractions in Lucene, sentences and documents need to be properties of extractions. Is there a good database engine that allows for fulltext search over extractions but also a relational structure so I can easily store properties of sentences and documents? Or is there a way to store this data in Lucene that I don't understand? A: You can index relations easily enough as field values in Lucene. What you can't do is perform queries with joins. But if you just want to drill up/down or get lists of all the extractions in a sentence or document, you can do that easily if you index the right keys. The place where you'll run into trouble is queries like: "all documents with title having the word 'foobar' where one of their sentences has the word 'bletch'. Even that can be overcome if you denormalize - ie copy - data in both places. But for a 4 TB index you might not want to do that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How can I test "Rate my App" functionality? I've got a bit of code in my app, that after X number of days will check if the user has rated the app, and if not, prompt them to do so. How can I feasibly JUnit test this in a painless manner? The emulator doesn't have the market application by default, but there are plenty of tutorials to set that up. Is there a way to stub this out so a unit test can check if the app has been rated, and if not attempt to rate it? I'm a little bit stuck on ideas on how I can actually verify this bit of code works, without running it manually Thanks A: Had a similar issue myself and so I simply wrote a quick app that would handle a market Uri activity. Subsequently however, I came across this: http://www.howtogeek.com/howto/21862/how-to-enable-the-android-market-in-the-google-android-emulator/ I've not tried it yet myself, but if it allows you to set up the market app on your emulator, this would likely be the ideal solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to grab an image tag from html via jquery So I have a data set that is returning something like this in the variable entry.content: <p style="float:right;margin:0 0 10px 15px;width:240px"> <img src="http://citysportsblog.com/wp-content/uploads/2011/09/RagnarNE.jpg" width="240"> </p><p>Have you heard of the epic adventure that is the</p> How would i just grab the img src url from this via jquery? A: assuming you only have one image: var sourceUrl = $('img').attr('src'); var sourceUrl = $(entry.content).find('img').attr('src'); A: You should give your image an Id and use the id selector (that way you know its only that element you're getting). You can run query code on plain text (not added to the DOM) as follows: string plainText = '<p style="float:right;margin:0 0 10px 15px;width:240px"> <img id="theImg" src="http://citysportsblog.com/wp-content/uploads/2011/09/RagnarNE.jpg" width="240"> </p><p>Have you heard of the epic adventure that is the</p>' var url = $(plainText).find('#theImg').attr('src'); Or if you cant modify it and its just that one image thats in the string: var url = $(plainText).find('img').attr('src'); A: If you don't have any other images with the same size: $('img[width="240"]').attr('src'); A: If it were me, I'd just regex replace to get the source from the variable: entry.content = entry.content.replace("/src=\"(.+?)\"/i", "\1"); (although you wouldn't want to use .+; I was just too lazy to find the possible URL characters). If you're not sure if entry.content will be in that form, then I'd add it to the DOM in a hidden div and get the source from there: var hiddenDiv = $(document.body).add("div"); hiddenDiv.css("display", "none"); hiddenDiv.html(entry.content); entry.content = hiddenDiv.find("img")[0].src; Granted, that's a far more dangerous approach, as it leaves you open to XSS, but if you trust the source, you could do it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: framework to performance test javascript I am currently implementing a module observer pattern to a large scale web application that has a large dependency on javascript. I have introduced unit testing of each of the modules which I find very beneficial in capturing any issues with my javascript. I would now also like to look at the possibility of performance testing my javascript. Are there any frameworks available where I can set up performance test for my javascript files? A: I'm familiar with the jsperf service for javascript performance testing. It is based on the benchmark.js benchmarking library. You could use use either depending upon the details of what you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: AWK fast value search I need a fast way to match a value in AWK, I have 250k values to search. I'm doing something like this: #list with 250k numbers instead of four number_list="9998532001 9998536052 9998543213 9998544904" if ( index(number_list,substr($5,9)) ) {printf "Value: %s\n",$5;} Any suggestions for a faster search ? A: If the substring you are searching for is of a consistent length and position in the target string (say the last 6 digits), then you could preprocess the list into an array and you'd be good to go. Preprocessing step (perhaps in the BEGIN target) n=split(numbers_list,a," "); # Rip in input sting into pieces for ( num in a ) { key=substr(a[num],length(a[num])-6,6); # Get the last six digits # Error processing (i.e. collision handling) should go here list[key]=a[num]; } Then when you need to do the lookup i=list[substr($5,9)] # i is now the full number associated with the key This is only a win if you will do many lookups, because you still have to pay the cost of iterating through that whole list (twice, in fact) during the pre-processing. Note that exact matching to the whole number qualifies as a substring of known length and position, just use key=a[num] (which looks funny and leads to several simplifications of the above code, but I'm sure you can figure it out). If you are looking for any occurrence of substring($5,9) in any of the numbers, this won't work, you'll have to iterate through n every time. A: Put all the numbers from number_list into an awk array and you'll have a fast lookup. if (substr($5,9) in numbers)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jquery AJAX and webservices using onchange for dropdownlist I have a dropdownlist that I use jquery ajax to make a call to a webmethod. My intended solution is to update all the data fields on the cuurent page based on the dropdown selected index using ajax. function getDBInfo() { var mySelectedIndex = $("#<%=dblParameter.ClientID%>").val(); //id name for dropdown list $.ajax({ type:"POST", url:"/Manage/Details.aspx?param=", data:{} contentType:application/json; charset=utf-8", dataType:"json" success: function(data) { //this is what I am trying to accomplish but not sure how I should handle the webservice method to do this or if I am even doing it right so far $("#<%=txtParameter.ClientID%>;").text(data.Parameter); $("#<%=txtName.ClientID%>;").text(data.Name); $("#<%=txtSSN.ClientID%>;").text(data.SSN); //etc.... } }); } then in my code behind I have my page method protected void Page_Load(object sender, EventArgs e) { dblParameter.Attributes.Add("onchange","getDBInfo"); } [WebMethod] public static DataRowView getDBInfo(string param) { ConnectionStringSettings conn = ConfiguationManager.ConnectionStrings["MasterDBConnectionString"]; SQLDataSource Details = new SqlDataSource(conn.ConnectionString, "SELECT * FROM [tblInfo] WHERE ([ParamID] = "+param); DataRowView db = (DataRowView)Details.Select(DataSourceSelectArguments.Empty); return db; } What am I doing wrong because in my javascript calling data.Name or data.Parameter won't work. Should it be data["Parameter"] instead? or am I way off base here Edit1: I changed a lot of my code around here is what I have and I am now its working $(document).ready(function(){ $("#<%=dblParameter.ClientID%>").change(function(){ var myparam= $("#<%=dblParameter.ClientID%>").val(); //id name for dropdown list $.ajax({ type:"POST", url:"Details.aspx/getDBInfo", data:'{param:"'+myparam+'"}', contentType:application/json; charset=utf-8", success: function(data) { alert(data.d) } }); }); }); protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string getDBInfo(string param) { MyMainClass myInit = new MyMainClass(); string target= myInit.GetInfo(param); return target; } A: ASP.net will wrap your data in a "d" object. This is the case with all ASMX services serialized through the ASP.NET. Even if you are returning a single string value, it will always be wrapped in a "d" object. You can solve your problem by changing your Success callback to the following: $("#<%=txtParameter.ClientID%>;").text(data.d.Parameter); $("#<%=txtName.ClientID%>;").text(data.d.Name); $("#<%=txtSSN.ClientID%>;").text(data.d.SSN); You can ready more about this here: A breaking change between versions of ASP.NET AJAX A: This is what worked: $(document).ready(function(){ $("#<%=dblParameter.ClientID%>").change(function(){ var myparam= $("#<%=dblParameter.ClientID%>").val(); //id name for dropdown list $.ajax({ type:"POST", url:"Details.aspx/getDBInfo", data:'{param:"'+myparam+'"}', contentType:application/json; charset=utf-8", success: function(data) { alert(data.d) } }); }); }); protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static string getDBInfo(string param) { MyMainClass myInit = new MyMainClass(); string target= myInit.GetInfo(param); return target; } A: I don't know much about json but u can use that way. debug the 'result' to see what is in. function getDBInfo() { // GET UR WEBMETHOD PARAM: SUPPOSE X PageMethods.getDBInfo(X, OnSucceeded, OnFailed); } // Callback function invoked on successful completion of the page method. function OnSucceeded(result, methodName) { if (result != null && result != '') // do whatever else //do whatever } // Callback function invoked on failure of the page method. function OnFailed(error, methodName) { if (error != null) { // do whatever } } A: Here you go: function getDBInfo() { var mySelectedIndex = $('#<%=dblParameter.ClientID%>').val(); $.ajax({ type: 'POST', url: '/Manage/Details.aspx', data: JSON.stringify({ param: mySelectedIndex }), contentType: 'application/json; charset=utf-8', success: function(data) { $('#<%=txtParameter.ClientID%>').text(data.d.Parameter); $('#<%=txtName.ClientID%>').text(data.d.Name); $('#<%=txtSSN.ClientID%>').text(data.d.SSN); } }); } Also make sure that the object that you are returnign from your page method has Parameter, Name and SSN properties which are used in the success callback. You are returning a DataRowView and I doubt it has such properties. Define and use a strongly typed class in this case which will be returned from your page method. Also notice the usage of the JSON.stringify method to send the JSON request. This method is natively built-in modern browsers but if you need to support legacy browsers you will need to include the json2.js script to your page as well. You will also notice other modifications that I did to your code: * *Removed unnecessary ; after your server side expressions inside the jQuery selectors *Removed the dataType: 'json' from the AJAX call => it's unnecessary, jQuery is intelligent enough to deduce it from the server Content-Type response header. *Quoted correctly the contentType parameter in your ajax call. *Added .d to the data parameter passed to the success callback. It's an ASP.NET stuff which wraps the entire JSON response with this d property: { d: ...... } I would also recommend you reading the following article about invoking ASP.NET PageMethods/Script WebMethods with jQuery.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: New error in supervisord on Ubuntu This error seems to have shown up in the latest set of upgrades on ubuntu Traceback (most recent call last): File "/usr/local/bin/supervisord", line 9, in <module> load_entry_point('supervisor==3.0a10', 'console_scripts', 'supervisord')() File "/usr/local/lib/python2.6/dist-packages/supervisor-3.0a10-py2.6.egg/supervisor/supervisord.py", line 364, in main options = ServerOptions() File "/usr/local/lib/python2.6/dist-packages/supervisor-3.0a10-py2.6.egg/supervisor/options.py", line 406, in __init__ existing_directory, default=tempfile.gettempdir()) File "/usr/lib/python2.6/tempfile.py", line 254, in gettempdir tempdir = _get_default_tempdir() File "/usr/lib/python2.6/tempfile.py", line 201, in _get_default_tempdir ("No usable temporary directory found in %s" % dirlist)) IOError: [Errno 2] No usable temporary directory found in ['/tmp', '/var/tmp', '/usr/tmp', '/usr/lib/python2.6'] I think it's a python thing. I'm running a supervisord process to keep a node.js webserver running, but am no longer able to run supervisord. Does anyone know how to fix this or know of a very reliable alternative to keeping my node.js webserver running (apart from the seemingly obvious "don't write stuff that crashes")? A: _get_default_tempdir just checks access to the temp dirs by writing and deleting a random file into temp dir. So you might want to check permissions on your temp dirs: '/tmp', '/var/tmp', '/usr/tmp', '/usr/lib/python2.6' A: As it turns out, the disk was full.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518297", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to redirect to a specific part of a page? I have this problem: my website have a big logo which full all the screen for common resolutions, which is hard to understand that the content is actually changing when the user clicks in a menu (because the content is to low on the page). My question is, is it possible to, instead of common redirects, do a redirect which include a specific sector in a page? A: In theory you can use anchors () in your URL (like http://www.domain.tld/page1#something) to jump to a specific part of your website, but I would give you the advice to change the layout and design of your website to show your visitors the content directly. You loose enourmous amounts of visitors when your content is "below the fold". When using anchors or Javascript to jump to the "right" position, you will still loose people, since they get confused because of the browser jumping around. Maybe use one template for your frontpage and another for all other pages to achieve the different designs. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WPF Reuse DataGrid TemplateColumn DataTemplates I've build a datagrid which has a custom column: <DataGridTemplateColumn Header="{x:Static local:MainWindowResources.gasNameLabel}" Width="*" MinWidth="150"> <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <TextBox Name="GasNameTextBox" Text="{Binding Path=Name, UpdateSourceTrigger=PropertyChanged}" Padding="2,0,0,0" /> <DataTemplate.Triggers> <Trigger SourceName="GasNameTextBox" Property="IsVisible" Value="True"> <Setter TargetName="GasNameTextBox" Property="FocusManager.FocusedElement" Value="{Binding ElementName=GasNameTextBox}"/> </Trigger> </DataTemplate.Triggers> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Label Name="GasNameLabel" Content="{Binding Path=Name}" Padding="0,0,0,0" Margin="6,2,2,2" /> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> As I am going to be reusing such column definition A LOT, I would really like to define it as an external DataTemplate to which I only provide the property to bind on (Binding Path= ...) and that the rest is reused...that way I would define Text template, Checkbox template and such and reuse them in various grids and only change bindings to different properties. Is that possible? Vladan A: Use a UserControl instead, put that in your application resources, and reuse the usercontrol.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518303", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ListActivity as StartActivity Hy. My startactivity should be a ListActivity. public class Main extends ListActivity Layout: <?xml version="1.0" encoding="utf-8"?> <ListView android:id="@+id/listView1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"></ListView> Everytime i start the app it crashs. Please help Logs: 09-22 16:37:35.115: ERROR/AndroidRuntime(349): Uncaught handler: thread main exiting due to uncaught exception 09-22 16:37:35.129: ERROR/AndroidRuntime(349): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.korn.pizzacounter/com.korn.pizzacounter.Main}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list' 09-22 16:37:35.129: ERROR/AndroidRuntime(349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 09-22 16:37:35.129: ERROR/AndroidRuntime(349): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 09-22 16:37:35.129: ERROR/AndroidRuntime(349): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 09-22 16:37:35.129: ERROR/AndroidRuntime(349): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 09-22 16:37:35.129: ERROR/AndroidRuntime(349): at android.os.Handler.dispatchMessage(Handler.java:99) 09-22 16:37:35.129: ERROR/AndroidRuntime(349): at android.os.Looper.loop(Looper.java:123) 09-22 16:37:35.129: ERROR/AndroidRuntime(349): at android.app.ActivityThread.main(ActivityThread.java:4363) 09-22 16:37:35.129: ERROR/AndroidRuntime(349): at Your content must have a ListView whose id attribute is 'android.R.id.list' A: If it's an ListActivity your default list must be called like this: <ListView android:id="@android:id/list" See developer documentation http://developer.android.com/reference/android/app/ListActivity.html A: use this android:id="@android:id/listView1 instead of android:id="@+id/listView1 in case listactivity of you must declare id like this A: at Your content must have a ListView whose id attribute is 'android.R.id.list' If you are extending the ListActivity you should not use the setContentView(R.layout.main). So remove setContentView(R.layout.main) from your code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Graphing and filling an area based on 4 or 5 coordinate points using JavaScript or Coldfusion Thanks for taking a look at my question. I'm trying to create a graph that will show the range of widths/heights that will fit within a container. The graphs will always be shaped in one of the two ways show below: http://i.stack.imgur.com/jIrO3.jpg or http://i.stack.imgur.com/XGyU0.jpg I know the x/y coordinates of the red corners of the object. There will always be either 4 or 5 points. I need to fill the area between the points as well. I was not able to make this work with Coldfusion's CFCHART, and haven't found a way with JavaScript. Does anyone know how this can be done? Thanks in advance for your help! A: I would recommend to it with Raphael. This library allows drawing of various shapes on the web pages using vector graphic. A: Have you tried the Google Charts API?
{ "language": "en", "url": "https://stackoverflow.com/questions/7518311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Split Text in I have a very long text without space. For example, <div style="width: 179px"> WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW </div> I want to split this text into lines with maximum width 179px. Do you know how to do that? A: Use CSS. word-wrap: break-word; A: This won't work in ALL browsers, but it should at least work for most (this is CSS): #your_div { white-space: pre-wrap; white-space: -pre-wrap; white-space: -o-pre-wrap; word-wrap: break-word; } A: I think the css3 word-wrap:break-word property will sort this out for you. A: Add the style word-wrap: break-word; to the div. It is a CSS3 property that works in ALL browsers (even IE5!) A: You can apply the CSS style "word-wrap: break-word;" to the element. Here's an example You can also apply WBR tags to the word and it will split it according to those tags. Here's an example of that Learn more about wbr tags A: I would suggest word-wrap: break-word A: Just see below the link, http://jsfiddle.net/xj56D/2/ A: Use word-wrap: break-word: http://jsfiddle.net/gilly3/fS5cX/
{ "language": "en", "url": "https://stackoverflow.com/questions/7518318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: KSOAP2: How to use HttpsTransportSE? I am developing a android app to communicate with an web service that requires an SSL connection. To do that, I want to use HttpsTransportSE, but I can't find tutorials about how to use that class. I am trying to build a new instance, but I don't know exactly the info I must pass to the constructor. A line of my code: HttpsTransportSE httpsTransport = new HttpsTransportSE("address", port, ????, timeout); What string should be at ???? place? If I replace ???? by "" or null, an IOException occurs. I think ???? should be the client certificate. Is that right? Does anybody have a tutorial about HttpsTransportSE? Any useful link? A: This code from the HttpsTransportSE should help: public HttpsTransportSE (String host, int port, String file, int timeout) { super(HttpsTransportSE.PROTOCOL + "://" + host + ":" + port + file); this.host = host; this.port = port; this.file = file; this.timeout = timeout; } So to hit https://MyServer:8080/MyService You call: HttpsTransportSE("MyServer", 8080, "/MyService", timeout);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Update with iBatis I need to update the following table: TOPICS = where WORD_ID is a foreign key and both of them are the key of TOPICS. I would like to query with iBatis: UPDATE TOPICS SET TOPIC = #newTopic# WHERE WORD_ID = #wordId# AND TOPIC = #oldTopic#; What's the way of using multiple parameters which are not only strings?? Thanks a lot! A: At java side build a HashMap Map map = new HashMap(); map.add("NewTopic",aNewTopicValue ); map.add("OldTopic",anOldTopicValue ); map.add("WordId",aWordId ); Here the map values could be of any type (string or integer etc). In Ibatis query specify parameterClass="map". <update id="mySel" parameterClass="map"> UPDATE TOPICS SET TOPIC = #NewTopic# WHERE WORD_ID = #WordId# AND TOPIC = #OldTopic# </update> A: You can specify data type along with parameter like below WHERE WORD_ID = #wordId:NUMERIC# A: <parameterMap class="ibatis.util.Entity" id="mySel_map"> <parameter property="NewTopic" jdbcType="VARCHAR" /> <parameter property="WordId" jdbcType="INT" /> <parameter property="OldTopic" jdbcType="VARCHAR" /> </parameterMap> <update id="mySel" parameterMap="mySel_map"> UPDATE TOPICS SET TOPIC = #NewTopic# WHERE WORD_ID = #WordId# AND TOPIC = #OldTopic# </update> Refer the above code. we can use the 'parameterMap' tag to map the parameter and specify the jdbcType and javaType.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: s3fs unable to mount bucket I apologize in advance for asking such a stupid question, but how do I mount a s3 bucket on my file system using s3fs? I used the simple instructions given in: https://github.com/s3fs-fuse/s3fs-fuse/wiki/Fuse-Over-Amazon I have it all installed and I put my credentials in the /etc/passwd-s3fs file and then I just mounted it like so: s3fs myBucket /mnt/... -o use_cache=/tmp But when I try to view the files (using the 'ls' command), and when I try to access them in a small java program I wrote, the directory is just empty. What am I doing wrong? Just to note: I'm running it on a linux server. I also tried it on a local Ubuntu guest hosted on vmware running on windows 7. Thanks! A: s3fs uses its own metadata scheme that is not compatible with other s3 tools, so, e.g., if you're mounting a bucket using s3fs whose contents were created by another s3 tool, then the 'format' of the bucket contents (especially if there are folders) will most likely not be compatible so, best way is to start with/mount an empty bucket and then populate the bucket with data using s3fs itself A: s3fs Reinstall s3fs-c but "initial commit, 1.59 release" s3fs-cloudpack is commit ver. 1.61 (install example)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does a PHP SOAP web service consumsed by RPG need a WSDL? I have a very basic, beginners PHP web service: <?php function EchoText($text){ return "ECHO: ".$text; } $server = new SoapServer(null, array('uri' => "urn://tyler/res")); $server->addFunction('EchoText'); $server->handle(); ?> I understand some basics about WSDL's... that they "explain" how to access a web service, what functions it has, what parameters that function contains, and what the return value could be. Question 1) do I need to create a WSDL for an RPG program which will call my web service? Question 2) if yes to #1 -> do I need to manually do this by creating a new .xml document? Question 3) if yes to #2 -> could someone provide me a sample WSDL for such a simple web service (my example above)? I could then build my code and expand off the example. Thanks in advance for any help, suggestions or links!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: adding array (list of values) to a json object I try to loop through some json (clustered twees from twitter) and count how often particular keywords (hashtags) are present so I can create an ordered list of frequent words. this (19) that (9) hat (3) this I've done by creating var hashtags = []; first time I add a new word i add th word and give the value 1 hashtags[new_tag] = 1; the next time a find the same worj I just add to the number hashtags[hashtag]+=1; the result is a simple structure with words and values. I can list out what I need with $.each(hashtags, function(i, val){ console.log(i+ " - "+ val); }) Now I realize I also nee to know what clusters these words where found in. So; I thing I need to add a list (array) to my "hashtags". I guess what I try to create is a json structure like this: hashtags: {"this": 19, clusters: [1,3,8]},{"that": 9, clusters: [1,2]} How do I add the arrays to the hashtags object? A: First create an object for holding the hashtags: var hashtags = {}; Then if an hashtag has never been seen yet, initialize it: hashtags[new_tag] = { count: 0, clusters: [] }; Increment counts: hashtags[new_tag].count += 1; Add cluster: hashtags[new_tag].clusters.push(the_cluster); A: What you want is an Object ({ }) for hashtags since you are using strings as keys, not an Array ([ ]) which you would be appropriate if you were using index as the key. I'd structure it like this: var hashtags = { "this": { count: 19, clusters: [1, 3, 8] }, "that": { count: 9, clusters: [1, 2] } }; So, when you add a new hash tag, do it like this: hashtags[new_tag] = { count: 1, clusters: [cluster] }, And, when you increment a hash tag, do this: hashtags[hashtag].count++; hashtags[hashtag].clusters.push(cluster);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TinyMCE: How to disable code rewriting? I'm trying to prevent TinyMCE (in Joomla) from rewriting code (adding, removing, moving tags and attributes, etc). I don't want to setup every tag, just simply stop TinyMCE from changing my code. The TinyMCE configuration: verify_html:false; doesn't work for me and toggling to the source code view or clicking show/hide still causes the editor to modify my source code. A: Go into the configuration of the tinyMCE plugin in Joomla and disable the code cleanup. A: Go to: extensions (Should be on the top tab control) Click: Plug-in Manager This will take you to a list of all of Joomla's plugins... Disable any plugins that start with "-editor" This should leave you with a bare bones editor which edits and saves basic text for Html without regard for what's in it. It's not pretty but if you found half as many bugs in Joomla's editor as I did, you'll be glad of the change. A: Additional to Hackwars answer: There is a file called tinymce.php holding the tinymce configuration. In this file you can change all necessary settings. To disable the cleanup functionality you need to set cleanup: false, A: Joomla 2.5 (and 3.0) Solution: Login to your administration and go to Site > Global Configuration > Text Filters. You can see that any input will have some joomla-side filters (regardless of what editor you use). At that place you can easily change text filtering for any User Group. Now Change Default Blacklist to No filtering for Super Users group. More info at http://docs.joomla.org/Help30:Site_Global_Configuration#Text_Filters
{ "language": "en", "url": "https://stackoverflow.com/questions/7518351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: switching connection strings in c# Are there any standards for switching out connection strings for different environments in C# web apps? I'm currently evaluating which ways are the most secure including where to store them. I've seen people simply add them to the web config and switch them in code with if statements checking which environment they are on, but this seems cumbersome. Any ideas? Thanks. A: How bout Web config transformation? It's available with VS2010 A: i find the answer to questions like this is that if you're having to manually do anything to your application's configuration you're doing it wrong. check out this scott hanselmen blog/video on web deploy. the best 45 minutes you'll spend this week. A: This should be part of your automated build process. I am a developer for BuildMaster, and it will handle this configuration file dilemma quite easily. Basically, you can create one "instance" of a configuration file in the tool for each environment you have, and you can even restrict access to any instance so for example, no developers could see production's configuration. When you're configuring the deployment plans to a certain environment, you can specify the instance you want to deploy, or you can deploy them manually from the tool at any time. If you want more information, take a look at our configuration files feature section.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Akamai CDN integration with Sitecore For our website, we want to use Akamai as CDN. The problem we have intercept all the html and change media URL's to akamai URL's. for eg: ~/media/Marketing/Stages/EmailMarkeImg.ashx http://media.akamai.com/~/Marketing/Stages/EmailMarkeImg.ashx So, right now, i am intercepting this using Response filters in a HttpModule. But there are performance issues with this, reason is, we need to find out all the tags with ~/media and append that name :http://media.akamai.com before all the This is really a performance issue from the response point of view. This is my first sitecore project and i am trying get a deep insight into this. But, i know you guys must have already done these kind of things. Please help me in this case. PS: Any options of extending the pipe lines, when the current item is looking for a media library image, just appending the akamai domain path. Please let me know. Thanks, A: If you are running 6.4 or later you can use the setting Media.MediaLinkPrefix. Example patch: http://cdn.mydomain.net/~/media/ This works only for media items in the media library. A: I've answered this before: How can I configure Sitecore so that it generates absolute links to media items? Short summary: there is no configuration to do this, you need to override some of the built-in methods to do this. See the above link for the exact details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518358", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: IE is still caching page content for a few seconds when META tags are applied. What to do? I have a scenario where the main website (which I have no control over) is loading my website from within an iframe. It's a GET with query string parameters chosen by the user on the main website. The issue is that IE caches my first page inside of that iframe. I applied the following meta tags: <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/> <meta http-equiv="Pragma" content="no-cache"/> <meta http-equiv="Expires" content="0"/> But IE is still caching it just for about 15 - 20 seconds or so. So if the user quickly goes back to the main website and chooses something else, they would see the cached version of my first page. What can I do here? A: Try busting the cache from the server by setting appropriate HTTP response headers: public class NoCacheAttribute : ActionFilterAttribute { public override void OnResultExecuting(ResultExecutingContext filterContext) { var cache = filterContext.HttpContext.Response.Cache; cache.SetExpires(DateTime.UtcNow.AddDays(-1)); cache.SetValidUntilExpires(false); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); cache.SetCacheability(HttpCacheability.NoCache); cache.SetNoStore(); } } and then decorate your controller action that is supposed to serve the <iframe> with this attribute: [NoCache] public ActionResult Foo() { ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem with List box count in asp.net website <asp:ListBox ID="ListBoxMembers" runat="server" SelectionMode="Multiple" DataValueField="FirstName"></asp:ListBox> I have this list box inside a pop up, When the user selects multiple user and click save button this is executed int countSelected = ListBoxMembers.Items.Cast<ListItem>().Where(i => i.Selected).Count(); string groupName = txt_GroupName.Text; var selectedNames = ListBoxMembers.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToList(); foreach(var FirstName in selectedNames) { Query } Here, the countSelected and selectedNames is always 0. where am i going wrong. I databind the listbox A: My guess is you databind on Postbacks too so the list gets repopulated before your event handler executes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wordpress Taxonomy - how does it know which object_id? I'm working on a project and would like to create a similar functionality that Wordpress has for taxonomy. I'm not quite sure how it all works though. They have 3 tables that are related: wp_terms ( term_id, name, slug, term_group ) wp_term_taxonomy( term_taxonomy_id, term_id, taxonomy, description, parent, count ) wp_term_relationships( object_id, term_taxonomy_id, term_order ) From what I can tell, object_id is a generic name for what is either a link_id or post_id, but how do you know which one it is to query against it? It also seems like wp_terms could be combined with wp_term_taxonomy. wp_term_taxonomy has the 'taxonomy' column, which is 'category' or 'link_category' by default, but other than that it just seems to reference the term_id, which has the slug and name. Any clarity would be awesome... really not seeing how this fits together. Thank you! A: * *assume that wp_terms is a master table of category. *wp_term_taxonomy is a table in which you can define categories hierarchy. Below are description of fields term_taxonomy_id = primary key(i think it is same as term_id most of the time) term_id = reference key to term_id of wp_terms table. taxonomy = type of category(category=post category, link_category= link category,post_tag = tags associated with posts, nav_menu = navigation menu, etc. ) parent = id of parent category *assume that wp_term_relationships is a relationship table of product and category. where object_id is product id and term_taxonomy_id is category id
{ "language": "en", "url": "https://stackoverflow.com/questions/7518362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: PHP: How to use params here? I am making a function so that I can post from Ajax using a general function where I just pass the params, to avoid having to create one php file for each Ajax function. This is how my function looks right now in the PHP side after receiving, via post, the params that you can see in the code: $class_name = $_POST['class_name']; $function_name = $_POST['function_name']; $params = "'" . implode("','", $_POST['params']) . "'"; $model = new $class_name(); //Apply the function echo $model->$function_name($params); It is working except from the part of the params... PHP is interpreting it as one param, what can I do so that $params is not intepreted as a single string? A: The third line actually makes $params a single string containing all the params. Depending on your framework (and how you're passing the params in your Ajax stuff), you might be able to pass $_POST['params'] as is to the method, rather than passing $params. In which case you don't need to build the string at all. If you need to call a function that expects the params to be passed individually, instead of in an array like that, try call_user_func_array(array($model, $function_name), $params) If $params contains 1, 2, and 3, and $function_name is 'foo', the above expression would be equivalent to $model->foo(1, 2, 3). Note, this will let people call any public method of any class that's available to your script. You need some kind of access control in order to keep people from running random stuff. As suggested in the comments on your question, a whitelist of some kind (even if it's just a member variable that says whether the class was meant to be used by random code like this) would go a long way toward preventing security issues. A: Don't implode them. Pass them as an array, like $_POST already is. echo $model->$function_name($_POST['params']);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Creating a screenshot of a gtk.Window For testing and documentation purposes I would like to create a screenshot of a gtk.Window object. I'm following a basic pygtk sample at the moment. The example with my modifications looks like the following: import gtk def main(): button = gtk.Button("Hello") scroll_win = gtk.ScrolledWindow() scroll_win.add(button) win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.add(scroll_win) win.show_all() if win.is_drawable() is not True: raise RuntimeError("Not drawable?") width, height = win.get_size() pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height) screenshot = pixbuf.get_from_drawable(win, win.get_colormap(), 0, 0, 0, 0, width, height) screenshot.save('screenshot.png', 'png') if __name__ == '__main__': main() gtk.main() I'm ending up with an error when the get_from_drawable method is invoked. TypeError: Gdk.Pixbuf.get_from_drawable() argument 1 must be gtk.gdk.Drawable, not gtk.Window Apparently the screenshot example that I merged into the basic example is using a gtk.gdk.Window that inherits from gtk.gdk.Drawable. My questions: * *Is there another way to make the Pixbuf object capture the window? *Can I make a gtk.Window a gtk.gdk.Window or find the gtk.gdk.Window functionality within the gtk.Window? A: The key difference to understand is that gtk.gdk.Window isn't a "window" in the sense that most people think of. It's not a GUI element, it's just a section of the screen that acts as a logical display area, as explained in the documentation. In that way, it is more of a low-level object. A gtk.Window object (the traditional "window") contains a window attribute which is the gtk.gdk.Window object that is used by the gtk.Window. It gets created when the window is initialized (in this case, after the call to win.show_all()). Here's a revision of your code that saves the image correctly: import gtk import gobject def main(): button = gtk.Button("Hello") scroll_win = gtk.ScrolledWindow() scroll_win.add(button) win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.add(scroll_win) win.show_all() # Set timeout to allow time for the screen to be drawn # before saving the window image gobject.timeout_add(1000, drawWindow, win) def drawWindow(win): width, height = win.get_size() pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height) # Retrieve the pixel data from the gdk.window attribute (win.window) # of the gtk.window object screenshot = pixbuf.get_from_drawable(win.window, win.get_colormap(), 0, 0, 0, 0, width, height) screenshot.save('screenshot.png', 'png') # Return False to stop the repeating interval return False if __name__ == '__main__': main() gtk.main() The timeout is necessary because even though the gtk.gdk.Window object has been created, the screen still hasn't been drawn, until gtk.main() starts running, I think. If you read the pixel buffer right after win.show_all(), it will save an image, but the image will be the section of the screen that the window will later take up. If you want to try it for yourself, replace the call to gobject.timeout_add with a simple call to drawWindow(win). Note that this method saves an image of the GTK window, but not the border of the window (so, no title bar). Also, as a side point, when defining a function that was called using gobject.timeout_add, you don't actually have to use return False explicitly, it just has to evaluate to a value equivalent to 0. Python return None by default if there is no return statement in the function, so the function will only be called once by default. If you want the function to be called again after another interval, return True. Using signals As noted by liberforce, instead of using a timeout, a better method would be to connect to the signals that are used by GTK to communicate events (and state changes in general). Anything that inherits from gobject.GObject (which all widgets do, basically) has a connect() function which is used to register a callback with a given signal. I tried out a few signals, and it appears that the one we want to use is expose-event, which occurs anytime a widget needs to be redrawn (including the first time it is drawn). Because we want the window to be drawn before our callback occurs, we'll use the connect_after() variant. Here's the revised code: import gtk # Don't use globals in a real application, # better to encapsulate everything in a class handlerId = 0 def main(): button = gtk.Button("Hello") scroll_win = gtk.ScrolledWindow() scroll_win.add(button) win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.add(scroll_win) # Connect to expose signal to allow time # for the window to be drawn global handlerId handlerId = win.connect_after('expose-event', drawWindow) win.show_all() def drawWindow(win, e): width, height = win.get_size() pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height) # Retrieve the pixel data from the gdk.window attribute (win.window) # of the gtk.window object screenshot = pixbuf.get_from_drawable(win.window, win.get_colormap(), 0, 0, 0, 0, width, height) screenshot.save('screenshot.png', 'png') # Disconnect this handler so that it isn't # repeated when the screen needs to be redrawn again global handlerId win.disconnect(handlerId) if __name__ == '__main__': main() gtk.main()
{ "language": "en", "url": "https://stackoverflow.com/questions/7518376", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I create an object from a string I have this object set: Object A Object AA: A Object BB: A Object CC: A how do i create an object of type AA Given a string variable with "AA" in it? I've been looking at the Activator stuff but can't quite figure it out. A: You need to get the Type instance for AA, then pass it to Activator.CreateInstance. Type myType = typeof(SomeTypeInProject).Assembly.GetType(typeName); object instance = Activator.CreateInstance(myType);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to dynamically adapt the layout by using only CSS Depending by the size of the app interface, I need to adapt dynamically the layout by using only CSS. It will be possible? If the width of my app is 500px, I'd like to display the 3 containers in this way: | A B | // width 500px | C | If the width of my app is 750px, I'd like to display the 3 containers in this way: | A B C | // width 750px Here is the example. By clicking on the button "change app size" you can change the size of the container. A: Using CSS3 Media Queries, yes you can. @media (min-width:500px) { ... } See http://www.w3.org/TR/css3-mediaqueries/ for more information. A: With CSS media queries: <link type="text/css" rel="stylesheet" href="style.css" /> <link rel="stylesheet" media="screen and (max-width: 500px)" href="css/mobile-500.css" /> <link rel="stylesheet" media="screen and (max-width: 750px)" href="css/mobile-750.css" /> A: You'll probably want to look into css media queries. Check out this link - http://coding.smashingmagazine.com/2010/07/19/how-to-use-css3-media-queries-to-create-a-mobile-version-of-your-website/
{ "language": "en", "url": "https://stackoverflow.com/questions/7518386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Coldfusion: need help with outputing query on one row per system instead of multiple rows HISTORY: A system has passed through 1 - 19 or so statuses before being moved to production. I need to build a report showing the date the system passed through a status and NA if the system did not pass through a status. REQUIREMENTS: The report needs to look something like this: System Initial Operations PIM_Assigned PIM_Complete Database Application Server001 9/1/2011 NA 9/2/2011 NA NA 9/1/2011 Server002 9/10/2011 NA 9/5/2011 9/25/2011 NA 9/9/2011 Server003 9/21/2011 9/22/2011 NA NA 9/24/2011 NA Server004 9/23/2011 9/19/2011 9/23/2011 9/20/2011 9/23/2011 9/1/2011 Here is the query with a sample data dump following (dump does not match above - the above is for illustration purposes): select status, convert(varchar,effectivedate,101) e, systemname from si_statushistory where systemname='SERVER052' order by e desc, history_id desc with output from my query looking like this: PSI 09/09/2011 SERVER052 Application 09/09/2011 SERVER052 Operations 09/09/2011 SERVER052 Application 07/14/2011 SERVER052 Operations 07/13/2011 SERVER052 Operations 07/13/2011 SERVER052 PSI 07/13/2011 SERVER052 PIM Assigned 06/08/2011 SERVER052 PSI 06/08/2011 SERVER052 SD_Verify 01/15/2012 SERVER052 PSI Operations 01/08/2012 SERVER052 Frame Team 01/01/2011 SERVER052 Example of what ONE row would look like: something is missing here I hope this is clear and makes sense... The page is being displayed using Coldfusion and I'm adequate with using Arrays and Structures if that makes this easier to build out. Time of of the essence which is why I'm reaching out for some help. I could do this but I need it sooner than later. A: CREATE PROCEDURE dbo.ReturnPivotedSystemInfo AS BEGIN SET NOCOUNT ON; ;WITH x AS ( SELECT [system] = systemname, [status], ed = CONVERT(CHAR(10), effectivedate, 101), -- not varchar w/o length rn = ROW_NUMBER() OVER (PARTITION BY systemname, status ORDER BY effectivedate DESC) FROM dbo.si_statushistory -- where clause here ) SELECT [system], Initial = COALESCE(MAX(CASE WHEN [status] = 'Initial' THEN ed END), 'NA'), Operations = COALESCE(MAX(CASE WHEN [status] = 'Operations' THEN ed END), 'NA'), PIM_Assigned = COALESCE(MAX(CASE WHEN [status] = 'PIM Assigned' THEN ed END), 'NA') --, repeat for other possible values of status FROM x WHERE rn = 1 GROUP BY [system]; END GO Now your ColdFusion just needs to execute the stored procedure dbo.ReturnPivotedSystemInfo and from there on it should be able to behave just as if you had called SELECT * FROM sometable...
{ "language": "en", "url": "https://stackoverflow.com/questions/7518388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Spring MVC support JSR 311 annotations? While helping out someone else, I noticed they were trying to do Spring development using the @GET, @Consumes, and @Path annotations. It is my understanding that these annotations come from the JSR-311 specification. I simply suggested that they use the Spring @RequestMapping annotation for mapping endpoints to their controller, but it made me curious as to whether or not Spring MVC (any version) supports JSR 311? A: Short answer: NO. To quote Juergen Hoeller: We're considering integration with JAX-RS on a separate basis - separate from Spring MVC's own endpoint model -, possibly supporting the use of Jersey (the JAX-RS RI) with Spring-style beans in a Spring web application context. This might make Spring 3.0 as well, depending on the finalization of JSR 311 and Jersey in time for Spring 3.0 RC1. Otherwise it would be a candidate for Spring 3.1. However I haven't found such a support neither in 3.0 nor in 3.1. Of course you can integrate frameworks like Apache CXF and use standard JSR-311 annotations. Spring MVC itself does not recognize these annotations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Jenkins/Hudson Build All Branches With Prioritization How do I configure Jenkins to build all branches while giving the master branch the highest priority? My first idea was to create two jobs with one configured to build all branches and the other to just build master, then using the job priority plugin to configure master ahead. This doesn't work since all branches obviously builds all branches including master. A: Git plugin has the BuildChooser extension point for this kind of purposes. Git plugin tells you all the interesting revisions that you might want to build (new tip commits that haven't been built before), and BuildChooser gets to decide which revision gets built. So if your BuildChooser always prefer to build the mater, you get the desired semantics. A: Christopher solved my question by writing the functionality. Give this guy some karma.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Concatenating a nested list with differing number of elements I am a newbie to R and have a concatenation problem that I haven't been able to solve. I have a huge data frame of the form: station POSIX date.str forec.time lead.time mean.ens obs 6019 2011-08-06 06:00 20110806 00 006 45 67 6019 2011-08-06 07:00 20110806 00 007 69 72 6031 2011-08-06 12:00 20110806 06 006 87 95 6031 2011-08-06 13:00 20110806 06 007 88 97 I have use "ply" to split the data frame like this mydata.split <- dlply(mydataframe, .(datestr), dlply, .(forec.time), dlply, .(lead.time), identity, .drop = FALSE) I do some calculation with data, which require that data are split up this way. I call this new list mynewlist af calculations. I would like to concatenate these data, but I run into problems because of differing number of list elements. > length(mynewlist[[1]][[1]]) [1] 34 > length(mynewlist[[1]][[2]]) [1] 38 I have tried to use do.call( rbind, do.call( rbind, do.call( rbind, mynewlist) ) ) to concatenate the list into a data frame, but I get the following message: In function (..., deparse.level = 1) : number of columns of result is not a multiple of vector length (arg 1) Is there a way of concatenating a nested list with differing number of elements? I am greateful for help or a point in a direction. Regard Sisse A: Just use ldply to stitch all those lists back together. With the baseball data in plyr, use dlply as in your question to spit the data: library(plyr) x <- dlply(baseball, .(year), transform, mean_rbi = mean(rbi)) Now use ldply to combine the lists into a data.frame: y <- ldply(x) The results: str(y) 'data.frame': 21699 obs. of 23 variables: $ id : chr "ansonca01" "forceda01" "mathebo01" "startjo01" ... $ year : int 1871 1871 1871 1871 1871 1871 1871 1872 1872 1872 ... $ stint : int 1 1 1 1 1 1 1 1 1 1 ... $ team : chr "RC1" "WS3" "FW1" "NY2" ... $ lg : chr "" "" "" "" ... $ g : int 25 32 19 33 29 29 29 46 37 25 ... ... $ rbi : int 16 29 10 34 23 21 23 50 15 16 ... ... $ gidp : int NA NA NA NA NA NA NA NA NA NA ... $ mean_rbi: num 22.3 22.3 22.3 22.3 22.3 ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7518394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I import a VS2005 Solution for C++ App into an IDE for debugging it on Linux? Can I import a VS2005 Solution for C++ app into some IDE that runs on Linux and allows me to debug the app? It is a working app and already has a makefile for Linux. A: Codelite allows you to import Visual Studio projects http://www.codelite.org/ However, it also allows you to import Makefile based projects, and you will probably get more mileage using this method. You can then use the codelite IDE to debug your application. It is just a wrapper around the GDB debugger. Although using codelite to debug your application will be more user friendly, I recommend learning GDB as there may be situations where you need to debug something and an IDE is not available. A: If you want an IDE on Linux, to perform the debugging with, you can use Eclipse, Kproject, etc, but you will have to create a project and then import your code manually to get it to work. It might be more work than its worth, so you might be just as well served with n.m.'s comment to your question in using gdb and ddd.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Code cleaning in entity framework This is a question that is completely a matter of opinion. But it might also be a question about stupidity from my side. Its working fine both ways. But I want to find out what people think. public IQueryable<User> Users { get { return context.Users; } } There we go... Thats a function that is returning all users from the EntityFramework context, its in my repository. context.Users is a IObjectSet btw. public User GetUserById(int userId) { return context.Users.FirstOrDefault(u => u.UserId == userId); } This is an example of another function in my repository. As I do here I use context.Users. I might aswell write it like this. public User GetUserById(int userId) { return Users.FirstOrDefault(u => u.UserId == userId); } I want to use the last one cause the code looks cleaner. But will this effect the performance in any way at all?! This is propably a stupid question... But Im abit new to working with bigger projects where every small detail could count. (I know that entity framework might be the wrong way to go but Its not my call) A: It seems like you're describing a layer of indirection/abstraction between your consuming code and Entity Framework. I consider this a good thing. I actually modify the T4 POCO templates to automatically generate what you have in #1 and generate an interface that just returns IQueryables. Many modern ORMs offer LINQ support these days...and it's nice to know that the rest of your code doesn't have to know what ORM it's talking to...in case you decide to move away from Entity Framework at some point. To answer your question about performance: no I don't think it will adversely affect performance. There are a few extra CIL statements being generated in your compiled code, but that's about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calling a copy constructor with instance being created I am not asking about the logic of such a call, rather I'm interested in a difference of support b/w Visual C++ and GCC / Clang. Visual C++ will not allow a new instance of an object to be used as the parameter for its own copy constructor. GCC and Clang allow this. Considering that 'int i = i;' is allowed, I'm wondering whether Visual C++ has a bug. class test { private: test() {} public: test(const test& t) {} }; int main(void) { int i = i; test t(t); -- this line gives an error in Visual C++ return 0; } A: To quote the C++ standard (3.3.2): The point of declaration for a name is immediately after its complete declarator and before its initializer In your first statement, the declarator ends after int i, and so the name i is available where it's used in the initializer (= i), so the statement is well-formed, but its behaviour is not defined. In your second statement, the declarator ends after test t(t), and there is no initializer; the name t is not available where you use it, so the statement is ill-formed. So the compiler is behaving correctly. I would hope it could be configured to give a warning about the first statement, but it's not required to reject it; it is required to reject the second, as you say it does. A: test t(t); -- this line gives an error in Visual C++ Where have you defined t? The compiler is not physic!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to disable CKEditor dialog skin? I hope somebody can give me some idea on this. I have a CKEditor 3.6 dialog which contains a single element of type html and loads an external page (or actually it's body html content). The style sheet for that page is loaded by MediaWiki 1.17 resource loader. My problem is that CKEditor skin takes priority over my style sheet. In firebug I can even disable CKEditor styles and see how the page gets it's original shape. Is there a way maybe to disable CKEditor style sheet for this dialog or lower its priority? Or any other way to solve this? Any ideas will be appreciated. Update: so simpler question is how can I remove inherited CSS properties which break my design? A: Please check something with Firebug: Open your dialog window and right click in the HTML element that contains the external content, then select "Inspect Element". In Firebug, select the HTML panel, then select the Style pane on the right side and make sure that the "Only Show Applied Styles" option is Not checked. Look at the right side of the style pane where the source file for each style block is shown, do you see that your style sheet (from the resource loader) is providing some of the styles? Do the styles from your style sheet all have lines through them to indicate that they've been overridden? In the past, I've used the information from the HTML and Style panes to create more targeted selectors for the styles, you may be able to over-ride the editor styles using that approach. Please provide the code being used: What is the structure of the external HTML content (including any classes and ids or styles)? Is the entire block enclosed in a container (div or table)? Are any of your styles targeted through the <body> tag of the external page? For the dialog code, you can strip out any functionality, unless it's pertinent like .addClass(). Just show the structure of the tab like so: CKEDITOR.dialog.add( 'Plugin Name', function( editor ) { return { title : Plugin.title, minWidth : 350, minHeight : 230, contents : [ { id : 'TabId', label : Lang.TabId, title : Lang.TabId, elements : [ { id : 'ElementId', type : 'html', label : Lang.ElementId, title : Lang.ElementId, style : 'text-align: center;', html : '<div>' + Some Content + '</div>', children : [ Viewing the code will make it easier to answer your question. Be Well, Joe
{ "language": "en", "url": "https://stackoverflow.com/questions/7518415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JQuery Username Validation with asp.net I am using the best tutorial of encosia website which was written by David ward and by his example given in his website for instant validation of username. Here is the link of the original post: http://encosia.com/aspnet-username-availability-checking-via-ajax/ So the problem here with this code is though I am using my custom membership it is always showing me the user is "Available" instead of "Not Available" if the user is not in the database. Here is my code: protected void Username_Changed(object sender, EventArgs e) { System.Threading.Thread.Sleep(2000); if (Membership.GetUser(Username.Text) != null) { UserAvailability.InnerText = "Username taken, sorry."; UserAvailability.Attributes.Add("class", "taken"); Button1.Enabled = false; } else { UserAvailability.InnerText = "Username available!"; UserAvailability.Attributes.Add("class", "available"); Button1.Enabled = true; } } This is my web.config: <connectionStrings> <remove name="LocalSqlServer"/> <add name="LocalSqlServer" connectionString="Data Source=.\sqlexpress;Initial Catalog=CustomMembership;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> <membership defaultProvider="CustomMembership"> <providers> <add name="CustomMembership" connectionStringName="LocalSqlServer" enablePasswordReset="true" enablePasswordRetrieval="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="0" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordAttemptWindow="5" passwordStrengthRegularExpression="" type="System.Web.Security.SqlMembershipProvider" /> </providers> </membership> A: try replacing (Username.Text) with (sender as TextBox).Text, if protected void Username_Changed is triggered by change in textbox
{ "language": "en", "url": "https://stackoverflow.com/questions/7518417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove page/ of High Voltage for statics page rails Hello I am using High Voltage for my statics pages in rails but I see the next structure when I make my statics pages: myserver.com/pages/about myserver.com/pages/privacy myserver.com/pages/terms . . . . I don't want that "page" word appear. I want that appear this structure myserver.com/about myserver.com/privacy myserver.com/terms Thank you very much. Regards! A: see this bug this might work: match '/:id' => 'high_voltage/pages#show', :as => :static, :via => :get EDIT: When you use the above instructions, you also need to go through your views and change all instances of: page_path(:id=>:about) to: static_path(:id=>:about)` or better yet, just: static_path(:about) So find all the link_to's in your views and make the changes above... Your urls will no longer have the word pages in them hope this helps A: You can remove the need for the "/pages" portion of the URL by adding the following to your config/routes.rb file. match '/*id' => 'high_voltage/pages#show', :as => :static, :via => :get The "*" will allow support for nested directories. Then you can create a link "/en/test" pointing to app/views/pages/en/test.html.erb as follows: <%= link_to "Test", static_path("en/test") %> To complete your semi-static setup, you may wish to consider 2 more things. 1) Some basic routes (placed above the previous route line) for default content for directories (as required) root :to => 'high_voltage/pages#show', :id => 'index' # map root to 'index.html' match '/en' => 'high_voltage/pages#show', :id => 'en/test' # map '/en' to '/en/test.html' 2) A nice SEO redirection to remove any extra trailing slashes: http://nanceskitchen.com/2010/05/19/seo-heroku-ruby-on-rails-and-removing-those-darn-trailing-slashes/ A: This works for me: match '*id', :to => 'high_voltage/pages#show' A: According to the documentation this can now be done by adding the code below to the high_voltage initializer. I have used this successfully in rails 4+ using the 2.4 version of the gem. # config/initializers/high_voltage.rb HighVoltage.configure do |config| config.route_drawer = HighVoltage::RouteDrawers::Root end
{ "language": "en", "url": "https://stackoverflow.com/questions/7518418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Changing max_allowed_packet property with Hibernate configuration Is there a way to change max_allowed_packet with the Hibernate XML configuration file? This is my Spring injection for Hibernate <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>jdbc:mysql://localhost:3306/surveysmart</value></property> <property name="username"><value>root</value></property> <property name="password"><value>xxx</value></property> </bean> <!-- Session Factory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource" /> </property> <property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" /> <property name="packagesToScan" value="com.sdl.contacts.vo" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> A: max_allowed_packet is a mysql configuration option. You should set it in your mysql configuration. http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html A: If you wan to changed it for this clients connections only you can try passing it as parameter in the jdbc url. jdbc:mysql://localhost:3306/surveysmart?max_allowed_packet=<value> As @hvgotcodes suggests it is better to change in the mysql server configuration.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: YouTube Annotations via PHP Zend Framework Is it possible to add annotations to a YouTube video using the PHP Zend framework and the YouTube API? A: It appears that the YouTube API does not support this functionality. It is currently a feature request here: http://code.google.com/p/gdata-issues/issues/detail?id=558
{ "language": "en", "url": "https://stackoverflow.com/questions/7518429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to strip_tags all tags from 0 to 300 chars and from 301 to allow only some tags I was wondering how on a given post that contains HTML also, to strip_tags($entry->description); from char 0 to 300 and from 301 to end of post allow only <b><p><br> strip_tags($entry->description, '<b><p><br>'); I am looking for a way that does not kill performance though, because I want the page to load fast. Thank you. A: Just strip_tags() the two parts separately: $start = strip_tags(substr($entry->description, 0, 300)); $rest = strip_tags(substr($entry->description, 300), '<b><p><br>'); $start . $rest;
{ "language": "en", "url": "https://stackoverflow.com/questions/7518431", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: python function to break a message in n lines Hy everyone, i want to do something like this but my logic is not so goog. I have a message, that must be 80 chars in every line: I can do this like this: msg = '' msg_list = [] for i in dict['msg']: if len(msg) >= 80 and i.isspace(): msg_list.append(msg) msg = "" msg += i The problem here is when my msg don't have 80 chars, any idea to make this block work better? A: import textwrap msg_list = textwrap.wrap(dict['msg'], 80) A: import re input = "put your text in here" tokens = re.split('\s', input) w = [] s = "" for token in tokens: if len(s) + len(token) < 80: s = " ".join([s,token]) else: w.append(s) s = "" print w A: Check the 80th character. If it's a space you can break the line. If not check the 79th. Rinse. Repeat Let's say you broke at char 76. Now check the (76+80)th character if it's a space. Etc. Ect. If you can't turn this into code, post your best attempt and we can advise from there. Also, for i in dict['msg']: doesn't make sense. Have you redefined the built in dict type?
{ "language": "en", "url": "https://stackoverflow.com/questions/7518432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do i access the non-final variable number inside an inner class in Java? This is my first time programming in Java so i can't understand why i can't access the variables outside of a function. I tried to change the variable to final but there's still an error: The final local variable number cannot be assigned, since it is defined in an enclosing type When there's no final keyword in the variable, the error is this: Cannot refer to a non-final variable number inside an inner class defined in a different method Here's my code: String[] number = this.nextNumber(); Button submitbutton = (Button)findViewById(R.id.button1); submitbutton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks //Toast.makeText(Addition.this, inp.getText(), Toast.LENGTH_SHORT).show(); if(inp.getText().toString().equals("")) { Toast.makeText(Addition.this, "Please enter your answer", Toast.LENGTH_SHORT).show(); } else { int answer = Integer.parseInt(inp.getText().toString()); if(Integer.parseInt(number[1]) == answer) { Toast.makeText(Addition.this, "NICE!", Toast.LENGTH_SHORT).show(); int currentPoint = Integer.parseInt((String) points.getText()); currentPoint = currentPoint + 1; points.setText(Integer.toString(currentPoint)); number = Addition.this.nextNumber(); // this part doesn't work. why? } else { Toast.makeText(Addition.this, "Wrong!", Toast.LENGTH_SHORT).show(); } } } }); I put a comment on the part that doesn't work. please tell me why A: Well, the two rules you're coming up against are exactly as the compiler states: * *A final variable has to be assigned exactly once - you can't change its value later *You can only access local variables from an anonymous inner class if they're final It's not clear what you're trying to do or why you're trying to change the value of the local variables from within your OnClickListener. What's the bigger picture here? Could you maybe declare a variable within the anonymous inner class itself, or make it an instance variable within your class? If you're new to Java I would strongly advise you to write simpler code to start with. Anonymous inner classes are relatively advanced. I'd actually encourage you to play with Java as a language on the desktop before starting Android development - play with the core libraries (collections, IO etc) and any interesting bits of the language within a simple console app which will be easy to start and debug without any Android-specific complications to hamper you. A: EDIT: As Jon says using a listener to modify a local variable is no use, when the listener assigns it a value the local variable would have gone out of scope and not reachable by any other means. What I write below makes sense only if number has life outside of this method. Inside the anonymous inner class you can only access final variables of the containing scope. But you cannot assign to final variables. The usual trick used is to use a final wrapper around a non-final variable. For example if number was a String, not an array (String[]) then the following will work: final String[] number = new String[] { this.nextNumber(); } // number[0] has the number, number itself is final wrapper Button submitbutton = (Button)findViewById(R.id.button1); submitbutton.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Perform action on clicks //Toast.makeText(Addition.this, inp.getText(), Toast.LENGTH_SHORT).show(); if(inp.getText().toString().equals("")) { Toast.makeText(Addition.this, "Please enter your answer", Toast.LENGTH_SHORT).show(); } else { int answer = Integer.parseInt(inp.getText().toString()); if(Integer.parseInt(number[1]) == answer) { Toast.makeText(Addition.this, "NICE!", Toast.LENGTH_SHORT).show(); int currentPoint = Integer.parseInt((String) points.getText()); currentPoint = currentPoint + 1; points.setText(Integer.toString(currentPoint)); number[0] = Addition.this.nextNumber(); // number is final and cannot be assigned but number[0] can } else { Toast.makeText(Addition.this, "Wrong!", Toast.LENGTH_SHORT).show(); } } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7518436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: printing UTF8String in XCode Debugger Console While printing contents of a NSTextField the debugger is displaying following character sequence \342\200\250 for newline. Can anyone tell me how to interpret this sequence, I expect it to be newline character since I entered newline after Headline news 1 print (Ptr)[[sender objectValue] UTF8String] $15 = 0x14a1b0 "Headline news 1\342\200\250Headline news 2\342\200\250Headline news 3\342\200\250Headline news 4" Also po [sender objectValue] outputs something like this (gdb) po [sender objectValue] Headline news 1
     Headline news 2
     Headline news 3     
Headline news 4 Thank you A: \342\200\250 (specifically, the bytes with values 0342 = 0xe2, 0200 = 0x80, and 0250 = 0xa8) is the UTF-8 encoding of Unicode character U+2028, named "LINE SEPARATOR". The newline that you entered is being interpreted as U+2028 for some reason, and then it is encoded as UTF-8 and printed out as a series of octal escapes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unexpected Error message from WCF service I have one wcf webservice deployed on server. In case of an exception the error message behaves like code is getting executed from local machine. For example the below error message indicates the local machine folder where actual code is stored. for example "C:\initpub...". Why i am getting this error on server. Any suggestion? Message: Object reference not set to an instance of an object. Trace: Server stack trace: at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at Domain.ExternalAccount.ExternalAccount.InsertExternalAccountWithPositions(ExternalAccountWithPositionsInParam request) at Domain.ExternalAccount.ExternalAccountClient.InsertExternalAccountWithPositions(ExternalAccountWithPositionsInParam request) in C:\Inetpub\wwwroot\Site\Secure\finplanextsvc\NaviplanExternalServices\Domain\ExternalAccount.cs:line 3145 at NaviplanExternalServices.NaviplanExternalAccount.InsertExternalAccount(AccountType acctType, ExternalPosition[] positions) in C:\Inetpub\wwwroot\Site\Secure\finplanextsvc\NaviplanExternalServices\NaviplanExternalServices\Services\NaviplanExternalAccount.svc.cs:line 178 A: The original source path and line number are stored in the .pdb file that is built along with your application. If you also deploy the .pdb with your .dll, then you get these in your stack traces. That is the default .net behavior, and is actually makes throwing an exception slower to execute if you have the .pdb in the deploy directory next to the .dll or .exe. You can remove that detail from the error message by not deploying, or deleting the .pdb file. A: The source file location is compiled into the .pdb when you build the project. It always refers to the source path from where it was built.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP set_time_limit limit QUESTION Would it work fine if I use sleep(300); to do a whole day (24 hours) in 5-minute gaps? This means, would set_time_limit (86400); work? Then I can set my host's schedule to only be used once every 24 hours. INFO I found what I am doing now on this question and am now using it to do something every 5 minutes. It works well and is on time with even the seconds correct. (Talking about the gap between each sleep) - it sleeps 3 times and then gets called again from my host's-schedular. I have a scheduled task set up at my host for every 15 minutes, problem is this is not happening every (precise) 15 minutes, but more like 16 and a bit minutes - and after a few hours it is totally out of sync. If it's possible to use it to not quit within 24hrs, then I can adjust the sleep in the code to make it execute exactly every 5 mins. UPDATE 17:17:50 22-09-2011 Check done! 17:34:09 22-09-2011 Check done! 17:47:47 22-09-2011 Check done! I ran a script that appended to a file the date and "Check done!" - this was without a loop and sleep and that is what I got. A: If you use set_time_limit(0);, the code will never time out and run forever unless it exits first. For instance I write programs in PHP in a while(1) { ... } loop. It ran for about two weeks straight (then I had to restart my computer for some unrelated reason). Cron is usually accurate though. If your host's cron is so out of sync, you should contact them and ask about it - that's not normal. EDIT: Also, you might want to consider running it forever and start it manually, then having a cron task that checks if it's still running, and restart it if it isn't. A: would set_time_limit (86400); work? Yes. But don't do that if you run your script through a web server, this would occupy a connection during this whole time.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: What makes admin button pop up on open graph? I have an open graph page: http://www.pmctool.com/pmc-extravaganza.php I have my fb_userID in the fb_admin og meta tag, but it never shows me the Admin button for the page. I created other pages with the same code, and I have an admin button that shows up, but this page I cannot get it to work. What am I doing wrong? A: Not doing it in the correct order. * *"unlike" the page *run through the linter (just to be sure the page is rescraped by facebook) http://developers.facebook.com/tools/debug *F5 - refresh the page *"like" the page *F5 - refresh *You should now see the admin link! If that doesn't work. Rerun the linter and wait 10-15 minutes to make sure the information propogates in facebook's servers, then redo the above steps (skipping #2) If fb_admins has your userID, all should go well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can PHP GD create image effects similar to fxCamera? I wonder whether PHP GD can produce these kinds of effect like those found in android's fxCamera * *ToyCam *Polandroid *Fisheye *Warhol
{ "language": "en", "url": "https://stackoverflow.com/questions/7518441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: x86 simple mov instruction This is a simple question but I can't find reliable answers on google. What does this instruction mean: movl %eax, (%esi, %ecx, 4) Is it move the value at register eax to the value in memory that (%esi, %ecx, 4) is pointing too? (%esi, %ecx, 4) is for an array. So it means Array[Xs + 4i] where Xs is the starting point in memory for the Array and i is just an offset in the integer array. A: Exactly correct. This is AT&T syntax, so the source comes first, then the destination. Thus, it stores the contents of the eax register to the memory location esi + 4*ecx. If you like to think of this as an array, it stores eax to the ecxth entry of an array of 4-byte objects based at esi. A: Yes, that's exactly what it is. In AT&T syntax, memory addressing is written as: offset(base, index, multiplier) offset is a signed constant specifying the offset from base, base is a register of where to start at, index is the register specifying how far after the start of the array to look, after multiplying by multiplier, which can be 1, 2, 4, or 8. You must specify at least one of offset, base, and index. To use index without base, you need to precede it with a comma ( (, index) ). If you don't specify multiplier, it defaults to 1. In Intel syntax, this is written as: [base + index*multiplier + offset] This is easier to understand, since it is simply a math problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }