text
stringlengths
8
267k
meta
dict
Q: How to align an element always center in div without giving width to its parent div? I am trying to align a element center in a div where i am not giving any width to parent div becouse it will spread according to screen size , there is total 3 element in div : * *Buttons *Heading *Logo buttons will always align left and logo will align right whenever screen size will be change and the heading will always align center like this My code is here http://jsfiddle.net/7AE7J/1/ please let me know where i am going wrong and what css i should apply for getting the element (heading) align center always. HTML <div id="header"> <div id="buttons"> <a href="#" class="button_back">link 1</a> <a href="#" class="button_back">link 2</a> </div> <h1>Heading of the page</h1> <div id="logo"> <a href="#"> <img src="http://lorempixum.com/60/60" width="178" height="31" alt="logo" /> </a> </div> </div> CSS #header { background:green; height:44px; width:100% } #buttons { float: left; margin-top: 7px; } #buttons a { display: block; font-size: 13px; font-weight: bold; height: 30px; text-decoration: none; color:blue; float:left} #buttons a.button_back { margin-left: 8px; padding-left:10px; padding-top: 8px; padding-right:15px } #header h1 { color: #EEEEEE; font-size: 21px; padding-top: 9px ; margin:0 auto} #logo { float: right; padding-top: 9px; } A: You can use inline-block for this: #header { text-align: center; } #header h1 { display: inline-block; } A: How about this: #header { position: relative; text-align: center; } #header h1 { display: inline; } #header #buttons { position: absolute; left: 0; top: 0; } #header #logo { position: absolute; right: 0; top: 0; } display: inline is actually a bit more cross-browser than display: inline-block; A: Try .centered { margin: 0 auto; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multicolumn combobox just like a combobox in winforms i have developed a user control for winforms in C#.Net framework 3.5, it is multi-column combo, named 'DataCombo'. i have created it with the help of Textbox and DataGridView, it looks like a combobox, and also behave as it, cursor jump on textbox list will appeared, the only difference is, that combobox provides only one column, and in this 'datacombo' we can show more than one column, and we can provide facility like sorting (just like a explorer), filter, column re-ordering etc. this is very useful component to me. my problem is that, when i put this control to a frame or groupbox or any container control, and my list size is more than container's size, than list will cut off as container size, i want this component should behave like a combobox when we put a combobox and its list size goes to out of container, although the list appears correctly any suggestion how could it do this i want some like this A: Turn off the visibility of dataGridView in UserControl and set following properties of UserControl in design mode. * *AutoSize=True *AutoSizeMode-GrowAndShrink
{ "language": "en", "url": "https://stackoverflow.com/questions/7537760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redcarpet/Bluecloth not allowing headers? Is there a way to use either Redcarpet or Bluecloth such that when it interpolates the markdown it won't make any headers? For example: #header 1 yields: header 1 header 1 (preferred) And: ##header 2 yields: header 2 header 2 (preferred) A: Well, you can escape characters in Markdown: # header 1 \# header 1 ## header 2 \## header 2 ...gives: header 1 # header 1 header 2 ## header 2 If you don't want to have to do this, or you're parsing other people's Markdown and don't have a choice, I would recommend pre-processing the incoming Markdown to do the above for you: def pound_filter text text.gsub /^#/, '\#' end Using Redcarpet you can verify that it works: text = <<-END # Hello ## World END Markdown.new(text.to_html) # => <h1>Hello</h1> # # <h2>World</h2> Markdown.new(pound_filter text).to_html # => <p># Hello # ## World</p> Of course since a line break in HTML doesn't actually render as such--it will appear as one line: # Hello ## World" ...you might want to augment that: def pound_filter text text.gsub( /((\A^)|([^\A]^))#/ ) {|match| "\n" == match[0] ? "\n\n\\#" : '\#' } end pound_filter text # => \# Hello # # \## World Markdown.new(pound_filter text).to_html # => <p>\# Hello</p> # # <p>\## World</p> This last would appear as: # Hello ## World Unfortunately you eventually get into weird territory like this, where a heading is inside a quote: > ## Heading ...but I leave that as an exercise to the reader. A: Saw a similar solution here that went like this: class RenderWithoutWrap < Redcarpet::Render::HTML def postprocess(full_document) Regexp.new(/\A<p>(.*)<\/p>\Z/m).match(full_document)[1] rescue full_document end end It removes all <p> & </p> tags. I used it like that and it worked. I placed that class in a new file called /config/initializers/render_without_wrap.rb. You could do something similar for all <h1>-<h6> tags class RenderWithoutHeaders < Redcarpet::Render::HTML def postprocess(full_document) Regexp.new(/\A<h1>(.*)<\/h1>\Z/m).match(full_document)[1] rescue full_document Regexp.new(/\A<h2>(.*)<\/h2>\Z/m).match(full_document)[1] rescue full_document Regexp.new(/\A<h3>(.*)<\/h3>\Z/m).match(full_document)[1] rescue full_document ...(you get the idea) end end You could then use it like this def custom_markdown_parse(text) markdown = Redcarpet::Markdown.new(RenderWithoutHeaders.new( filter_html: true, hard_wrap: true, other_options: its_your_call )) markdown.render(text).html_safe end I haven't tested it, but it's an idea. A: 1. You should be able to escape your markdown source text with backslashes: \# not a header 2. You could also monkey-patch it: module RedCloth::Formatters::HTML [:h1, :h2, :h3, :h4, :h5, :h6].each do |m| define_method(m) do |opts| "#{opts[:text]}\n" end end end A: Given that twiddling the Markdown pre-parsing is hard, and Markdown allows inserted HTML, how about stripping out heading elements from the resulting HTML instead?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: automatically move the focus of next text field if the length of the text field is equal to max range hi i have to text fields i want to move the focus from first text field to another textfield automatically for this i am using the following code - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { BOOL isValid = YES; NSInteger insertDelta = string.length - range.length; if (textField.tag == 0) { if (textField.text.length + insertDelta >= 8) { [txtRxStoreNumber becomeFirstResponder]; if (txtRxStoreNumber.text.length >= 5) { isValid = NO; } } }else if (textField.tag == 1) { if (textField.text.length + insertDelta > 5) { isValid = NO; } else if(textField.text.length + insertDelta == 0) { textField.text = @""; [txtRxItemNumber becomeFirstResponder]; isValid = NO; } } return isValid; } the first textfield max range is 7 . it is working but the problem is after entering the 8th character only the cursor focus moving to second text field. if only 7 characters are entered the focus of cursor is in first text field only. after entering the 7th character i want to move to focus of cursor to second text field . can any one please help me how to do that. A: the first textfield max range is 7 but: if (textField.text.length + insertDelta >= 8) So I would sugest to change the above line to >= 7
{ "language": "en", "url": "https://stackoverflow.com/questions/7537765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run my game for different screen resolution using andengine I am developing a game using andeninge. I fixed camera width and height private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; @Override public Engine onLoadEngine(){ this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new FillResolutionPolicy(), this.mCamera).setNeedsSound(true)); return engine; } In game the image of building size is (1020x400). The building view correctly when camera_widhth and camera_height is 480 ,320. How to run my game for different screen resolution using andengine (Using same building image size). Otherwise i need to change building images for all screen resolution ? A: You can use fixed camera, like you do now, if you want to. OpenGL ES will scale the view to fill the device screen. This is probably the easiest solution but it will either change the aspect ratio or leave black boxes below/above or left/right of your screen when the game is run on device that has different aspect ratio than 1.5 (480/320). I think currently most devices have 1.66 aspect ratio (800/480). Other option is to use: DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics) CAMERA_WIDTH = metrics.widthPixels() CAMERA_HEIGHT = metrics.heightPixels() to set your camera size and then use combination of the pixel sizes and the screens pixel density (dpi) (see http://developer.android.com/reference/android/util/DisplayMetrics.html) and the use .setScale to your Sprites to scale them accordingly. A: Andengine games will scale onto the device natively - so... If you set your CAMERA_WIDTH/HEIGHT to 480x320 and someone runs it on a phone which is 800x480 your game will be scaled-up to 720x480 (1.5x) and there will be an 80px margin (top, bottom, left, right or split between them depending on your View's gravity). You have to decide what most of the people using your App will be using - I tend to target 800x480 and live with some shrinkage to smaller screens - rather than the other way around... A: You can use this Source : @Override public Engine onLoadEngine() { final Display defaultDisplay = getWindow().getWindowManager().getDefaultDisplay(); CAMERA_WIDTH = defaultDisplay.getWidth(); CAMERA_HEIGHT = defaultDisplay.getHeight(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.PORTRAIT, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } A: AndEngine by default assumes that you want a fixed resolution policy. But you can also change it, as given in the following link, http://android.kul.is/2013/10/andengine-tutorial-dealing-with-screen-sizes.html Or, you can follow this code and modify your code accordingly. (My preference) // Calculate the aspect ratio ofthe device. float aspectRatio = (float) displayMetrics.widthPixels / (float) displayMetrics.heightPixels; // Multiply the aspect ratio by the fixed height. float cameraWidth = Math.round(aspectRatio * CAMERA_HEIGHT); // Create the camera using those values. this.mCamera = new Camera(0, 0, cameraWidth, cameraHeight); // Pick some value for your height. float cameraHeight = 320; // Get the display metrics object. final DisplayMetrics displayMetrics = new DisplayMetrics(); // Populate it with data about your display. this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
{ "language": "en", "url": "https://stackoverflow.com/questions/7537771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Table border-collapse: mixing settings I'd like to have a group of table entries using the collapse setting but to have it separate from other groups. Do I have to make a new table for each of these "zones"? I tried that and they don't line up. And they don't collapse together the right way when I just apply border-collapse on the th and td in my CSS. Ascii art time. <!-- table with two rows two columns with first one having colspan=2: --> β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β” | abcd β”‚ β”œβ”€β”€β”€β”¬β”€β”€β”€β”€β”€ | a | bc | β””β”€β”€β”€β”΄β”€β”€β”€β”€β”˜ <!-- Same table, separate looks like this (but more squished because there arent enough unicode table characters for this) --> β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β” | abcd β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ <-- this bit is squished together β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β” | a || bc | β””β”€β”€β”€β”˜β””β”€β”€β”€β”€β”˜ And what I want is something like this where I've got arbitrary control of whether they get collapsed or not: <!-- this table is made of two rows. two <td colspan=2> in the first row. four <td> in the second row. The third and fourth ones are to be separate. The rest collapse their borders. --> β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” | abcd β”‚ efg | β”œβ”€β”€β”€β”¬β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ <--- again, here the hh and ijk borders should be separate but rising to fill that space | | |β”Œβ”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β” | a | bc ||hh|| ijk | | | |β””β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”΄β”€β”€β”€β”€β”˜ where you can see that I've got hh and ijk as clearly separate, but the rest are collapsed together. The problem with putting them into zones which are their own tables, is that the tables no longer share alignments. It makes things not line up in the table any more (how could I expect it to?) but it is a deal-breaker because my data will no longer be organized. A: I'm pretty sure that isn't possible with a table. Someone correct me if I'm wrong. I've tried using margin: and cellspacing= but they both don't work properly. A: I think your best bet is to use a second table. Then you would need to remove some borders and use border-collapse:separate; and border-spacing table{ border-collapse:collapse; } td{ padding:1em; border:1px solid red; border-collapse:collapse; } td.no_border{ border-bottom:0; border-right:0; padding:0; } table.separate{ border-collapse:separate; border-spacing:5px; } table.separate td{ border-collapse:separate; padding:1em; border-spacing:5px; } Working Example: http://jsfiddle.net/jasongennaro/k2cN5/
{ "language": "en", "url": "https://stackoverflow.com/questions/7537772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Splitting, enriching and putting back together I have a message carrying XML (an order) containing multiple homogenous nodes (think a list of products) in addition to other info (think address, customer details, etc.). I have to enrich each 'product' with details provided by another external service and return the same complete XML 'order' message with enriched 'products'. I came up with this sequence of steps: * *Split the original XML with xpath to separate messages (also keeping the original message) *Enrich split messages with additional data *Put enriched parts back into the original message by replacing old elements. I was trying to use multicast by sending original message to endpoint where splitting and enriching is done and to aggregation endpoint where original message and split-enriched messages are aggregates and then passed to processor which is responsible for combining these parts back to single xml file. But I couldn't get the desired effect... What would be the correct and nice way to solve this problem? A: The Splitter EIP in Camel can aggregate messages back (as a Composed Message Processor EIP). http://camel.apache.org/splitter See this video which demonstrates such a use-case http://davsclaus.blogspot.com/2011/09/video-using-splitter-eip-and-aggregate.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7537776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Prevent scrolling to top when using jQuery .load I have three buttons on the site and when you click each one, they use .load to add different things to a DIV. The problem I'm having is whenever you click a button, it sends you back to the top of the page. I've tried using preventDefault() and return false but it didn't work for me, I might have just placed it in the wrong spot. You can see the problem at http://coralspringshigh.org/cshs/ , here's the jQuery that I have now: if($(tabsId).length > 0){ loadTab($(tabsId)); } $(tabsId).click(function(){ if($(this).hasClass(selected)){ return false; } $(tabsId).removeClass(selected); $(this).addClass(selected); $(containerId).hide(); loadTab($(this)); $(containerId).fadeIn(); return false; }); function loadTab(tabObj){ if(!tabObj || !tabObj.length){ return; } $(containerId).addClass('loading'); $(containerId).load(tabObj.attr('href'), function(){ $(containerId).removeClass('loading'); $(containerId).fadeIn('fast'); }); } Thank you in advance. A: Your Issue When you are loading the content, you are hiding the previous content, which is shortening your page. So, your page is not scrolling up, but your page is becoming shorter, and your browser is re-aligning to the new bottom of the page. This is what is causing the behavior you are seeing. The Solution(s) To solve this problem, there are a few things you can do. My recommendation is to load the content in the background, and display a loading overlay that goes over the old content. Then, when the new content is loaded, swap it out by hiding the old content after you show the new content. The user won't see a difference since it will happen quickly, but you not get that 'scroll' effect. Another way to solve it is to use the jQuery .scrollTo() function to scroll to the new content after it is loaded, so that the content goes to the top of the page (or as high as the page can be). Addendum Your HTML is not completely valid. The <div> element cannot have an href attribute. Instead, wrap your text in an <a> tag to make it valid. <div class="classname"><a href="page.html" class="ajaxclicklink">Students</a></div> and from there, your code should do a event.preventDefault(); event.stopPropagation(); This will stop the default linking, and also allow the use of a browser that does not support javascript. It is a good practice (and more symatically correct, imo) to have full working links instead of just javascript faked links. A: After an year and for future problems, the best solution is use fadeTo() instead fadeIn()
{ "language": "en", "url": "https://stackoverflow.com/questions/7537777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: break from asynchronous task android I would like to stop my asynchronous thread on back click of user. Could you please suggest if there is any way to stop asynchronous thread in android. Please forward your suggestions. A: If you're talking about AsyncTask then you can call its cancel() method. If you pass true to this method and the task is waiting on some object or I/O operation then the waiting will be interrupted and the task will be cancelled. But if you pass false to this method or the task is not waiting (e.g. performing some calculations) then it will not be cancelled. In this case you can call isCancelled() method from doInBackground() and finish calculations when isCancelled() returns true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to differentiate between programmatically scrolling list view and manually doing so? I need to differentiate between programmatically scrolling a list view and manually scrolling a list view. I am not quite sure how to do it. Any idea ? Thanks. A: I guess a way would be to do something like add onscrollchanged listener and onTouch listener to the listview. And keep a boolean like fromUser. In the onTouch listener you can set the flag to true on MotionEvent.ActionDown. When the MotionEvent is ActionUp you can set the flag to false. So whenever the scroll listener is fired you can check the flag and see whether its from the user or not.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to fadeIn an image using tag instead of a using jQuery? I'm trying out some jQuery for the first time. My first goal is for one image on the page to fade into a different image. I've figured out how to do this with a couple of divs that have background-image set to the different image files (see code below). However, this would work better for my situation if I was somehow doing this to an existing img tag instead of using some divs. Is there any way to do what this code does, but with the img tag? <html> <head> <script type="text/javascript" src="jquery-1.6.4.js"></script> <script type="text/javascript"> $(function() { $("#imgblock2").delay(3000).fadeIn(3000); }); </script> <style type="text/css"> #imgblock { background-image:url("frame.jpg"); width:240; height:320; position:absolute; top:0; left:0; } #imgblock2 { background-image:url("average.jpg"); width:240; height:320; position:absolute; top:0; left:0; display:none; } </style> </head> <body> <div id="imgblock"></div> <div id="imgblock2"></div> </body> </html> A: Yes, Use actual images instead of divs. you an give the images id's as well. A: Have a container div that includes both images and set its position to relative. After that you can put both images inside that div and give them id's, be sure to set their position to absolute so that they are layered on top of each other. A: This is not that hard ;) $(document).ready(function() { var relatedImg = $("#imgblock"); relatedImg.css("display", "none"); relatedImg.fadeIn("slow", function(){ relatedImg.fadeOut("slow", function(){ relatedImg.attr("src", "http://farm6.static.flickr.com/5221/5592275221_8190eb9b9c.jpg"); relatedImg.fadeIn("slow"); }); }); }); Explanation At first, we set the display property to "none" via javascript (so customers without would just see the image) after the fadeIn we fadeOut our image and change the image src with the attr function.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I get a part of the URL to be assigned to a string? the url on my local project is :- http://localhost/mysite/KB/Type-1/General-Article and on server it is:- http://www.mysite.com/KB/Type-1/General-Article from both the urls, I want to fetch the URL part until Type-1 without slash ie from localhost website address, I want:- http://localhost/mysite/KB/Type-1 and from server, I want :- http://www.mysite.com/KB/Type-1 How can I do this? Please help ..thanks Please note that Type-1 is not a fixed, it wcan change. It can be anything like "Type-2", "User-Articles", etc. Thanks for the answers but will this still work if there is a slash at the end of the URL too? like this:- http://www.mysite.com/KB/Type-1/General-Article/ Please note that the text "KB" in the URL is FIXED. A: try this code, url.Substring(0, url.LastIndexOf("/")-1); edit: if you have ending slash, you can use following code url=url.Remove(test1.Length - 1); url.Substring(0, url.LastIndexOf("/")-1); A: since you don't provide enough information only some general idea: EDIT 2 - as per comments: string MySubURL = MyURL.SubString ( 0, MyURL.TrimEnd(null).TrimEnd(new char[]{'/'}).LastIndexOf ("/") ); A: This will do what you want whether there is a '/' at the end or not in a single line. It is a bit longer, but it works for all of your outlined requirements. string url = "http://www.mysite.com/KB/Type-1/General-Article"; string seg = url.EndsWith("/") ? url.Substring(0, url.TrimEnd('/').LastIndexOf('/')) : url.Substring(0, url.LastIndexOf('/'));
{ "language": "en", "url": "https://stackoverflow.com/questions/7537790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Understanding Recursion to generate permutations I find recursion, apart from very straight forward ones like factorial, very difficult to understand. The following snippet prints all permutations of a string. Can anyone help me understand it. What is the way to go about to understand recursion properly. void permute(char a[], int i, int n) { int j; if (i == n) cout << a << endl; else { for (j = i; j <= n; j++) { swap(a[i], a[j]); permute(a, i+1, n); swap(a[i], a[j]); } } } int main() { char a[] = "ABCD"; permute(a, 0, 3); getchar(); return 0; } A: PaulR has the right suggestion. You have to run through the code by "hand" (using whatever tools you want - debuggers, paper, logging function calls and variables at certain points) until you understand it. For an explanation of the code I'll refer you to quasiverse's excellent answer. Perhaps this visualization of the call graph with a slightly smaller string makes it more obvious how it works: The graph was made with graphviz. // x.dot // dot x.dot -Tpng -o x.png digraph x { rankdir=LR size="16,10" node [label="permute(\"ABC\", 0, 2)"] n0; node [label="permute(\"ABC\", 1, 2)"] n1; node [label="permute(\"ABC\", 2, 2)"] n2; node [label="permute(\"ACB\", 2, 2)"] n3; node [label="permute(\"BAC\", 1, 2)"] n4; node [label="permute(\"BAC\", 2, 2)"] n5; node [label="permute(\"BCA\", 2, 2)"] n6; node [label="permute(\"CBA\", 1, 2)"] n7; node [label="permute(\"CBA\", 2, 2)"] n8; node [label="permute(\"CAB\", 2, 2)"] n9; n0 -> n1 [label="swap(0, 0)"]; n0 -> n4 [label="swap(0, 1)"]; n0 -> n7 [label="swap(0, 2)"]; n1 -> n2 [label="swap(1, 1)"]; n1 -> n3 [label="swap(1, 2)"]; n4 -> n5 [label="swap(1, 1)"]; n4 -> n6 [label="swap(1, 2)"]; n7 -> n8 [label="swap(1, 1)"]; n7 -> n9 [label="swap(1, 2)"]; } A: Though it is little old question and already answered thought of adding my inputs to help new visitors. Also planning to explain the running time without focusing on Recursive Reconciliation. I have written the sample in C# but easy to understand for most of the programmers. static int noOfFunctionCalls = 0; static int noOfCharDisplayCalls = 0; static int noOfBaseCaseCalls = 0; static int noOfRecursiveCaseCalls = 0; static int noOfSwapCalls = 0; static int noOfForLoopCalls = 0; static string Permute(char[] elementsList, int currentIndex) { ++noOfFunctionCalls; if (currentIndex == elementsList.Length) { ++noOfBaseCaseCalls; foreach (char element in elementsList) { ++noOfCharDisplayCalls; strBldr.Append(" " + element); } strBldr.AppendLine(""); } else { ++noOfRecursiveCaseCalls; for (int lpIndex = currentIndex; lpIndex < elementsList.Length; lpIndex++) { ++noOfForLoopCalls; if (lpIndex != currentIndex) { ++noOfSwapCalls; Swap(ref elementsList[currentIndex], ref elementsList[lpIndex]); } Permute(elementsList, (currentIndex + 1)); if (lpIndex != currentIndex) { Swap(ref elementsList[currentIndex], ref elementsList[lpIndex]); } } } return strBldr.ToString(); } static void Swap(ref char Char1, ref char Char2) { char tempElement = Char1; Char1 = Char2; Char2 = tempElement; } public static void StringPermutationsTest() { strBldr = new StringBuilder(); Debug.Flush(); noOfFunctionCalls = 0; noOfCharDisplayCalls = 0; noOfBaseCaseCalls = 0; noOfRecursiveCaseCalls = 0; noOfSwapCalls = 0; noOfForLoopCalls = 0; //string resultString = Permute("A".ToCharArray(), 0); //string resultString = Permute("AB".ToCharArray(), 0); string resultString = Permute("ABC".ToCharArray(), 0); //string resultString = Permute("ABCD".ToCharArray(), 0); //string resultString = Permute("ABCDE".ToCharArray(), 0); resultString += "\nNo of Function Calls : " + noOfFunctionCalls; resultString += "\nNo of Base Case Calls : " + noOfBaseCaseCalls; resultString += "\nNo of General Case Calls : " + noOfRecursiveCaseCalls; resultString += "\nNo of For Loop Calls : " + noOfForLoopCalls; resultString += "\nNo of Char Display Calls : " + noOfCharDisplayCalls; resultString += "\nNo of Swap Calls : " + noOfSwapCalls; Debug.WriteLine(resultString); MessageBox.Show(resultString); } Steps: For e.g. when we pass input as "ABC". * *Permutations method called from Main for first time. So calling with Index 0 and that is first call. *In the else part in for loop we are repeating from 0 to 2 making 1 call each time. *Under each loop we are recursively calling with LpCnt + 1. 4.1 When index is 1 then 2 recursive calls. 4.2 When index is 2 then 1 recursive calls. So from point 2 to 4.2 total calls are 5 for each loop and total is 15 calls + main entry call = 16. Each time loopCnt is 3 then if condition gets executed. From the diagram we can see loop count becoming 3 total 6 times i.e. Factorial value of 3 i.e. Input "ABC" length. If statement's for loop repeats 'n' times to display chars from the example "ABC" i.e. 3. Total 6 times (Factorial times) we enter into if to display the permutations. So the total running time = n X n!. I have given some static CallCnt variables and the table to understand each line execution in detail. Experts, feel free to edit my answer or comment if any of my details are not clear or incorrect, I am happy correct them. Download the sample code and other samples from here A: To use recursion effectively in design, you solve the problem by assuming you've already solved it. The mental springboard for the current problem is "if I could calculate the permutations of n-1 characters, then I could calculate the permutations of n characters by choosing each one in turn and appending the permutations of the remaining n-1 characters, which I'm pretending I already know how to do". Then you need a way to do what's called "bottoming out" the recursion. Since each new sub-problem is smaller than the last, perhaps you'll eventually get to a sub-sub-problem that you REALLY know how to solve. In this case, you already know all the permutations of ONE character - it's just the character. So you know how to solve it for n=1 and for every number that's one more than a number you can solve it for, and you're done. This is very closely related to something called mathematical induction. A: It chooses each character from all the possible characters left: void permute(char a[], int i, int n) { int j; if (i == n) // If we've chosen all the characters then: cout << a << endl; // we're done, so output it else { for (j = i; j <= n; j++) // Otherwise, we've chosen characters a[0] to a[j-1] { // so let's try all possible characters for a[j] swap(a[i], a[j]); // Choose which one out of a[j] to a[n] you will choose permute(a, i+1, n); // Choose the remaining letters swap(a[i], a[j]); // Undo the previous swap so we can choose the next possibility for a[j] } } } A: Think about the recursion as simply a number of levels. At each level, you are running a piece of code, here you are running a for loop n-i times at each level. this window gets decreasing at each level. n-i times, n-(i+1) times, n-(i+2) times,..2,1,0 times. With respect to string manipulation and permutation, think of the string as simply a 'set' of chars. "abcd" as {'a', 'b', 'c', 'd'}. Permutation is rearranging these 4 items in all possible ways. Or as choosing 4 items out of these 4 items in different ways. In permutations the order does matter. abcd is different from acbd. we have to generate both. The recursive code provided by you exactly does that. In my string above "abcd", your recursive code runs 4 iterations (levels). In the first iteration you have 4 elements to choose from. second iteration, you have 3 elements to choose from, third 2 elements, and so on. so your code runs 4! calculations. This is explained below First iteration: choose a char from {a,b,c,d} Second Iteration: choose a char from subtracted set {{a,b,c,d} - {x}} where x is the char chosen from first iteration. i.e. if 'a' has been choose in first iteration, this iteration has {b,c,d} to choose from. Third Iteration: choose a char from subtracted set {{a,b,c,d} - {x,y}} where x and y are chosen chars from previous iterations. i.e. if 'a' is chosen at first iteration, and 'c' is chosen from 2nd, we have {b,d} to play with here. This repeats until we choose 4 chars overall. Once we choose 4 possible char, we print the chars. Then backtrack and choose a different char from the possible set. i.e. when backtrack to Third iteration, we choose next from possible set {b,d}. This way we are generating all possible permutations of the given string. We are doing this set manipulations so that we are not selecting the same chars twice. i.e. abcc, abbc, abbd,bbbb are invalid. The swap statement in your code does this set construction. It splits the string into two sets free set to choose from used set that are already used. All chars on left side of i+1 is used set and right are free set. In first iteration, you are choosing among {a,b,c,d} and then passing {a}:{b,c,d} to next iteration. The next iteration chooses one of {b,c,d} and passes {a,b}:{c,d} to next iteration, and so on. When the control backtracks back to this iteration, you will then choose c and construct {a,c}, {b,d} using swapping. That's the concept. Otherwise, the recursion is simple here running n deep and each level running a loop for n, n-1, n-2, n-3...2,1 times. A: This code and reference might help you to understand it. // C program to print all permutations with duplicates allowed #include <stdio.h> #include <string.h> /* Function to swap values at two pointers */ void swap(char *x, char *y) { char temp; temp = *x; *x = *y; *y = temp; } /* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */ void permute(char *a, int l, int r) { int i; if (l == r) printf("%s\n", a); else { for (i = l; i <= r; i++) { swap((a+l), (a+i)); permute(a, l+1, r); swap((a+l), (a+i)); //backtrack } } } /* Driver program to test above functions */ int main() { char str[] = "ABC"; int n = strlen(str); permute(str, 0, n-1); return 0; } Reference: Geeksforgeeks.org
{ "language": "en", "url": "https://stackoverflow.com/questions/7537791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "53" }
Q: Interface Builder: determine which element has the initial focus I have a Cocoa app with a table view and a few other controls. When the app launches and the window is shown, a blue focus ring is drawn around the table view. How can I get rid of that focus ring? I'd like nothing to have the focus when the window first shows. A: The window has initialFirstResponder binding that shows which control will be active when the window becomes active. Change the initialFirstResponder or adjust tableview settings in interface builder to hide the focus ring A: The best way I've found of stopping any of the controls from being the first responder when a window is first displayed is in the window controller: Swift 3: class YourWindowController: NSWindowController { override func windowDidLoad() { super.windowDidLoad() // Wait a frame before setting the first responder to be the window itself. // We can't just set it right now, because if the first responder is set // to the window now the system just interprets that as meaning that we // want the default behavior where it automatically selects a view to be // the first responder. DispatchQueue.main.async { window!.makeFirstResponder(nil) } } } It's messy, and sometimes when the window loads you see the focus ring starting to appear on one of the controls for one frame, but I haven't found a better way yet.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: three20 actively developed Is three20 still actively being developed? From the three20.info site, I see no new features/UI elements since earlier this year when I looked into it. Besides three20, is there another good framework out there? A: As far as i know, Three20 is only maintained by community (bug fixes). Jeff left the project and decided to clean up that mess & provide solid documentation. He recently started a new project on github called Nimbus, his plan is to port all features of Three20 to Nimbus without the problems we face today with Three20. A: I haven't given up on three20 yet. It's a good framework and it saves me hours of work. I'm submitting bug fixes and small improvements to the framework from time to time and I see some activity in github. (not as much as it used to be) I tried using nimbus, and I was really impressed with the documentation and existing classes. However, note that the developer went to work in CA and said he'll contribute less to his new framework. The three20.info site is not maintained, but you can download the latest version from github.com/facebook/three20.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: StringBuilder Class OutOfMemoryException I have written following function public void TestSB() { string str = "The quick brown fox jumps over the lazy dog."; StringBuilder sb = new StringBuilder(); int j = 0; int len = 0; try { for (int i = 0; i < (10000000 * 2); i++) { j = i; len = sb.Length; sb.Append(str); } Console.WriteLine("Success ::" + sb.Length.ToString()); } catch (Exception ex) { Console.WriteLine( ex.Message + " :: " + j.ToString() + " :: " + len.ToString()); } } Now I suppose, that StringBuilder has the capacity to take over 2 billion character (2,147,483,647 to be precise). But when I ran the above function it gave System.OutOfMemoryException just on reaching the capacity of about 800 million. Moreover, I am seeing widely different result on different PC having same memory and similar amount of load. Can anyone please provide or explain me the reason for this? A: Each character requires 2 bytes (as a char in .NET is a UTF-16 code unit). So by the time you've reached 800 million characters, that's 1.6GB of contiguous memory required1. Now when the StringBuilder needs to resize itself, it has to create another array of the new size (which I believe tries to double the capacity) - which means trying to allocate a 3.2GB array. I believe that the CLR (even on 64-bit systems) can't allocate a single object of more than 2GB in size. (That certainly used to be the case.) My guess is that your StringBuilder is trying to double in size, and blowing that limit. You may be able to get a little higher by constructing the StringBuilder with a specific capacity - a capacity of around a billion may be feasible. In the normal course of things this isn't a problem, of course - even strings requiring hundreds of megs are rare. 1 I believe the implementation of StringBuilder actually changed in .NET 4 to use fragments in some situations - but I don't know the details. So it may not always need contiguous memory while still in builder form... but it would if you ever called ToString.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "25" }
Q: paypal ipn problem, url malformed (sandbox works, paypal doesn't) I have an IPN file that works perfectly in sandbox. It returns valid or not and executes the code correctly. However if I try real live payments it tells me the url is malformed This is the error with live payments: bool(false) string(15) " malformed" this is the curl code I have: if($testmode === true) { $paypalaction = "https://www.sandbox.paypal.com/cgi-bin/webscr"; } elseif($paypal == "paypal") { $paypalaction = "https://www.paypal.com/cgi-bin/webscr"; } // read the post from PayPal system and add 'cmd' $req = 'cmd=_notify-validate'; foreach ($_POST as $key => $value) { // If magic quotes is enabled strip slashes if (get_magic_quotes_gpc()) { $_POST[$key] = stripslashes($value); $value = stripslashes($value); } $value = urlencode($value); // Add the value to the request parameter $req .= "&$key=$value"; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$paypalaction); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT, 3); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $req); $res = curl_exec($ch); var_dump($res); var_dump(curl_error($ch)); curl_close($ch); A: It sounds like you may be posting sandbox transactions to the live URL or the other way around. Make sure that when you try a live transaction, you are doing so with a real, live PayPal account. Double-check your code to ensure that your test for which PayPal URL is working correctly. A: The problem wasn't with paypal or sandbox but just me being stupid. i had the following if statement: if($testmode === true) { $paypalaction = "https://www.sandbox.paypal.com/cgi-bin/webscr"; } elseif($paypal == "paypal") { $paypalaction = "https://www.paypal.com/cgi-bin/webscr"; } But the $paypal variable wasn't used anymore so it never entered the elseif statement. I should have been only an if else: if($testmode === true) { $paypalaction = "https://www.sandbox.paypal.com/cgi-bin/webscr"; } else { $paypalaction = "https://www.paypal.com/cgi-bin/webscr"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pull data in the Map/Reduce functions? According to the Hadoop : The Definitive Guide. The new API supports both a β€œpush” and a β€œpull” style of iteration. In both APIs, key-value record pairs are pushed to the mapper, but in addition, the new API allows a mapper to pull records from within the map() method. The same goes for the reducer. An example of how the β€œpull” style can be useful is processing records in batches, rather than one by one. Has anyone pulled data in the Map/Reduce functions? I am interested in the API or example for the same. A: I posted a query @ mapreduce-user@hadoop.apache.org and got the answer. The next key value pair can be retrieved from the context object which is passed to the map, by calling nextKeyValue() on it. So you will be able to pull the next data from it in the new API. Is the performance of pull better than push in this scenario? Also, what are the scenarios in which the pull will be useful?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Setuptools / distutils: Installing files into the distribution's DLLs directory on Windows I'm writing a setup.py which uses setuptools/distutils to install a python package I wrote. It need to install two DLL files (actually a DLL file and a PYD file) into location which is available for python to load. Thought this is the DLLs directory under the installation directory on my python distribution (e.g. c:\Python27\DLLs). I've used data_files option to install those files and all work when using pip: data_files=[(sys.prefix + "/DLLs", ["Win32/file1.pyd", "Win32/file2.dll"])] But using easy_install I get the following error: error: Setup script exited with error: SandboxViolation: open('G:\\Python27\\DLLs\\file1.pyd', 'wb') {} The package setup script has attempted to modify files on your system that are not within the EasyInstall build area, and has been aborted. So, what's the right way to install those files? A: I was able to solve this issue by doing the following changes: 1. All data_files path changed to be relative data_files=["myhome", ["Win32/file1.pyd", "Win32/file2.dll"])] 2. I try to find the location of "myhome" in the package init file so I'll be able to use them. This require some nasty code, because they are either under current Python's root directory or under an egg directory dedicated to the package. So I just look where a directory exits. POSSIBLE_HOME_PATH = [ os.path.join(os.path.dirname(__file__), '../myhome'), os.path.join(sys.prefix, 'myhome'), ] for p in POSSIBLE_HOME_PATH: myhome = p if os.path.isdir(myhome) == False: print "Could not find home at", myhome else: break 3. I then need to add this directory to the path, so my modules will be loaded from there. sys.path.append(myhome)
{ "language": "en", "url": "https://stackoverflow.com/questions/7537799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to upload files to DropBox in blackberry I want to upload files either text file or video file to Drop Box in blackberry. So how can I proceed?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: executing operation for each list element in swi-prolog and others How do I do an operation for each element of a list, in order? Based on these two resources: * *http://www.swi-prolog.org/pldoc/doc/swi/library/lists.pl *http://www.swi-prolog.org/pldoc/doc_for?object=foreach/2 I imagine I can always rely on: * *foreach(member(X, [1,2]), write(X)). Is that deterministic and can I wrap the member/2 predicate as I please in my own predicates and still always iterate in order? A: Yes, but you have to worry about your predicate failing. If it can, the remaining elements in the list will not be processed because it produces a conjunction rather than a failure-driven loop. I would be more keen to use maplist/2 since I think it is more widely used than foreach/2 but I also hadn't seen this option before. :) Edit: Let's discuss what I mean about failure-driven loops. There are two primitive iteration methods in Prolog: recursion and failure-driven loops. Say I want to print out every item in a list. The recursive method is going to look like this: print_all([]). print_all([X|Rest]) :- write(X), nl, print_all(Rest). So given a list like [1,2,3], this is going to expand like so: print_all([1,2,3]) write(1), nl, print_all([2,3]) write(1), nl, write(2), nl, print_all([3]) write(1), nl, write(2), nl, write(3), nl, print_all([]) write(1), nl, write(2), nl, write(3), nl. This is how member/2 is usually implemented: member(X, [X|_]). member(X, [_|Xs]) :- member(X, Xs). So you can see the recursive method is pretty simple and general. Another simple but somewhat frowned-upon method is to simulate a failure to engage the backtracking mechanism. This is called a failure-driven loop and looks like this: print_all(List) :- member(X, List), write(X), nl, fail. print_all(_). When you run this version of print_all/1, what happens is a little more complex than simple expansion. print_all([1,2,3]) member([1,2,3], 1) write(1), nl fail retry member([1,2,3], 2) write(2), nl fail retry member([1,2,3], 3) write(3), nl fail retry print_all(_) true Verbally, the fail forces Prolog to back up to the last choice point it made and try using the next solution. Well, write/1 and nl/0 don't produce choice points because they only have one solution, but member/2 does have multiple solutionsβ€”one for each item in the list. So Prolog takes each item out of the list and prints it. Finally when member/2 runs out of solutions, Prolog backs up to the previous choice point, which is the second body of the print_all/1 predicate, which always succeeds. So the output looks the same. I think people nowadays generally prefer not to use failure-driven loops, but I don't understand the arguments well enough to parrot them usefully. One thing that may help you to see what's going on is use the trace predicate and step through the expansion of both versions, and see if you can make sense of the differences. My notation above is completely made up for this answer and may not be as clear. Looking back over what I originally wrote and your actual question: * *foreach is going to be deterministic *member will always iterate in order, because lists are defined in such a way that you must access each item in turn Moreover, these days at least on S.O. you will get a lot of people telling you to use maplist and its ilk, so it's probably not just going to work, but also a good idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Proper way to program in Lisp? I'm new to Common Lisp, and found myself taking advantage of way functions returns values. The following are to two trivial examples: (defun safe-avg (a b) (and (numberp a) (numberp b) (/ (+ a b) 2))) (defun safe-div (a b) (and (numberp a) (numberp b) (> b 0) (/ a b))) But I could've written it like this (arguably clearer): (defun safe-avg (a b) (if (and (numberp a) (numberp b)) (/ (+ a b) 2))) (defun safe-div (a b) (if (and (numberp a) (numberp b) (> b 0)) (/ a b))) I wanted to know what is the preferred method of doing something like this and the reasoning behind it, before I start abusing this habit. A: Since you do not use the "else" branch, you could use when: (defun safe-div (a b) (when (and (numberp a) (numberp b) (> b 0)) (/ a b))) which is the same as: (defun safe-div (a b) (if (and (numberp a) (numberp b) (> b 0)) (/ a b) nil)) which is the same as your version, but more explicit. Anyway, these are all functionally equivalent. I would rather think about how these functions are to be used. If you do it like this, you will have to do null checks each time you call these functions, which is tedious. It would be better to use conditions, either through type declarations, through asserts, or through explicit when … signal forms. You can then define handlers and restarts for these conditions for entire parts of your program. Further reading: Practical Common Lisp, ch. 19. In this case, I would not handle this here at all: (defun safe-div (a b) (/ a b)) (or rather, just use /). If / gets the wrong arguments, it will signal an error which you can then handle outside, where you know what that could mean. A: The first form is idiomatically acceptable. It isn't the best example of using AND's return value effectively, since the second form is a little clearer without being any lengthier. But you shouldn't be afraid to use LISP as intended! For instance, going in an (inadvisable) direction...someone might argue that the implicit "nil return" of if statements could be confusing and try and parallel if/else structure to be more clear: (defun safe-avg (a b) (cond ((and (numberp a) (numberp b)) (/ (+ a b) 2)) (t nil))) That's bad. And you don't want to go down that road. So go ahead and use the expressions and trim the amount of code with nice evaluations, and use comments to pick up the slack to remind others (and yourself) of how it works if there's anything non-obvious about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to set different properties from objects which are returned by the Factory pattern? I was wondering on how to set properties on which objects which are returned by the concrete factory. The factory can return objectA with properties A and B, but it can also return objectB with properties X, Y, Z. Since the client only know the interface objectA and objectB inherits, it doesn't know which object he is dealing with. So, my question is, what is the OO way of setting these properties? Do I need to introduce a kind of setting class, which contains all the properties of classA and classB? But this isn't OO, because when there's a new class I have to update the setting class as well... I hope you undserstand my question and can help me out :) PS: If it matters, I am working with C# A: You can use a visitor which knows which properties to set and can assign it to the concrete class which you get (inside the factory). Now this visitor can set the desired properties in abstract way. class Factory { .. obj = new ConcreteObject(); obj.accept(new ConcreteObjectVisitor()); } class ConcreteObject{ accept(Visitor visitor){ visitor.visit(this); } } class ConcreteObjectVisitor implements Visitor { visit(ConcretTypeInterface param){ obj = (ConcretType)param; param.setA() param.setB() param.setC() } } A: If client needs to set values of properties that don't exist in common interface, it has to have some knowledge on concrete types of objects that the factory has created. There are several approaches to this: * *Client decides what kind of object it needs and calls appropriate factory operation. So for this scenario, the factory would have a different operations for creating objectA and objectB. Values of properties to be set could be passed as parameters of those operations. *Client decides what kind of object it needs and passes this decision to factory as a value of a parameter of factory method. The values themselves are passed as a single array, collection or dictionary object in another parameter. *Factory decides what class to instantiate, passes new instance to client and then client discovers the concrete class of given object (in C# via GetType() method). If concrete class is accessible to client, it can perform a cast, if not, it can set values of properties using reflection. If examples are needed, just write a comment :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7537806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sencha Touch Remote and Local Storage Combined I am trying to learn Sencha Touch and am working on an app which is helping me a lot to learn it. I have a situation where there is a News tab and it returns news from RSS using proxy of XML datatype. It works so far. I am loading those RSS at the tab activate event and there is a progress bar also shown which blocks the UI while it's retrieving news. Now assume if there is no internet and the loader will load indefinitely. How can I make my app use Remote as well as Local storage to show those news. I mean bind List control to Local storage but update Local storage with Remote call in background? I know how to bind List control to Local storage but how can I update Local storage in background with Remote call to the URL in background on List activate listener? A: You can use 'setProxy' method of the store object to change it from local to ajax. Also you can load the data in the background and then add each item to the store with it's add method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I make a vector/array of System::Windows::Forms::Checkbox^ Couldn't find any answer to this problem, or not even any questions asked. So what I'm trying to do, is a std::vector, maybe just a normal array, of Checkboxes. std::vector< System::Windows::Forms::CheckBox^ >m_items; m_items.push_back( myCheckbox ); That's what I currently have, and it clearly ain't working. So does anyone have any ideas, on how to get it working, cause I've tried everything I can, but vectors don't seem to support Checkboxes. Incase you need the error code: c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\xmemory(200): error C3699: '&&' : cannot use this indirection on type 'System::Windows::Forms::CheckBox ^' 1> c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\vector(421) : see reference to class template instantiation 'std::allocator<_Ty>' being compiled 1> with 1> [ 1> _Ty=System::Windows::Forms::CheckBox ^ 1> ] 1> c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\vector(481) : see reference to class template instantiation 'std::_Vector_val<_Ty,_Alloc>' being compiled 1> with 1> [ 1> _Ty=System::Windows::Forms::CheckBox ^, 1> _Alloc=std::allocator<System::Windows::Forms::CheckBox ^> 1> ] 1> d:\programming\vc++ projects\mahi wcs race maker\mahi wcs race maker\RestrictedItemsForm.h(69) : see reference to class template instantiation 'std::vector<_Ty>' being compiled 1> with 1> [ 1> _Ty=System::Windows::Forms::CheckBox ^ 1> ] 1>c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\vector(630): error C3699: '&&' : cannot use this indirection on type 'System::Windows::Forms::CheckBox ^' 1>c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\vector(655): error C3699: '&&' : cannot use this indirection on type 'System::Windows::Forms::CheckBox ^' 1>d:\programming\vc++ projects\mahi wcs race maker\mahi wcs race maker\RestrictedItemsForm.h(69): error C4368: cannot define 'm_items' as a member of managed 'MahiWCSRaceMaker::RestrictedItemsForm': mixed types are not supported 1>d:\programming\vc++ projects\mahi wcs race maker\mahi wcs race maker\RestrictedItemsForm.h(170): error C2663: 'std::vector<_Ty>::push_back' : 2 overloads have no legal conversion for 'this' pointer A: The regular std::vector does not support CLR reference types. Instead, you must use cliext::vector. Include the following: #include <cliext/vector> And use with: cliext::vector<System::Windows::Forms::CheckBox^> items; items.push_back(myCheckBox); Of course, you can also use the regular .Net collections, like List<T>, which behaves similarly as a vector.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537809", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: function declaration scope Most people seem to declare functions outside the code block that's using them like this: void doSomething(); void doStuff() { doSomething(); } I'm wondering if it's considered a good habit to do instead like this: void doStuff() { void doSomething(); doSomething(); } The second method has smaller scope and that's generally considered good style, but why isn't almost anyone using it? Are there some drawbacks? A: As the function has to be defined in the enclosing namespace scope, there doesn't seem to be a great advantage in restricting the declaration to the function scope. Conventionally, having a single declaration in a header file is easier to maintain as, if the function definition needs to change, only a single declaration needs to be adjusted not a declaration in each other function where the function is used. A: If doSomething() is only used in this c-file, it should be declared static. static void doSomething(); It is a good pratice to declare all static function prototypes at the beginning of a file instead of in the middle of the code line in your example. This way, if someone is looking through your code and sees all the static function prototyes he can get quick overview of whats happening.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you concatenate two strings? Possible Duplicate: How do I concatenate multiple C++ strings on one line? How would I take: string test1 = "Hello "; string test2 = "World!"; and concatenate them to make one string? A: How about string test3 = test1 + test2; Or maybe test1.append(test2); A: You could do this: string test3 = test1 + test2; Or if you want to add more string literals, then : string test3 = test1 + test2 + " Bye bye World!"; //ok or, if you want to add it in the beginning, then: string test3 = "Bye bye World!" + test1 + test2; //ok
{ "language": "en", "url": "https://stackoverflow.com/questions/7537820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Looking for a convenient way to call Java from C++ It seems most documentation or helper libraries relating to JNI (Java Native Interface) are concerned with calling native code from Java. This seems to be the main use of it, even though it is capable of more. I want to mostly work in the opposite direction: modify an existing (fairly large) portable C++ program by adding some Java libraries to it. For example, I want to make it call databases via JDBC, or message queue systems via JMS, or send emails, or call my own Java classes, etc. But with raw JNI this is pretty unpleasant and error-prone. So I would ideally like to write C++ code that can call Java classes as easily as C++/CLI can call CLR classes. Something like: using namespace java::util::regex; // namespaces mapped Pattern p = Pattern.compile("[,\\s]+"); array<java::lang::String> result = p.split("one,two, three four , five"); for (int i=0; i < result.length(); i++) std::cout << result[i] << std::endl; This way, I wouldn't have to manually do the work of getting the method ID by passing the name and the weird signature strings, and would be protected from programming errors caused by the unchecked APIs for calling methods. In fact it would look a lot like the equivalent Java. NB. I AM STILL TALKING ABOUT USING JNI! As an underlying technology it is perfect for my needs. It is "in process" and highly efficient. I don't want to run Java in a separate process and make RPC calls to it. JNI itself is fine. I just want a pleasant interface to it. There would have to be a code generation tool to make equivalent C++ classes, namespaces, methods, etc. to exactly match what is exposed by a set of Java classes I specify. The generated C++ classes would: * *Have member functions that accept similarly-wrapped versions of their parameters and then do the necessary JNI voodoo to make the call. *Wrap the return values in the same way so I can chain calls in a natural way. *Maintain a per-class static cache of method IDs to avoid looking up them every time. *Be totally thread-safe, portable, open source. *Automatically check for exceptions after every method call and produce a std C++ exception. *Also work for when I'm writing native methods in the usual JNI way but I need to call on to other Java code. *The array should work totally consistently between primitive types and classes. *Will no doubt need something like global to wrap references in when they need to survive outside of a local reference frame - again, should work the same for all array/object references. Does such a free, open-source, portable library/tool exist or am I dreaming? Note: I found this existing question but the OP in that case wasn't nearly as demanding of perfection as I am being... Update: a comment about SWIG led me to this previous question, which seems to indicate that it is mostly about the opposite direction and so wouldn't do what I want. IMPORTANT * *This is about being able to write C++ code that manipulates Java classes and objects, not the other way round (see the title!) *I already know that JNI exists (see the question!) But hand-written code to the JNI APIs is unnecessarily verbose, repetitious, error-prone, not type-checked at compile time, etc. If you want to cache method IDs and class objects it's even more verbose. I want to automatically generate C++ wrapper classes that take care of all that for me. Update: I've started working on my own solution: https://github.com/danielearwicker/cppjvm If this already exists, please let me know! NB. If you're considering using this in your own project, feel free, but bear in mind that right now the code is a few hours old, and I only wrote three very unstrenuous tests so far. A: I'm one of the prinicpal architects for Codemesh's language integration products, including JunC++ion. We have been doing this kind of integration since 1999 and it works really well. The biggest problem is not the JNI part. JNI is tedious and hard to debug, but once you get it right, it mostly just keeps working. Every now and then, you get broken by a JVM or an OS update, and then you have to fine-tune your product, but in general it's stable. The biggest problem is the type system mapping and the trade-offs between general usability and targeted solution. You state for example that you don't like the fact that JACE treats all object references as globals. We do the same thing (with some escape hatches) because it turns out that this is the behavior that works best for 95% of customers, even if it hurts performance. If you're going to publish an API or a product, you have to pick the defaults that make things work for most people. Picking local references as the default option would be wrong because more and more people are writing multithreaded applications, and a lot of Java APIs that people want to use from other languages are intrinsically multithreaded with asynchronous callbacks and the like. We also found out that you really want to give people a GUI-based code generator to create the integration specification. Once they've specified it, you use the CLI version to integrate it into the nightly build. Good luck with your project. It's a lot of work to get right. We spent several years on it and we're still making it better regularly. A: I had pretty much the same problems, ended up doing it on my own, maybe this helps someone. https://github.com/mo22/jnipp It has a small runtime footprint (<30kb), manages references, and supports generating Java class interfaces. I.e. LocalRef> stringArray; and then using stringArray[1]->getBytes() or something. A: Re calling Java from C++. You can do what you wish but you must let Java be in control. What I mean by this is that you create Java threads that call into Native code and from there they block, kind of waiting for your native code to give it something to do. You create as many Java threads as you need to get enough work / throuhput done. So your C++ application starts up, it creates a JVM/JavaVM (as per the documented way, example exists in qtjambi codebase see below), this in turn perform the usual JNI initialization and System.loadLibrary() and provides JARs with "native" linkage. You then initialize a bunch of threads and call some JNI code (that you created) where they can block in wait for your C++ code to give them some work to do. Your C++ code (presumabily from another thread) then sets up and passes all the information needed to one of the blocked and waiting Java Thread workers, it is then given the order to run, it may then go back into pure-Java code to do work and return with a result. ... It is possible to setup and create and contain a JavaVM instance from C++ code. This can be force fed your own CLASSPATH/JARs to setup the contained environment you need encapsulated inside your C++ program. Outline of that as I'm sure you have found already at http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/invocation.html ... There is a kind of C++ => Java JNI generator in the QtJambi project (that I work on and help maintain). This is quite bespoke for the Qt toolkit but essentially it translates a bunch of C++ header files into a collection of C++ .cpp/.h files and *.java file to provide linkage and shell containment of the object so that the competing memory allocation schemes play well together. Maybe there is something to be taken from this. This is certainly a proof in cencept for what you are asking the generator just happens to be contained in the qtjambi project (but could be made independant with some work) and this is LGPL licensed (open-source). The Qt toolkit is not a small API yet it can generated 100s of classes to cover high % of API (>85% and almost 100% of Core/GUI parts). HTH A: Yes, there are existing tools that do exactly this -- generate C++ wrappers for Java classes. This makes use of Java APIs in C++ more transparent and enjoyable, with lower cost and risk. The one that I've used the most is JunC++ion. It's mature, powerful and stable. The primary author is very nice, and very responsive. Unfortunately, it's a commercial product, and pricey. Jace is a free, open-source tool with a BSD license. It's been years since I last played with jace. Looks like there's still some active development. (I still remember the USENET post by the original author, over a decade ago, asking basically the same question you're asking.) If you need to support callbacks from Java to C++, it's helpful to define C++ classes that implement Java interfaces. At least JunC++ion allows you to pass such C++ classes to Java methods that take callbacks. The last time I tried jace, it did not support this -- but that was seven years ago. A: I also had many difficulties getting JNI to work on different operating systems, coping with 32/64-bit architectures and making sure the correct shared libraries were found and loaded. I found CORBA (MICO and JacORB) difficult to use too. I found no effective way to call from C/C++ into Java and my preferred solutions in this situation are to run my Java code as either: * *a stand-alone program that I can easily run from C/C++ programs with java -cp myjar.jar org.foo.MyClass. I guess this is too simplistic for your situation. *As a mini-server, accepting requests from C/C++ programs on a TCP/IP socket and returning results through this socket too. This requires writing networking and serializing functions but decouples the C/C++ and Java processes and you can clearly identify any problems as being in the C++ side or Java side. *As a Servlet in Tomcat and make HTTP requests from my C/C++ program (other servlet containers would also work too). This also requires writing networking and serializing functions. This is more like SOA. A: What about using Thrift or Protocol Buffers to facilitate your Java to C++ calls? A: Maybe a bit of a too large hammer for this nail, but isn't that what CORBA was built for? A: Since CORBA doesn't seem to be what you want, here are links describing how to start JVM from C/C++ and calling JAVA-methods. http://java.sun.com/docs/books/jni/html/invoke.html and http://java.sys-con.com/node/45840 PS: When interfacing Java with C++ you should also have a look at JNA or bridj. A: Answering my own question: http://java4cpp.kapott.org/ Doesn't appear to be an active project. The author recommends it not be used with JDK 1.5 or later. It appears to have a serious problem: it passes around naked pointers to its wrapper objects: java::lang::Integer* i = new java::lang::Integer("10"); delete i; // don't forget to do this! It also causes a more subtle problem that in order to represent assignment compatibility (e.g. a class as a subtype of the interface it implements) the wrappers have to inherit from each other.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: Convert an SQL expression if it has a LENGTH function with SUBSELECT query to SQLite I know that in SQLite, we use the LENGTH function instead of len. But when I want to use the LENGTH function with a subquery like so: select length(select name from tblNames where name=1) I receive an error. Here is the Microsoft SQL version of the expression: iif(len((select BilgiAcik from DigerBilg where BilgTip=12 and BilgDgr=Cstr(Dr.Fr)))>0,( select BilgiAcik from DigerBilg where BilgTip=12 and BilgDgr=Cstr(Dr.Fr)),Cstr(Dr.Fr)) as Fr, I converted the above expression into SQLite as so: (case length((select BilgiAcik from DigerBilg where BilgTip=12 and BilgDgr=CAST(Dr.Fr as TEXT))>0 ( select BilgiAcik from DigerBilg where BilgTip=12 and BilgDgr=Cstr(Dr.Fr)) else CAST(Dr.Fr as TEXT) end) as Fr, What I'm I doing wrong about? Can't I just use the SUBSELECT query with the LRNGTH function? Any suggestions on how to solve this problem? A: You will want to restructure your statement to be more similar to the following. select length(name) from (select name from tblnames where name=1); You can manage this a bit more easily by aliasing the subselects if you like. select length(t.name) from (select name from tblnames where name=1) as t;
{ "language": "en", "url": "https://stackoverflow.com/questions/7537823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Getting an error while Updating WCF Service Reference I got an error like this. There was an error downloading http://localhost:5705/UserService.svc Unable to connect Remote Server No Connection could be made because the target machine actively refused 127.0.0.1:5705 Metadata contains a reference that cant be Resolved 'http://localhost:5705/UserService.svc' could not connect to 'http://localhost:5705/UserService.svc' TCP error code 10064:No Connection could be made because the target machine actively refused 127.0.0.1:5705, enable to connect Remote Server No Connection could be made because the target machine actively refused 127.0.0.1:5705 A: There is normally 4 reasons for this: * *The service is not running *The meta data exchange is not enabled *No mex endpoint is defined *port is blocked on firewall
{ "language": "en", "url": "https://stackoverflow.com/questions/7537824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: List of open browser tabs programmatically Is there a way to programmatically obtain a list of open tabs in a browser by index? For example, suppose Google Chrome is open with two tabs. In the program, a line something like: tabs_list = list_tabs(hwnd) ...where hwnd is the handle to the window for the overall Chrome instance and tabs_list is a dictionary something like: { 0 : 'http://stackoverflow.com/', 1 : 'http://www.otherstufff.com/' } (...or maybe by title of the window instead of url) If so, then bringing focus to one of them can be possible from the Python script with keyboard commands, control- (CTRL-) like control-1 or control-2. An edit added later to try to help clarify: Picture a local wxPython app, where you already know how to activate a given instance of Chrome on that same box from within your wxPython app running locally, and that browser instance has multiple tabs open, and now you want to insure that a certain tab has focus, to be able to interact with that web page that is being displayed (maybe using CTRL-A CTRL-C for example to harvest its content). This question is not about issuing keyboard commands, that is already known, the question is how to obtain a list of open tabs, if possible, thanks. A: Its not possible. First you haven't noted what app you develop but if you use python for a website backend - then its just a server-side language and does not know what a "browser" is - the server outputs to the browser and thats all. And I don't believe it's possible with client-side language like javascript as this seem to be a serious security and privacy issue if it was possible. Edit: If you are developing a Chrome plugin lets say it might be a whole different story - but then it goes towards the Chrome API and your tagging is wrong, as "python" itself can not do that. A: While not sure of your target OS, you can do this on Mac OS X: >>> from appscript import * >>> map(lambda x: x.title(), app('Google Chrome').windows[0].tabs()) [u'Stack Overflow', u'Google'] On Windows, you will want to look into OLE Automation with Python.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: FileReader for text file in Android Good times! My Android app is trying to read simple text file, using usual Java combination FileReader fr = new FileReader("file:///android_asset/example.txt"); BufferedReader bfr = new BufferedReader(fr); But what ever I do, I'm getting File not Found exeption, although there is another html-file in this directory and shown in WebView correctly. So, my question is: FileReader can be used for simple reading text file or I have to use InputStream ? A: You have to InputStream like as follows.Change the code like this.I hope it will work: FileInputStream fis = new FileInputStream("file:///android_asset/example.txt"); BufferedReader bfr = new BufferedReader(new InputStreamReader(fis)); A: Use getAssets() method. BufferedReader br=new BufferedReader(new InputStreamReader(getAssets().open("example.txt"))); A: Android doesn't know where your files are located. You have to use their functions. See the section called data storage, especially the section on internal storage and the methods in the Android Context class for opening and writing to files. For example you could use the Context method getFileStreamPath to get a Java File object and pass that to a Java FileReader. File yourFile = getFileStreamPath(YOUR_FILENAME); if (yourFile.exists()) { BufferedReader in = new BufferedReader(new FileReader(yourFile)); ... in.close(); } P.S. Here's a very similar question and answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Can I configure JSch to automatically reconnect on connection failures? I am using the JSch API for Java for SFTP connections. Sometimes the server may be down for a second or the connection may be busy. In these cases I would need to re-connect to the server three times at least before I decide the connection has failed. Does JSch provide any configuration option to do this automatically? A: JSch has no such configuration option, but you can simply do this yourself. Session s = new Session(...); for(int i = 0; i < MAX_TRIES; i++) { try { s.connect(); break; } catch(JSchException ex) { if(i == MAX_TRIES - 1) throw ex; continue; } } After executing this block, either the session is connected or a JSchException is thrown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Testing concurrent/parallel execution I'm currently writing a small framework for demand-driven workflows. The API is now stable and I am working on improving tests. It's easy to show that computations are correct (which is a good start), however, the main interest of the framework is to launch subtasks in parallel (when needed and possible). Is there a way to test automatically that two different pieces of code do run in a parallel/concurrent fashion ? I prefer not relying on execution time (speed-up) measurments. The framework is written in scala, and relies a lot on Akka Futures. EDIT: Here is an example: val foo = step { //... defines an arbitrary task } // Runs 5 times the code inside step foo val foos = repeat( 5 )( foo ) I would like to be sure that the code inside foo is executed 5 times in parallel. A: I don't see a way to do this without changing tasks (i.e. when you need to test that two specific tasks run in parallel). But if you can change the tasks, just add an actor to the system. Make every task send messages to this actor when starting or ending work. If the actor receives two Starting messages in a row, the tasks should be running in parallel (or at least in different threads). A: This test does not make any sense to me. On a computer with less than 5 cores you cannot get a parallelism of 5. It seems like you are testing Akka, which we are already doing, so just relax and test the dispatcher settings to verify that when it will run it will have the desired effect. Hope that helps, Cheers, √
{ "language": "en", "url": "https://stackoverflow.com/questions/7537835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: C# - Converting KeyPress to scancode/scancode to key name I have a WinForm application where I need to capture a KeyPress and fetch the scancode for it. Along with that I need to convert existing scancodes int key names (by converting to virtual keys beforehand perhaps?) Is there any way to accomplish this? A: The first part is possible, but tricky, because multiple Virtual Key (VK) codes will map to the same scancode (depending on the keyboard shift/ctrl/alt state). I'm not sure what you mean by "key name," but if you're referring to the physical keyboard layout then, for your next step, you will need to make some assumptions about the key's location based on standard physical keyboard layouts (101-key, 102-key etc). See my answer to this question for some sample code and a more detailed description. A: If you still need it, you can use Reflection for private members access. I know it's not good idea and interfaces can change in next versions, but it works for .Net Framework 4.6 private void OnKeyDown(object sender, KeyEventArgs e) { MSG l_Msg; ushort l_Scancode; PresentationSource source = e.InputSource; var l_MSGField = source.GetType().GetField("_lastKeyboardMessage", BindingFlags.NonPublic | BindingFlags.Instance); l_Msg = (MSG)l_MSGField.GetValue(source); l_Scancode = (ushort)(l_Msg.lParam.ToInt32() >> 16); //Use scancode }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Valgrind program is crashing Bad permissions for mapped region at address I am trying to run my program to check memory leaks in my program but whenever I start my program I am getting ==3476== Process terminating with default action of signal 11 (SIGSEGV): dumping core ==3476== Bad permissions for mapped region at address 0xCFE3FF8 ==3476== at 0x005212e1: get_document_root (mongoose.c:1557) ==3476== ==3476== HEAP SUMMARY: ==3476== in use at exit: 2,134,492 bytes in 3,948 blocks ==3476== total heap usage: 5,473 allocs, 1,525 frees, 2,863,520 bytes allocated ==3476== and in full valgrind log thee is no invalid read or write on the memory. I am not able to understand why it is crashing. A: It was crashing because of custom 404 page and that file was not there. So it was infinitely looking for that file and doing buffer overflow.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP exec function not working I am trying to execute a command from php script using php exe function. The script calls .exe file located in program files whereas my xampp is intalled in E: I m trying the following command C:\\Program Files\\GPStill\\pstill.exe its not working.But if i manually open cmd prompt and stand in c:\prgram files folder than run pstill.exe it works... Any ideas ??? A: you need to escape the folders for example <?php $command 'C:\"Program Files"\"Internet Explorer"\iexplore.exe'; exec($command); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7537847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the case that requires nested transaction? Even a transaction is nested, it won't be updated until outmost transaction commits. So what's the meaning of nested transaction and what's the specific situation that requires the feature? A: for example assume such a situation: Class A { /// props save(); } class B { A a{get;set}; // other props save(); } now when you want to save B, you first save A assume in saving A you have some service calls for verification or etc, such a situation in saving B (some verifications) so you need rollback if B can not verified, also you should to rollback when you can't verify A so you should have nested one (in fact Separation of concern cause to this, you can mix all things and have a spaghetti code without nested transaction). A: There is nothing called Nested Transactions. The only transaction that SQL considers, is the outermost one. It's the one that's committed or is rolled back. Nested Transactions are syntactically valid, that's all. Suppose you call a procedure from inside a transaction, and that procedure has transactions itself, the syntax allows you to nest transactions, however the only one that has any effect is the outermost. edit: Reference here : http://www.sqlskills.com/BLOGS/PAUL/post/A-SQL-Server-DBA-myth-a-day-(2630)-nested-transactions-are-real.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7537854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to initialize properties in Javascript constructor I am playing with html5 canvas to create bouncing balls. I have this all working but I have to call an initialise function to set certain properties. How can I do this automatically in the constructor without having the initializer firing when the properties are accessed? var test1 = new Ball(20); test1.setAngleAndVelocity(); //I dont want to have to call this. function Ball(speed){ this.position = new Vector2(canvas.width / 2, canvas.height / 2); this.velocity; this.speed = speed; this.angle; this.setAngleAndVelocity = function(){ this.angle = Math.floor(Math.random() * 360) * 0.0174532925; this.velocity = new Vector2(this.speed/10 * Math.cos(this.angle), this.speed/10 * Math.sin(this.angle)); } } A: Since setAngleAndVelocity() is a static method, I'd recommend putting it in the prototype of your Ball class: function Ball(speed){ this.position = new Vector2(canvas.width / 2, canvas.height / 2); this.speed = speed; this.setAngleAndVelocity(); //Sets the additional values } Ball.prototype.setAngleAndVelocity = function(speed){ speed = typeof speed != "undefined" ? speed : this.speed; this.angle = Math.floor(Math.random() * 360) * 0.0174532925; this.velocity = new Vector2(speed/10 * Math.cos(this.angle), speed/10 * Math.sin(this.angle)); } this.velocity; and this.angle; aren't necessary: They're not defining anything, and the only use they serve is to show the developer what properties may be defined. After these modifications, your script has become more efficient, and can be used in this way: var test1 = new Ball(20); //Inititalized test1.setAngleAndVelocity(22); //Optional, a method to adjust the speed value after the init of the class. A: Just inline that computation into the constructor. function Ball(speed){ this.position = new Vector2(canvas.width / 2, canvas.height / 2); this.speed = speed; this.angle = Math.floor(Math.random() * 360) * 0.0174532925; this.velocity = new Vector2(this.speed/10 * Math.cos(this.angle), this.speed/10 * Math.sin(this.angle)); } ADDENDUM If you want to keep the function around to update the angle and velocity at other times in your application, place that function in the prototype: Ball.prototype.changeSpeed = function (newSpeed) { this.speed = newSpeed; this.velocity = new Vector2(this.speed/10 * Math.cos(this.angle), this.speed/10 * Math.sin(this.angle)); } You can call this method from the constructor if you wish: function Ball(speed){ this.position = new Vector2(canvas.width / 2, canvas.height / 2); this.angle = Math.floor(Math.random() * 360) * 0.0174532925; this.changeSpeed(speed); } See http://jsfiddle.net/FnHLX/ for a working example. You can also write a similar function for angle changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS: Place UIView on top of UITableView in fixed position I need to put a UIView (for ads) on top of a UITableView in my iphone app. The problem is that when I scroll the table to the bottom the added UIView is scrolling with the table. What I want is for it to be fixed on the bottom of the screen. Is there a way to do that? This is the code which I have used to add the UIView to the table: awView = [AdWhirlView requestAdWhirlViewWithDelegate:self]; awView.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin; [self.tableView addSubview:awView]; A: I had a similar problem where I wanted to add a loading indicator on top of my UITableViewController. To solve this, I added my UIView as a subview of the window. That solved the problem. This is how I did it. -(void)viewDidLoad{ [super viewDidLoad]; //get the app delegate XYAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; //define the position of the rect based on the screen bounds CGRect loadingViewRect = CGRectMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2, 50, 50); //create the custom view. The custom view is a property of the VIewController self.loadingView = [[XYLoadingView alloc] initWithFrame:loadingViewRect]; //use the delegate's window object to add the custom view on top of the view controller [delegate.window addSubview: loadingView]; } A: Here is how it worked for me. The Ad stays at the bottom of the view. In ViewDidLoad, in YourController.m: awView = [AdWhirlView requestAdWhirlViewWithDelegate:self]; awView.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height-kAdWhirlViewHeight/2); [self.view addSubview:awView]; Then add this method somewhere in the same .m file: -(void)scrollViewDidScroll:(UIScrollView *)scrollView { CGRect newFrame = awView.frame; newFrame.origin.x = 0; newFrame.origin.y = self.tableView.contentOffset.y+(self.tableView.frame.size.height-kAdWhirlViewHeight); awView.frame = newFrame; } Don't forget to declare awView. A: I appreciate this is an old question. But I've found the answers either with false information in part and unclear snippets. So for what it's still worth, here is how I added a "floating" view to the bottom of my UITableViewController's view. Yes, you can do that, even if the accepted answers says you cannot. In your -viewDidLoad method, you can create a view which we will name bottomFloatingView. This is also set up as a property. Be sure to add a content inset to the bottom of your table view, this will avoid hiding any of the table's content with your floating view. Next, you should use the UIScrollViewDelegate to update the frame of the floating view. The illusion will be that your view is stuck to the bottom. In reality, this view is moving all the time you are scrolling, and is always being computed to appear at the bottom. Scroll views are very powerful ! And probably are one of the most underrated UIKit classes I think. So here is my code. Note the property, the content inset on the table view and the -scrollViewDidScroll: delegate method implementation. I created my floating view in my storyboard which is why you can't see that being setup. Also don't forget you should probably also use KVO to observe changes to the table view's frame. It's possible for that to change over time, the easiest way to test that is by toggling on and off the in call status bar in the simulator. Last thing, if you're using section header views in your table view, those views will be the top most view in the table view so you'll also want to bring your floating view to the front, do this when you change its frame. @interface MyTableViewController () @property (strong, nonatomic) IBOutlet UIView *bottomFloatingView; @end @implementation MyTableViewController static NSString *const cellIdentifier = @"MyTableViewCell"; - (void)dealloc { [self.tableView removeObserver:self forKeyPath:@"frame"]; } - (void)viewDidLoad { [super viewDidLoad]; [self.tableView addSubview:self.bottomFloatingView]; self.tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, CGRectGetHeight(self.bottomFloatingView.bounds), 0.0); self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, CGRectGetHeight(self.bottomFloatingView.bounds), 0.0); [self.tableView addObserver:self forKeyPath:@"frame" options:0 context:NULL]; } #pragma mark - UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 20; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row]; return cell; } #pragma mark - UIScrollViewDelegate - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [self adjustFloatingViewFrame]; } #pragma mark - KVO - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([keyPath isEqualToString:@"frame"]) { [self adjustFloatingViewFrame]; } } - (void)adjustFloatingViewFrame { CGRect newFrame = self.bottomFloatingView.frame; newFrame.origin.x = 0; newFrame.origin.y = self.tableView.contentOffset.y + CGRectGetHeight(self.tableView.bounds) - CGRectGetHeight(self.bottomFloatingView.bounds); self.bottomFloatingView.frame = newFrame; [self.tableView bringSubviewToFront:self.bottomFloatingView]; } @end A: For people like me looking for a simple solution using Swift, these answers are kind of outdated. Here's what I did (assuming myCustomView was established somewhere else in the file): func scrollViewDidScroll(_ scrollView: UIScrollView) { let pixelsFromBottom = CGFloat(20)//or whatever the let theHeight = self.tableView.frame.height + scrollView.contentOffset.y myCustomView.frame = CGRect(x: 0, y: theHeight - pixelsFromBottom , width: self.view.frame.width, height: myCustomView.frame.height) } A: * *Add your view to the superview of the table view (if possible; UITableViewControllermakes this impossible). *Add your view to the table view and reposition it in the -scrollViewDidScroll:delegate method (UITableViewDelegateis a sub-protocol of UIScrollViewDelegate). A: - (void)viewDidLoad { [super viewDidLoad]; footerView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-64, SCREEN_WIDTH, 64)]; footerView.backgroundColor = [UIColor blueColor ]; [self.navigationController.view addSubview:footerView]; } - (void)dealloc { [footerView removeFromSuperview]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Android plist xml parsing issue I have to parse a plist file in Android application. Plist is similar to xml given on following url: http://pastie.org/2583229 Will I be able to parse to display data in the app? Which parser is good for this purpose? Please help me here by giving me some suggestions. A: Below I have mentioned one way of parsing that XML. I have used XmlPullParser to parse the above mentioned xml: String str1 ="<Xml to be parsed>"; XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser xpp = factory.newPullParser(); xpp.setInput( new StringReader (str1)); int eventType = xpp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String str; if(eventType == XmlPullParser.START_DOCUMENT) { System.out.println("Start document"); } else if(eventType == XmlPullParser.START_TAG) { str = xpp.getName(); System.out.println("Start tag "+str); } else if(eventType == XmlPullParser.END_TAG) { System.out.println("End tag "+xpp.getName()); } else if(eventType == XmlPullParser.TEXT) { System.out.println("Text "+xpp.getText()); } eventType = xpp.next(); } System.out.println("End document"); A: Your response is xml file so you can read that file using any xml parser For more details about different types of xml parser follow below link Different types of xml parsers
{ "language": "en", "url": "https://stackoverflow.com/questions/7537859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to apply styling on the parent container of a:visited? I need to style my divs(that're parent container of links) differently when the links have been visited. Can I do that using pure CSS, or I need to resort to JS ? A: You can not do this using pure CSS, not even in the latest CSS3 specification. You can do it with JS. With plain JS its quite unpleasant thing to do. If you use let's say jQuery, then you can do something like this: $('a:visited').parent('div').css('color: #fff;'); A: No, you can't do backreferences like this in CSS. You'll need to select them using JavaScript. Alternately, HTML5 allows you to put <a> elements around block elements so you can turn this inside out: a:visited .parent_container { background: pink; } A: It's not possible using only CSS. You've to implement your :visited logic. Then using JS, when the user click on a link, add a class (ie visited) to its parent div.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to serialize .NET Table Adapter I need to serialize a .NET table adapter. Serializing a data adapter and the data set is not a problem but i seem unable to serialize the table adapter. Looking at the type its typically specific to whatever you name it..like if i create a Invoice Table Adapter..the type will be InvoiceTableAdapter and its base type is component. This does not give me an easy type to work from like the sql data adapter which is relatively simple to serialize. Also, i need to be able to serialize it and deserialize it without having to include the dll it came from when i deserialize it. The only dlls available on when deserializing will be standard .NET dlls. A: Also, i need to be able to serialize it and deserialize it without having to include the dll it came from when i deserialize it. If you are using BinaryFormatter (which I don't recommend, by the way), then no: you can't do that. That isn't how BinaryFormatter works. It expects to recreate exactly what was serialized, which demands the same dlls. If you are using any other serializer, it makes perhaps even less sense; you should be serializing *data, really. Not plumbing details like adapters. In all seriousness, I think you need to reconsider your design here. Why are you trying to serialize adapters, for example? What would that even mean? It might, for example, make sense to write a DTO that represents the data you need to construct a vanilla SqlDataAdapter.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Send value on onsubmit I want to send document.getElementById('source').value onsubmit. How can i send? thanks this value document.getElementById('source').value working fine. But I want to call this on submit. Because some time user could change the value. new AjaxUpload(btnUpload, { action: 'upload-file.php?source='+document.getElementById('source').value+'&destination='+document.getElementById('destination').value+'&subjectarea='+document.getElementById('subjectarea').value+'&order_id='+document.getElementById('order_id').value, name: 'uploadfile', onSubmit: function(file, ext,source){ if (! (ext && /^(txt|pdf|doc|docx|pptx|ppt|xlsx|xls)$/.test(ext))){ // extension is not allowed status.text('Only TXT, PDF, PPTX, PPT, XLS, XLSX, DOC or DOCX files are allowed'); return false; } ; status.text('Uploading...'); } A: you should put it in an input type value and then in the server - use REquest["id"] to get the val A: $.ajax({ url:upload-file.php', data:{source:$('#source').val(),destination:$('destination').val(),subjectarea:$('#subjectarea').val(),order_id:$('#order_id').val()}, type:'post', dataType:'text', success:function(msg){ $('#div').html(msg); }, error:function(){ // handle your error } }); here "data" is used to send the variable to requested file. you can get these variable in your requested file by using $_POST[] OR $_REQUEST[] variable. So name of the variable would be $_POST['source'], $_POST['destination'] and so on
{ "language": "en", "url": "https://stackoverflow.com/questions/7537869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android FrameLayout and TextView - why does LayoutParams work where setGravity() does not? I'm using a FrameLayout to display (on demand) some text on the screen. I want the text to be in a certain place, so I thought setGravity() would do the job... but no, it seems to have no effect whatsoever on where the text goes (and other objects like ImageView don't even have this method). So first, what exactly is TextView.setGravity() used for? (Edit: I understand this much better now, thanks! Still not clear on the following part of the question though.) Second, it seems the only way to update a FrameLayout in this way is to create a new FrameLayout.LayoutParams object with the settings you want, and then use the setLayoutParams() method to apply it. (This seems to automatically update the view so is a requestLayout() call necessary?) And is there a simpler / more straightforward way to achieve this for a FrameLayout... say, without creating a new LayoutParams object as I'm doing now? Thanks! For reference, below is a (working) code snippet showing how I'm setting up this FrameLayout and TextView. FrameLayout fl1 = new FrameLayout(this); FrameLayout.LayoutParams flp1 = new FrameLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); fl1.setId(9001); fl1.setLayoutParams(flp1); ..... tv1 = new TextView(this); FrameLayout.LayoutParams tvp1 = new FrameLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, (Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)); tv1.setId(9006); tv1.setLayoutParams(tvp1); // This works tv1.setBackgroundColor(Color.GRAY); tv1.setTextColor(Color.BLACK); tv1.setText("Dynamic layouts ftw!"); tv1.setGravity(Gravity.CENTER); // This does NOT work ..... fl1.addView(tv1); A: tv1.setGravity(Gravity.CENTER); belongs to the gravity of the TEXT inside the TextView. As documentation states: Sets the horizontal alignment of the text and the vertical gravity that will be used when there is extra space in the TextView beyond what is required for the text itself. A: 1) view.setGravity means hows the view should positions if children. In the case of the textview it refers to the positioning of the text. When in linearlayouts or viewgroups it refers to its child views. 2) I checked your code. You are already using textview.setGravity method. In that case you dont need to specify gravity parameters in the FrameLayout.LayoutParams constructor. Other thing I noticed is that you gave the textview the width and height as wrap content which will only take the size of the text. So there is no meaning in giving gravity as the textview has no extra area to position the text to the center. You need to give the width of the textview as fill_parent. That should make your gravity property work. Btw this is a very good article about Gravities. It explains both about gravity and the layout_gravity attribute. If you want your textview to wrap the content then you should add your textview to a linearlayout and setgravity to the linear layout. This should give what your are trying to do LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); FrameLayout fr = new FrameLayout(this); fr.setLayoutParams(lp); fr.setBackgroundColor(Color.RED); LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); LinearLayout l = new LinearLayout(this); l.setLayoutParams(lp2); l.setGravity(Gravity.CENTER); l.setBackgroundColor(Color.BLUE); ViewGroup.LayoutParams vp = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); TextView t = new TextView(this); t.setLayoutParams(vp); t.setText("Blessan Mathew"); t.setBackgroundColor(Color.CYAN); l.addView(t); fr.addView(l);
{ "language": "en", "url": "https://stackoverflow.com/questions/7537873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you convert an int into a string in c++ I want to convert an int to a string so can cout it. This code is not working as expected: for (int i = 1; i<1000000, i++;) { cout << "testing: " + i; } A: Use std::stringstream as: for (int i = 1; i<1000000, i++;) { std::stringstream ss("testing: "); ss << i; std::string s = ss.str(); //do whatever you want to do with s std::cout << s << std::endl; //prints it to output stream } But if you just want to print it to output stream, then you don't even need that. You can simply do this: for (int i = 1; i<1000000, i++;) { std::cout << "testing : " << i; } A: Do this instead: for (int i = 1; i<1000000, i++;) { std::cout << "testing: " << i << std::endl; } The implementation of << operator will do the necessary conversion before printing it out. Use "endl", so each statement will print a separate line. A: You should do this in the following way - for (int i = 1; i<1000000, i++;) { cout << "testing: "<<i<<endl; } The << operator will take care of printing the values appropriately. If you still want to know how to convert an integer to string, then the following is the way to do it using the stringstream - #include <iostream> #include <sstream> using namespace std; int main() { int number = 123; stringstream ss; ss << number; cout << ss.str() << endl; return 0; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Intent and Bundle Relation While using Intent object we can put different types of data directly using its putExtra(). We can also put these extra data into a Bundle object and add it to Intent. So why do we need Bundle if we can do so using Intent directly? A: Sometimes you need to pass only a few variables or values to some Other Activity, but what if you have a bunch of variable's or values that you need to pass to various Activities. In that case you can use Bundle and pass the Bundle to the required Activity with ease. Instead of passing single variable's every time. A: Let's assume you need to pass a Bundle from one Activity to another. That's why Intent allows you to add Bundles as extra fields. EDIT: For example if you want to pass a row from a database along with some other data it's very convenient to put this row into a Bundle and add this Bundle to the Intent as a extra field. A: As you can see, the Intent internally stores it in a Bundle. public Intent putExtra(String name, String value) { if (mExtras == null) { mExtras = new Bundle(); } mExtras.putString(name, value); return this; } A: I guess what @Lalit means is supposing your activity always passes the same variables to different intents, you can store all of them in a single Bundle in your class and simply use intent.putExtras(mBundle) whenever you need the same set of parameters. That would make it easier to change the code if one of the parameters become obsolete in your code, for example. Like: public class MyActivity { private Bundle mBundle; @Override protected void onCreate(Bundle savedInstanceState) { mBundle = new Bundle(); mBundle.putString("parameter1", value1); mBundle.putString("parameter2", value2); } private void openFirstActivity() { Intent intent = new Intent(this, FirstActivity.class); intent.putExtras(mBundle); startActivity(intent); } private void openSecondActivity() { Intent intent = new Intent(this, SecondActivity.class); intent.putExtras(mBundle); startActivity(intent); } } OBS: As stated already, Intent stores the parameters in a internal Bundle, and it's worth noting that when you call putExtras, the internal Intent bundle doesn't point to the same object, but creates a copy of all variables instead, using a simple for like this: for (int i=0; i<array.mSize; i++) { put(array.keyAt(i), array.valueAt(i)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Eclipse RCP Fast View in Horizontal Orientation I do know how to register a View in the Fast views bar within a RCP Eclipse application (using plugin.xml). It opens in Vertical orientation. Does anybody know how to tell this view to open in Horizontal orientation per default? Thanks a lot for your help. A: Not sure if it is available. Already in 2004, it was mentioned in bug 55830: We have no plans to expose the "horizontal/vertical" fastview option as API (since this concept might be removed in the future in favor of 2 resize sashes). And the 2005 question about the same feature went unanswered! I currently add a fast view to my perspective... layout.addFastView(IConsoleConstants.ID_CONSOLE_VIEW, 0.35f); How can I programmatically set this view to default to a horizontal orientation? I assume this is not possible to do through the API? THe current IPageLayout doesn't seem to have any parameter for the orientation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to enable shell_exec() function in CentOS 5.6? I am using CentOS 5.6. When I google to find the answer about how to enable shell_exec() in CentOS 5.6 they answer as the following: # nano /etc/php.ini remove shell_exec from the disable_functions list. But in my php.ini file shows the following: disable_functions = How can I enable shell_exec() function in CentOS 5.6? A: Make sure your SELinux is disabled. A: Disable safe_mode and shell_exec should be available. A: create a script contains the following <?php phpinfo(); ?> and see if there is other php.ini files A: I found this in the Internet: disable_functions = ""
{ "language": "en", "url": "https://stackoverflow.com/questions/7537884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: if i call a non synchronized method from my synchronized method is non synchronized method thread safe? I i make a call to noonsynchronized method from within my synchronized method is it thread safe? I have 2 methods as follows: public class MyClass{ void synchronized doSomething1(){ doSomething2(); } void doSomething2(){ //will this block of code be synchronized if called only from doSomething1?? } } A: When calling doSomething1() the caller's Thread locks on the monitor of the instance of MyClass. Until that thread's execution exits doSomething1 the lock will remain which includes if it goes into doSomething2. This will cause other threads to block when attempting to lock. Keep in mind: synchronized does not thread-safe it make. Further info: * *JLS 3rd Ed 17.1 Locks A: If doSomething2() is only called from doSomething1(), then it will only be called by a single thread for a single instance of MyClass. It could still be called from different threads at the same time, via different instances - so if it acts on any shared data which may not be specific to the instance of MyClass, it's still not guaranteed to fix all threading issues. Basically, you need to think carefully about any mutable shared state used by multiple threads - there are no easy fixes to that, if you need mutable shared state. In your particular case you'd also need to make sure that doSomething2() was only called from doSomething1() - which would mean making it private to start with... A: If doSomething2() is called ONLY from doSomething1() then yes - it is thread safe.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Clone variable in Word VBA Given the range with revisions in it, I need to reconstruct the original text and the modified text. The first solution was to: Sub OriginalText (ByVal Rng as Range) Rng.Revisions.RejectAll OriginalText = Rng.Text End sub Yet it turned out that ByVal is not really ByVal. the moment RejectAll is called, all changes are rejected in original document as well, and there is no way to apply them - they're gone from ThisDocument.Revisions. Is there a (preferably handy) way to copy the variable Rng to any (say,Rng2) in the sub so I can work with the copy of the range without affecting the source? Is there a way to serialized the range and bring it together, maybe? Upd: Let me put it this way. Is there a chance to copy the object (Range in my case) so the changes made to the copy won't affect the source? I think that still is the fastest and the most elegant solution. A: Range is a marker, even though it returns the content of the range. If you want the text, you need to say so. Set r = Selection.Range TextNow = Selection.Range.Text TextOrig = OriginalText(r) A: .RejectAll seems to be clearing all of the revisions (including when the text was first entered). It would be convenient if we could access .Revisions(0), but it doesn't look like this is possible. Your best bet may be to see if you can store the original document before the changes are made. If that is not possible, you could go through with something like this script and find all of the changes by hand. A: Try Range.Duplicate, which seems to create a clone of the range.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537886", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Properly Saving to file with a file name ofstream myfile; string s=r->str_name+".txt"; myfile.open (s); where r->str_name is a string. If r->str_name was "animals" , would it save the file as animals.txt if i concatenate like this? A: Close. It does do as you expect in that r->str_name will be "animals.txt" but to pass it to myfile.open() you have to turn it into a const char* like so: myfile.open (s.c_str());
{ "language": "en", "url": "https://stackoverflow.com/questions/7537889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: not evaluation doubles Okay so I am sending doubles value to this and its not parsing them as doubles instead it is completely ignoring the decimal values. here is my code if I enter 2.0 + 5.0 it makes it 2 0 5 0 +. =( import java.beans.Expression; import java.util.ArrayList; import java.util.Scanner; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Infix2Postfix { private static String grabDigits(String s, int start){ String num = ""; for(int i=start; i < s.length(); i++){ char ch = s.charAt(i); if(Character.isDigit(ch)) num += ch; else return num; } return num; } private static Double apply(Double a, char op, Double b){ switch(op){ case '+' : return a + b; case '-' : return a - b; case '*' : return a * b; case '/' : return b == 0 ? null : a / b; default: return null; } } public static Double evalPostfix(String expr){ Stack<Double> s = new Stack<Double>(); for(int i=0; i<expr.length(); ){ char ch = expr.charAt(i); if(Character.isDigit(ch)){ String numStr = grabDigits(expr, i); i += numStr.length(); Double value; if(isColmn(numStr)){ value = getvaluefromcolmn(numStr); }else{ value = Double.parseDouble(numStr); } s.push(value); } else { if(isOp(ch)){ if(s.size() < 2) return null; Double b = s.pop(); // right arg Double a = s.pop(); // left arg s.push(apply(a, ch, b)); } else if(!Character.isWhitespace(ch)) return null; i++; // consume individual char } } if(s.size() != 1) return null; return s.pop(); } private static Double getvaluefromcolmn(String numStr) { // TODO Auto-generated method stub return null; } private static boolean isColmn(String numStr) { // TODO Auto-generated method stub return false; } private static int prec(char op){ switch(op){ case '+' : case '-' : return 0; case '*' : case '/' : return 1; default: return -1; } } private static boolean isOp(char ch){ return prec(ch) != -1; } public static String infix2postfix(String expr) { Stack<Character> s = new Stack<Character>(); String pExpr = ""; int numOperands = 0; int numOperators = 0; for(int i=0; i<expr.length(); i++){ char ch = expr.charAt(i); if(Character.isDigit(ch)){ pExpr += " " + ch; // could have used the grabDigits method here ... while(i+1 < expr.length() && Character.isDigit(expr.charAt(i+1))){ pExpr += expr.charAt(i+1); i++; } numOperands++; } else if (ch == '(') s.push(ch); else if (ch == ')'){ while(!s.empty() && s.peek() != '('){ pExpr = pExpr + " " + s.pop() + " "; numOperators++; } if(s.empty()) return "no matching open paren"; if(numOperators >= numOperands) return "too many operators"; s.pop(); } else if(isOp(ch)){ // pop operators with same or higher precedence while(!s.empty() && isOp(s.peek()) && prec(s.peek()) >= prec(ch)){ pExpr = pExpr + " " + s.pop(); numOperators++; } if(numOperators >= numOperands) return "too many operators"; s.push(ch); } // else white space - do nothing } while(!s.empty()){ char op = s.pop(); if(!isOp(op)) return "error"; pExpr += " " + op; } return pExpr; } public static void exp(String expr, ArrayList<ArrayList<Comparable<?>>> entries){ expr.replace("(", " ( "); expr.replace(")", " ) "); expr.replace("+", " + "); expr.replace(" - ", " - "); expr.replace("/", " / "); expr.replace("*", " * "); System.out.println("infix: " + expr); System.out.println("this is at expreesion after replacing "+ expr); System.out.println("postfix: " + infix2postfix(expr)); System.out.println("--------"); } public static void main(String [] args){ Scanner kbd = new Scanner(System.in); // ArrayList<int> tst; ArrayList<Integer> tst2; System.out.print("> "); while(kbd.hasNextLine()){ String expr = kbd.nextLine(); expr = expr.replaceAll("\\s+",""); System.out.println(expr); Pattern pattern = Pattern.compile("\\s+"); Matcher matcher = pattern.matcher(expr); boolean check = matcher.find(); String str = matcher.replaceAll(" "); expr = expr.replace("(", " ( "); expr =expr.replace(")", " ) "); expr =expr.replace("+", " + "); expr =expr.replace("-", " - "); expr =expr.replace("/", " / "); expr =expr.replace("*", " * "); String[] exprArray = expr.split(" "); System.out.println(str+ " this is expr "+exprArray[1]); System.out.println(expr); ArrayList<ArrayList<Comparable<?>>> entries = null; String pExpr = infix2postfix(expr); //System.out.println(evalPostfix(expr)); System.out.println(" postfix version: " + pExpr); System.out.println(" eval(\"" + pExpr + "\"): " + evalPostfix(pExpr)); System.out.print("> "); } } } A: I didn't check your code in detail but the following line while(i+1 < expr.length() && Character.isDigit(expr.charAt(i+1))) ... looks like you are parsing only digits but not '.' for each expression. The same holds true for your method grabDigits. A: By stopping at the first non-digit you are stopping at the decimal point, and therefore ignoring both it and everything after it. Don't convert strings to doubles with your own code, use Double.parseDouble().
{ "language": "en", "url": "https://stackoverflow.com/questions/7537890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: django render_to_string not working I am trying to implement an ajax view to create an object and then return it and insert it into the template. It is almost working except I cannot seem to get render_to_string() to work to render the html to insert. The object is being created and html is being returned and inserted into the template however the variables are not included in the html. My view is below. def tr_create_xhr(request, person, slug): if request.method == "POST": form = TopicResourceForm(request.POST) if form.is_valid(): try: r = Resource.objects.get(url=form.cleaned_data['resource']) except Resource.DoesNotExist: r = Resource.objects.create(url=form.cleaned_data['resource'], rtype=form.cleaned_data['rtype']) r.save() obj = form.save(commit=False) obj.resource = r try: topic = Topic.objects.get(person__user=request.user, slug__iexact=slug) except Topic.DoesNotExist: return Http404 obj.topic = topic objs = obj.save() html = render_to_string('includes/tr_inc.html',{"r":objs, "topic":topic}) res = {'html':html} if request.is_ajax(): return HttpResponse(simplejson.dumps(res), mimetype="application/json") else: return HttpResponseRedirect("../..") return Http404 This is the template "includes/tr_inc.html": {% load markup %} {% load people_tags %} <li> <h5>{{ r.title }}</h5> <p><a class="tru" href={{ r.resource.url }}>{{ r.resource.url|sliceit:70 }}</a></p> <span class="oc"><p>Added {{ r.added }}{% if r.rtype %} |<a href={% url resource_type_detail r.rtype.slug %}>{{ r.rtype }}</a>{% endif %} | <a href="/topics/user/{{ r.topic.person.user }}/{{ r.topic.slug }}/topic-resource/delete/{{ r.id }}/">Delete</a> <a href="/topics/user/{{ r.topic.person.user }}/{{ r.topic.slug }}/topic-resource/edit/{{ r.id }}/">Edit</a> {{ r.note|markdown }}</span> </li> The html string that is returned is the template without any variables inserted. A: Model method 'save' doesn't return an object. So you 'objs' variable is empty. You should write html = render_to_string('includes/tr_inc.html',{"r":obj, "topic":topic}) A: I had exact the same problem today. It is quite easy. Please check the Django document for this method, there is actually a third optional parameter: context_instance=RequestContext(request). Therefore your render_to_string should be like this: html = render_to_string( 'includes/tr_inc.html',{"r":obj, "topic":topic}, context_instance=RequestContext(request)) Then everything should work properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to POST when slider's value is changed/button is pressed with jQuery mobile? I have 1 slider and 1 button: <div data-role="fieldcontain"> <input type="range" name="slider" id="slider" value="0" min="0" max="100" /> </div><br><br> <div data-role="fieldcontain"> <select name="slider" id="slider" data-role="slider"> <option value="off">Off</option> <option value="on">On</option> </select> </div> How can I POST (like form action="http://somesite" method="post"), when slider's value is changed? button is pressed? A: One solution would be to add a custom data attribute that enables the input to auto submit the form it is child of. Format of such an attribute could be: <select name="slider" id="slider" data-role="slider" data-autosubmit="true"> <option value="off">Off</option> <option value="on">On</option> </select> The jQuery code to enable auto submit is as easy as below, but we need to make it a bit more complicated for the slider, see the fiddle sample in the end for that. $('[data-autosubmit="true"]').change(function(){ $(this).parents('form:first').submit(); }); I don't know if you use the native jQuery mobile form handling or a custom one, but if you want to use a custom hook on the submit it could look something like this: $("form").submit(function() { //Handle the submit with a jQuery.post or whatever }); Here is a fiddle with some running sample code: http://jsfiddle.net/4VFgS/1/ The fiddle code got some handling to prevent that you submit the form 100 times per second. A: $('#slider').change(function(){ ... $.post(yoururl, yourdata, function(callbackdata){ ... }); }); See jQuery.post() and jQuery.change() Edit: BTW: Having 2 elements with the same id will likely lead to major problems sooner than later. Edit 2: If you're trying to get a response from a different domain this way, you're probably out of luck unless they offer you JSONP or the like. You will not be able to fetch content from a 3rd party site via XMLHttpRequest because of Same Origin Policy Limitations. You could proxy the request through your server, though, so the AJAX call would go to the same domain.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set password for Redis? I'm working with redis on my local machine so I dont really need to set up a password to connect to the server with my php client (I'm using predis as a client). However, I'm moving my app to a live server, so I want to set up a password to connect to my redis server. I have few questions: * *I checked all over the internet about how to set up the password and it looks like I need to add the password in the redis.conf. I couldnt find though what I should add exactly to the configuration file to set up the password. *also in predis how should I add the password. I'm using the following array of parameters to connect to the redis server $my_server = array('host' => '127.0.0.1','port' => 6379,'database' => 1); should I add the password this way? > $my_server = array('host' => '127.0.0.1','port' => > 6379,'database' => 1,'password'=>password); * *last question, I'm trying to stop my redis-server on the live server. Every time I enter the following command , I keep getting the same error message redis-server stop [23925] 23 Sep 20:23:03 # Fatal error, can't open config file 'stop' usually on my local machine I enter /etc/init.d/redis-server stop to stop redis server but its not working on my live server since there is no process called redis-server in my /etc/init.d A: you can also use following command on client cmd :: config set requirepass p@ss$12E45 above command will set p@ss$12E45 as a redis server password. A: Example: redis 127.0.0.1:6379> AUTH PASSWORD (error) ERR Client sent AUTH, but no password is set redis 127.0.0.1:6379> CONFIG SET requirepass "mypass" OK redis 127.0.0.1:6379> AUTH mypass Ok A: * *stop redis server using below command /etc/init.d/redis-server stop *enter command: sudo nano /etc/redis/redis.conf *find requirepass foobared word and remove # and change foobared to YOUR PASSWORD ex. requirepass root A: On versions prior to REDIS 6 , the only way to secure your REDIS is to open your redis.conf , uncomment the # requirepass line, and add in your password. However , the downside of this is that this is a global password shared by ALL connections. requirepass iampwd Unless you need backwards compatibility you should move to REDIS 6, and instead use ACLs to create users with the least privileges acl setuser dummyuser on >dummypwd allcommands allkeys https://redis.io/topics/acl A: For that, you need to update the redis configuration file.By default, there is no any password for redis. 01) open redis configuration file sudo vi /etc/redis/redis.conf find requirepass field under SECURITY section and uncomment that field.Then set your password instead of "foobared" # requirepass foobared It should be like, requirepass YOUR_PASSWORD Then restart redis and start redis-cli. If you need to check whether you have set the password correctly, you can run below commads in redis-cli. sithara@sithara-X555UJ ~ $ redis-cli 127.0.0.1:6379> set key1 18 (error) NOAUTH Authentication required. 127.0.0.1:6379> auth admin OK 127.0.0.1:6379> get key1 (nil) 127.0.0.1:6379> exit sithara@sithara-X555UJ ~ $ redis-cli 127.0.0.1:6379> set key1 18 (error) NOAUTH Authentication required. 127.0.0.1:6379> auth admin OK 127.0.0.1:6379> set key2 check OK 127.0.0.1:6379> get key2 "check" 127.0.0.1:6379> get key1 (nil) 127.0.0.1:6379> set key1 20 OK 127.0.0.1:6379> get key1 "20" 127.0.0.1:6379> exit ` A: Run Command redis-cli redis 127.0.0.1:6379> AUTH PASSWORD (error) ERR Client sent AUTH, but no password is set redis 127.0.0.1:6379> CONFIG SET requirepass "amolpass" OK redis 127.0.0.1:6379> AUTH amolpass Ok ------------------OR ---------------------- Get Redis Installation Path redis-cli config get dir GET Config File Path sudo find / -name "redis.conf" -exec grep -H "^dir" {} \; 2> /dev/null generate the same password as this one: echo "amol-pass" | sha1sum OUTPUT :960c3dac4fa81b4204779fd16ad7c954f95942876b9c4fb1a255667a9dbe389d Edit : /etc/redis/redis.conf requirepass 960c3dac4fa81b4204779fd16ad7c954f95942876b9c4fb1a255667a9dbe389d Restart Redis service redis-server restart TEST Command : redis-cli set key1 10 (error) NOAUTH Authentication required. auth your_redis_password A: For Mac installed with HomeBrew/Brew (redis-cli): redis-cli AUTH oldpassword CONFIG SET requirepass "newpassword" CONFIG REWRITE Restart: brew services stop redis //relogin A: sudo nano /etc/redis/redis.conf find and uncomment line # requirepass foobared, then restart server now you password is foobared A: using redis-cli: root@server:~# redis-cli 127.0.0.1:6379> CONFIG SET requirepass secret_password OK this will set password temporarily (until redis or server restart) test password: root@server:~# redis-cli 127.0.0.1:6379> AUTH secret_password OK A: For those who use docker-compose, it’s really easy to set a password without any config file like redis.conf. Here’s how you would normally use the official Redis image: redis: image: 'redis:4-alpine' ports: - '6379:6379' And here’s all you need to change to set a custom password: redis: image: 'redis:4-alpine' command: redis-server --requirepass yourpassword ports: - '6379:6379' Everything will start up as normal and your Redis server will be protected by a password. For details, this blog post seems to support the idea. A: i couldnt find though what i should add exactly to the configuration file to set up the password. Configuration file should be located at /etc/redis/redis.conf and password can be set up in SECURITY section which should be located between REPLICATION and LIMITS section. Password setup is done using the requirepass directive. For more information try to look at AUTH command description. A: To set the password, edit your redis.conf file, find this line # requirepass foobared Then uncomment it and change foobared to your password. Make sure you choose something pretty long, 32 characters or so would probably be good, it's easy for an outside user to guess upwards of 150k passwords a second, as the notes in the config file mention. To authenticate with your new password using predis, the syntax you have shown is correct. Just add password as one of the connection parameters. To shut down redis... check in your config file for the pidfile setting, it will probably be pidfile /var/run/redis.pid From the command line, run: cat /var/run/redis.pid That will give you the process id of the running server, then just kill the process using that pid: kill 3832 Update I also wanted to add, you could also make the /etc/init.d/redis-server stop you're used to work on your live server. All those files in /etc/init.d/ are just shell scripts, take the redis-server script off your local server, and copy it to the live server in the same location, and then just look what it does with vi or whatever you like to use, you may need to modify some paths and such, but it should be pretty simple. A: open redis configuration file sudo nano /etc/redis/redis.conf set passphrase replace # requirepass foobared with requirepass YOURPASSPHRASE restart redis redis-server restart A: How to set redis password ? step 1. stop redis server using below command /etc/init.d/redis-server stop step 2.enter command : sudo nano /etc/redis/redis.conf step 3.find # requirepass foobared word and remove # and change foobared to YOUR PASSWORD ex. requirepass root A: If you are losing password on Redis restart and you are running Redis as a windows service then you should set requirepass in redis.windows-service.conf file as well. A: This error means there is no password set in your redis instance. If you send auth information from your code you will probably get this message. There are two ways to solve. * *Open the redis config file. sudo nano /etc/redis/redis.conf You can use 'where is' option to find '# requirepass' Uncomment the passphrase line and set new password # requirepass yourpassword *Open terminal and connect redis-cli redis-cli *Set passphrase CONFIG SET requirepass "yourpassword" *Finally, you can test AUTH yourpassword Thats is!
{ "language": "en", "url": "https://stackoverflow.com/questions/7537905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "140" }
Q: Why output data are not corresponding to it's column in Union All query Here's a piece of the output array(7) { ["type"]=> string(16) "new post comment" ["book_id"]=> string(1) "1" ["name"]=> string(9) "whatever" ["author_id"]=> string(4) "test" ["content"]=> string(19) "2011-07-16 03:20:01" ["create_time"]=> string(1) "3" ["id"]=> string(1) "1" } And this is part of my query SELECT 'bookcomment' AS type ,b.book_id ,b.name ,c.book_id ,c.author_id ,c.content ,c.create_time AS create_time ,u.id ,u.name FROM tbl_book AS b, tbl_book_comment AS c, tbl_user AS u WHERE u.id=c.author_id in (1,2) AND b.book_id=c.book_id UNION ALL SELECT 'new post comment' AS type ,po.post_id ,po.title ,pc.author_id ,pc.content ,pc.create_time AS create_time ,pc.post_id ,u.id ,u.name FROM tbl_post as po, tbl_post_comment as pc, tbl_user as u WHERE u.id=pc.author_id in(1,2) AND po.post_id=pc.post_id UNION ALL SELECT 'bookrating' AS type ,b.book_id as one ,b.name ,ra.book_id ,ra.user_id ,ra.rating ,ra.create_time AS create_time ,u.id ,u.name FROM tbl_book AS b, tbl_user_book_rating AS ra, tbl_user AS u WHERE u.id=ra.user_id in (1,2) AND b.book_id=ra.book_id UNION ALL... ORDER BY create_time DESC As the result shown,data correspond to 'author_id' should have correspond to 'content' and 'content' should be 'create_time'. What's wrong with my query? A: Looks like you've mixed up the order of the columns in the second SELECT. Your columns are like this (first query on the left, second in the middle, third on right): type type type b.book_id po.post_id one b.name po.title b.name c.book_id pc.author_id ra.book_id c.author_id pc.content ra.user_id c.content create_time ra.rating create_time pc.post_id create_time u.id u.id u.id u.name u.name u.name The order gets mixed up at pc.author_id by the look of it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery ~ How to keep moving the object when keydown In JQuery ~ I hope to make a simple character moving, Stop > Left || right. This script make #moveCharacter turn left walk 10px once. How can I keydown keep turn left walking,when keyup stop walking (like a character)?? // Left moving $(document).keydown(function(e){ if (e.keyCode == 37) { $("#moveCharacter").animate({marginLeft: "-=10px"}, {queue:false}); return false; } }); 2.I try to change keypress() but it has not work.....what wrong? var xTriggered = 0; $(document).keypress(function(e){ xTriggered++; if (e.which == '37') { $("#moveCharacter").animate({marginLeft: "-="+xTriggered+"px"}, {queue:false}); return false; } }); A: You want to be using the keypress event instead of keydown. As per the JQuery API: If the user presses and holds a key, a keydown event is triggered once, but separate keypress events are triggered for each inserted character A: May this code will work as you want var xTriggered = 0; $(document).keydown(function(e){ xTriggered++; if (e.which == '37') { $("#moveCharacter").animate({marginLeft: "-="+xTriggered+"px"}, {queue:false}); return false; } //EDIT $(document).keydown(function(e) { if(e.keyCode == 37) { // left $("#moveCharacter").animate({ marginLeft: "-=10"}); } }); $(document).keyup(function(e) { $("#moveCharacter").queue("fx", []); $("#moveCharacter").stop(); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7537918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SWI Prolog interpret/compile from command line I am using Windows, and i want to interpret/compile a prolog file with cmd, is any method to do that?. The purpose is to make a shell to the interpreter/compiler prolog to a file like: gplc -output C:\a.output -input C:\a.pl And in the output file to be the answers for my goals. I had read some documentation for swi-prolog.com and I didn't find. I had tried with GNU Prolog(and it raise me an error for gcc) I have this file D:\a.pl mouther(john). jiji(ok). ?- jiji(ok). in CMD I run swipl -s D:\a.pl -o D:\a2.txt And I want in a2 the answers for my goals, but it isn't. A: I cannot check it right now but you could start out with something like swipl -s file.pl -g "mygoal(3,foo)." -t halt. This would consult file.pl, run goal mygoal(3,foo) and then halt the interpreter without entering interactive mode. Check the command line options for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Magento - Magmi PHP errors I'm currently trying to implement Magmi on our Magento setup but getting the following errors on the first Magmi page, this is just going to the first page and not running anything yet (obviously direct path has been replaced in the below info): Notice: require_once() [function.require-once]: 1. h->opened_path=[/path/to/root/magmi/inc/magmi_version.php] h->filename=[/path/to/root/magmi/inc/magmi_version.php] in /path/to/root/magmi/web/head.php on line 5 Notice: require_once() [function.require-once]: apc_cache_find [33623919] in /path/to/root/magmi/web/head.php on line 5 Notice: require_once() [function.require-once]: 1. h->opened_path=[/path/to/root/magmi/inc/magmi_config.php] h->filename=[/path/to/root/magmi/inc/magmi_config.php] in /path/to/root/magmi/web/magmi.php on line 2 Notice: require_once() [function.require-once]: apc_cache_find [33623914] in /path/to/root/magmi/web/magmi.php on line 2 Notice: require_once() [function.require-once]: 1. h->opened_path=[/path/to/root/magmi/inc/properties.php] h->filename=[/path/to/root/magmi/inc/properties.php] in /path/to/root/magmi/inc/magmi_config.php on line 2 Notice: require_once() [function.require-once]: apc_cache_find [33623920] in /path/to/root/magmi/inc/magmi_config.php on line 2 Notice: require_once() [function.require-once]: 1. h->opened_path=[/path/to/root/magmi/inc/magmi_statemanager.php] h->filename=[/path/to/root/magmi/inc/magmi_statemanager.php] in /path/to/root/magmi/web/magmi.php on line 3 Notice: require_once() [function.require-once]: apc_cache_find [33623917] in /path/to/root/magmi/web/magmi.php on line 3 Notice: require_once() [function.require-once]: 1. h->opened_path=[/path/to/root/magmi/inc/fshelper.php] h->filename=[/path/to/root/magmi/inc/fshelper.php] in /path/to/root/magmi/web/magmi.php on line 5 Notice: require_once() [function.require-once]: apc_cache_find [33623909] in /path/to/root/magmi/web/magmi.php on line 5 Notice: require_once() [function.require-once]: 1. h->opened_path=[/path/to/root/magmi/web/magmi_web_utils.php] h->filename=[/path/to/root/magmi/web/magmi_web_utils.php] in /path/to/root/magmi/web/magmi.php on line 6 Notice: require_once() [function.require-once]: apc_cache_find [33623950] in /path/to/root/magmi/web/magmi.php on line 6 Notice: require_once() [function.require-once]: 1. h->opened_path=[/path/to/root/magmi/web/magmi_config_setup.php] h->filename=[/path/to/root/magmi/web/magmi_config_setup.php] in /path/to/root/magmi/web/magmi.php on line 26 Notice: require_once() [function.require-once]: apc_cache_find [33623940] in /path/to/root/magmi/web/magmi.php on line 26 Notice: require_once() [function.require-once]: 1. h->opened_path=[/path/to/root/magmi/inc/dbhelper.class.php] h->filename=[/path/to/root/magmi/inc/dbhelper.class.php] in /path/to/root/magmi/web/magmi_config_setup.php on line 4 Notice: require_once() [function.require-once]: apc_cache_find [33623912] in /path/to/root/magmi/web/magmi_config_setup.php on line 4 and so on... Has anyone come across this problem before?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to delete folders in sdcard of file explorer? I created several folders in the sdcard (Eclipse) by running an Android application in the emulator. Now I want to delete the folders which I have created on the sdcard. I am able to delete files in the folders but I could not delete the folders in the sdcard. How can I do this? Is there a way to delete folders? A: Using adb command you can delete folders. click Run - > CMD-> type adb shell --> cd sdcard -> rmdir {dirname} Note : Make sure your dir should be empty. For non-empty directory use. click Run - > CMD-> type adb shell --> cd sdcard -> rm -r {dirname} A: We can do it in a single command line as under: adb shell rm -r sdcard/<dirname> A: Well, answer from Brijesh Thakur is really helpful. I just tried this and it worked fine for me to some extent. I would like to mention that if your directory contains any files then the rmdir command will not work. You will have to use rm -r command for that. To make it more easy for beginners I am explaining the process as follows. * *First you need to locate your adb folder, mine was at D:\Android SDK\platform-tools> *Now execute adb shell in a command prompt as: D:\Android SDK\platform-tools>adb shell *A hash (#) symbol or dollar sign ($) will appear, then enter the following command: # cd sdcard *Now you are in the sdcard of the device. If your folder is a sub folder then further locate its parent folder using the cd command. Finally, use the rm -r command to remove the folder recursively as follows. This will delete all files and directories in the folder. # rm -r FolderName Please note that if you want to remove a single file you can use the rm command only and then the file name (with extension probably). And you can also use rmdir command if the directory you trying to delete is empty. A: Using adb shell with rm command you can delete(nonempty as well as empty) folders. click Run -- > CMD--> type adb shell --> cd sdcard --> rm -r {dirname} A: If you want to delete everything in your android file system, you need to get its storage name from adb! # adb shell echo $EXTERNAL_STORAGE It will give you the path where everything is stored!It will print the storage name in command line, for few devices it is /sdcard and for few, it is /storage/emulated/legacy etc Now you want to delete everything in that, you need # adb shell rm -r /sdcard/ that /sdcard/ is not same for all devices, it could be /storage/emulated/legacy/ for some devices! warning-: It will delete every folder in your file manager except "android" folder now if you want to delete a particular folder in that file manager # adb shell rm -r /sdcard/FolderName A: * *remount the sdcard with read and write permission: adb shell mount -o remount,rw / *Go to adb shell: adb shell *Delete file you want: rm -r /sdcard/file_name It will work most better.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Get line which contains string I'm trying to get a line from a textfile that contains a certain sequence of characters : my input : <tr><td>lucas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> </tr> <tr><td>jeanpierre.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span title="Cannot connect to 193.191.187.25:22345." style="color:red;font-weight:bold">X</span></td> <td><span title="No response from DNS at 193.191.187.25." style="color:red;font-weight:bold">X</span></td> </tr> <tr><td>sofie.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span title="Cannot connect to 193.191.187.26:22345." style="color:red;font-weight:bold">X</span></td> <td><span title="No response from DNS at 193.191.187.26." style="color:red;font-weight:bold">X</span></td> </tr> <tr><td>thomas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> </tr> Now I need to get the line that contains lucas, I tried this with beautifulsoup, but it is not meant to get a line only content of html tags, so I tried with a regular in operator : def soupParserToTable(self,input): global header soup = self.BeautifulSoup(input) header = soup.first('tr') tableInput='0' for line in input: if 'lucas' in line: tableInput = line print tableInput However it keeps returning 0 instead of <tr><td>lucas.vlan77.be</td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> <td><span style="color:green;font-weight:bold">V</span></td> </tr> A: If input is just a string, then for line in input doesn't iterate lines, it iterates characters. So 'lucas' would never be found in a one-character string and tableInput would not be assigned. The line-based iteration behaviour only happens when the object is a file. If you wanted to loop through each line of a string you'd have to do: for line in input.split('\n'): ... Since you have BeautifulSoup available I'd say it would be much better to use that to read the value from the first cell in each row, rather than rely on crude and fragile string-searching. ETA: how I would get the table entry for the row that contains the string 'lucas' any hints ? Use td.parent to get the containing row, td.parent.parent to get the containing table/tbody, and so on. If you wanted to get the V or X in the next column, you could say something like: tr= soup.find(text= re.compile('lucas')).parent.parent vorx= tr.findAll('td')[1].find('span').string
{ "language": "en", "url": "https://stackoverflow.com/questions/7537932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fast scanning of SD card on Android I am trying to write an algorithm for fastest scanning of whole SD card. What I try to achieve is something in the line with QuickPic, which has "normal speed" initial scanning of SD card, but any subsequent refresh is incredibly fast. I have tried several things, and I have some more ideas which I have not tested 1) Always scan entires SD card. I tried this...it's a bit slower on initial scan. but all subsequent scans are faster, but not as fast as QucikPic. 2) After initial scan add FileObserver to all folders. Although it only increases memory of application by approximately 1 MB, I am afraid this will affect performance or even drain battery, since it must run all the time. Also, I have database on SD card and I am constantly getting events for journal file being created/deleted. I am sure when working with other apps there will be other folders/files for which I will get constant notification. Not sure this is OK performance wise. 3) Using data from MediaStore. Unfortunately it seems that on my HTC Desire Media store is not always up to date with what's on SD card (not sure why), but that's not good enough. 3) Using ContentObserver. Haven't tried this yet, and must check documentation, but I have a feeling that if MediaStore doesn't have an image in it's DB, then I won't get it from ContentObserver either. Do you guys have any other suggestion? Basically what I need is to know about all image files on SD card at some point. Initial scan can take a bit longer, subsequent scans should be as fast as possible (I know it depends on number of folders/files on SD card) but QuickPic scans (or whatever it does) entire SD card in about 0.6-0.8 seconds, and I just can't do it that fast. A: Bona fide apps like QuickPic are undoubtedly using the MediaStore for their source. Here is an example that finds all the external image files in the MediaStore and their thumbnails. Note that the DATA column in the MediaStore refers to the file's full path. import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.provider.MediaStore; import androidx.loader.content.CursorLoader; import java.io.IOException; import java.util.ArrayList; class ImageFileInfo { ImageFileInfo(String fileFullPath, Bitmap image, Bitmap thumbnail) { this.fileFullPath = fileFullPath; this.image = image; this.thumbnail = thumbnail; } String fileFullPath; Bitmap image; Bitmap thumbnail; } public class GetImageInfos { static ArrayList<ImageFileInfo> getImageInfos(Context context) { ArrayList<ImageFileInfo> list = new ArrayList<>(); final String[] cols = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA }; CursorLoader loader = new CursorLoader(context); loader.setUri(MediaStore.Images.Media.EXTERNAL_CONTENT_URI); loader.setProjection(cols); loader.setSelection(null); loader.setSortOrder(MediaStore.Images.Media.DATA); Cursor cursor = loader.loadInBackground(); ContentResolver resolver = context.getContentResolver(); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); int imagePathCol = cursor.getColumnIndex(MediaStore.Images.Media.DATA); String imagePath = cursor.getString(imagePathCol); int imageIdCol = cursor.getColumnIndex(MediaStore.Images.Media._ID); int imageId = cursor.getInt(imageIdCol); Bitmap image = BitmapFactory.decodeFile(imagePath); Bitmap thumb = MediaStore.Images.Thumbnails.getThumbnail( resolver, imageId, MediaStore.Images.Thumbnails.MINI_KIND, null); list.add(new ImageFileInfo(imagePath, image, thumb)); } return list; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to implement Network Triangulation? I am developing an application in android 2.2 to identify location of user by Network: 1) First: location= (GsmCellLocation)tm.getCellLocation(); cellId= location.getCid(); lac= location.getLac(); 2) Second wonder "http://www.google.com/glm/mmap" to get latitude and longitude and range. 3) Third I repeat this step three times to obtain information from three different cells How can I implement the triangulation? It is possible to perform a mapping between latitude/longitude and xy co-ordinates? A: I think I've solved it... many thanks. * *I have converted coordinates into radians. *I have changed the latitude/longitude (in radians) to ECEF xyz. *I've done some math to calculate the intersection of three circles. *I've re-converted the coordinates of this intersection, from ECEF to latitude & longitude and subsequently to degrees. A: You do linear interpolation with the vertices of the triangle you got.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Generate all ways of selection of n items Possible Duplicate: How to find all possible subsets of a given array? How can all ways of selection of items be generated efficiently using C++? For example, if there are there items A, B and C. [A,B,C] => [A], [B], [C], [A,B], [B,C], [A,C], [A, B, C] A: Essentially, you can break the problem down into: "For each item, will it be part of the set or not". If you can find all combinations of that then you can find all possible ways of selecting items. A way of representing whether an item is in the set or not is with a Boolean. True or 1 if it is in the set and false or 0 if it isn't. So we need a Boolean for each of the items. This brings to mind an int or another type as they are all essentially, a bunch of bits. Now how can we find all combinations of those booleans. There is a simple answer: loop through all the integers. For example: ABCD Number in base 10 0000 0 0001 1 0010 2 0011 3 0100 4 .... ... 1111 (2^4) - 1 We know there are 2^4 answer since each item can be in the set or not in the set so there are 2 possibilities for each item. If there are 4 element then there are 2*2*2*2 or 2^4 combinations. There's also an easy way to find 2^n. Simply doing 1 << n. This leads us to the simple answer: for (int i = 0; i < (1 << n); i++) { // Here the ath bit of i will be set if the ath item is part of the set } Note that this will include the empty set, ie [ ]. If you don't want this, simply start the loop from 1 instead of 0. Hope this helps. A: For that input set: #include <iostream> void print(int b, char *a, int n) { for(int i = 0 ; i < n ; i++) { if( b & 0x1) std::cout << a[i]; b = b >> 1; } std::cout << std::endl; } int main() { char a[] = {'A','B','C'}; for(int i = 1 ; i < 8 ; i++ ) print(i,a,3); return 0; } Output: A B AB C AC BC ABC Demo : http://ideone.com/2Wxbi Now it's your turn to improve and generalize this approach, and find it's limitations. A: If you have N elements (here N=3), then iterate i from 1 to (1<<3) and in each iteration look at binary value of i.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SelectedValue property for a Autocomplete User Control First off, forgive my English, my attempt, I am creating a autocomplete user control, to replace drop downs, I have created the user control, and its working fine. Now for simplicity sake, I need to provide a public property in my User Control to get the selected id, similar to the SelectedValue of the DropDrown control. I'm stuck with this, any ideas will be appreciated. Hi My Code UserControl.ascx <%@ Control Language="C#" AutoEventWireup="true" Code File="UserControl.ascx.cs" Inherits="UserControl" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> function DispValue(sender, e) { alert(e.get_value() + " : user control"); document.getElementById(hiddenFieldName.Client ID).value = e.get_value(); } UserControl.ascx.cs public partial class UserControl : System.Web.UI.UserControl { protected void page_load(object sender, EventArgs e) { ACEName.ContextKey = "1"; } public String SelectedValue { get { return this.hdnValue.Value; } } public String SelectedText { get { return this.Name.Text; } } } MyAspxPage.aspx <%@ Register Src="~/UserControl.ascx" TagPrefix="puc" TagName="UserControl" %> Patient Name MyAspxPage.cs DataTable dt; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { dt = new DataTable(); dt.Columns.Add("col1"); dt.Columns.Add("col2"); dt.Columns.Add("col3"); dt.Columns.Add("col4"); dt.Columns.Add("col5"); dt.Columns.Add("col6"); if (Session["dt"] == null) { dt = AddRow(dt); gvPatient.DataSource = dt; gvPatient.DataBind(); Session["dt"] = dt; //ViewState["dt"] = dt; } else dt = (DataTable)Session["dt"];//ViewState["dt"]; } } private DataTable AddRow(DataTable dt) { for (int i = 0; i < 5; i++) { DataRow dr = dt.NewRow(); dr[0] = ""; dr[1] = ""; dr[2] = ""; dr[3] = ""; dr[4] = ""; dr[5] = ""; dt.Rows.Add(dr); } return dt; } protected void GridPatient_DataBound(object sender, EventArgs e) { foreach (GridViewRow item in gvPatient.Rows) { UserControl ptuc = (UserControl)item.FindControl("pucPatient1"); string id = ptuc.SelectedValue; } } public void Save(object sender, EventArgs e) { foreach (GridViewRow item in gvPatient.Rows) { if (item.RowType == DataControlRowType.DataRow) { UserControl ptuc = (UserControl)item.FindControl("pucPatient1"); string id = ptuc.SelectedValue;//getting null value. string patientName = ptuc.SelectedText; } } } this is all what i did. Thanking You, cheers Sharanamma. A: Probably you are using the TextBox control in background for your Autocomplete. So, define the SelectedValue as following: public string SelectedValue { get { return this.textBox.Text; } } Or if you need the ID of the selected value, not display text, then place HiddenField near your TextBox and populate the ID of selected value from autocomlete using JavaScript. And the use it on the server side: public string SelectedValue { get { return this.hiddenField.Text; } } A: you can use findcontrol() in gridview's RowDataBound Event. May be it can helps you to find values of hidden field
{ "language": "en", "url": "https://stackoverflow.com/questions/7537949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Documents/Inbox folder for opening file from another App I registered my app to associate some filetypes. so when the file comes in the mail attachment, I use my app to open the file. My app will automatically create a "Inbox" folder inside my Documents folder, and save the file in "Inbox". This Inbox is special, because it prevents me to create a folder or move a file into it by program. Question comes to me is: * *What is the special for the "Inbox"? Can I change some setting, and it will allow me to create a subfolder inside? *What is normal solution for this? Thanks Cullen A: Inbox is just a link to your email stuff. You should copy the files from there to your documents directory withNSFileManager.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jqGrid set cells data while inline edit active I think it's a stupid question but I can not find a solution. I created a table with jqGrid and I enabled inline editing On each line I added a button that enables or disables editing I wanted to add a second button active only during editing that would allow you to load the default values ​​in the various fields of active inline edit row. I do not know how to access and change data row while editing setRowData work well if row i selected but not in inline edit mode Anyone have any suggestions, thanks. Update I have found a (bad I think) solution but explain my problem: if (edit_enabled) { // save current data jQuery('#SEQtbl').jqGrid('saveRow',row_edit, false, 'clientArray'); // read back row data var row = jQuery("#SEQtbl").jqGrid('getRowData',row_edit); // change something .... ..... // save data jQuery("#SEQtbl").jqGrid('setRowData',row_edit, row); // reneter row edit mode jQuery('#SEQtbl').jqGrid('editRow', row_edit,true); } ` A: I think you've already got your answer in the code you posted. According to the jqGrid documentation for setRowData "Do not use this method when you editing the row or cell. This will set content and and overwrite the input elements". Basically, when you call setRowData or getRowData on a row that is in edit mode, you get/set the HTML of the row, not the data. I'm not sure of what your requirements are, but it may be a better UI solution to have the "set default values" button active at the same time as the enable/disable edit buttons. The user can click "set defaults", and it will set the defaults, then enter edit mode. I don't quite understand why you have this "set defaults" button to begin with. Shouldn't the defaults be loaded when the new row is added? Or is it the case that your users may want to reset a row that already has data back to the default values?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In Java, how can I create an equivalent of an Apache Avro container file without being forced to use a File as a medium? This is somewhat of a shot in the dark in case anyone savvy with the Java implementation of Apache Avro is reading this. My high-level objective is to have some way to transmit some series of avro data over the network (let's just say HTTP for example, but the particular protocol is not that important for this purpose). In my context I have a HttpServletResponse I need to write this data to somehow. I initially attempted to write the data as what amounted to a virtual version of an avro container file (suppose that "response" is of type HttpServletResponse): response.setContentType("application/octet-stream"); response.setHeader("Content-transfer-encoding", "binary"); ServletOutputStream outStream = response.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(outStream); Schema someSchema = Schema.parse(".....some valid avro schema...."); GenericRecord someRecord = new GenericData.Record(someSchema); someRecord.put("somefield", someData); ... GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(someSchema); DataFileWriter<GenericRecord> fileWriter = new DataFileWriter<GenericRecord>(datumWriter); fileWriter.create(someSchema, bos); fileWriter.append(someRecord); fileWriter.close(); bos.flush(); This was all fine and dandy, except that it turns out Avro doesn't really provide a way to read a container file apart from an actual file: the DataFileReader only has two constructors: public DataFileReader(File file, DatumReader<D> reader); and public DataFileReader(SeekableInput sin, DatumReader<D> reader); where SeekableInput is some avro-specific customized form whose creation also ends up reading from a file. Now given that, unless there is some way to somehow coerce an InputStream into a File (http://stackoverflow.com/questions/578305/create-a-java-file-object-or-equivalent-using-a-byte-array-in-memory-without-a suggests that there is not, and I have tried looking around the Java documentation as well), this approach won't work if the reader on the other end of the OutputStream receives that avro container file (I'm not sure why they allowed one to output avro binary container files to an arbitrary OutputStream without providing a way to read them from the corresponding InputStream on the other end, but that's beside the point). It seems that the implementation of the container file reader requires the "seekable" functionality that a concrete File provides. Okay, so it doesn't look like that approach will do what I want. How about creating a JSON response that mimics the avro container file? public static Schema WRAPPER_SCHEMA = Schema.parse( "{\"type\": \"record\", " + "\"name\": \"AvroContainer\", " + "\"doc\": \"a JSON avro container file\", " + "\"namespace\": \"org.bar.foo\", " + "\"fields\": [" + "{\"name\": \"schema\", \"type\": \"string\", \"doc\": \"schema representing the included data\"}, " + "{\"name\": \"data\", \"type\": \"bytes\", \"doc\": \"packet of data represented by the schema\"}]}" ); I'm not sure if this is the best way to approach this given the above constraints, but it looks like this might do the trick. I'll put the schema (of "Schema someSchema" from above, for instance) as a String inside the "schema" field, and then put in the avro-binary-serialized form of a record fitting that schema (ie. "GenericRecord someRecord") inside the "data" field. I actually wanted to know about a specific detail of that which is described below, but I thought it would be worthwhile to give a bigger context as well, so that if there is a better high-level approach I could be taking (this approach works but just doesn't feel optimal) please do let me know. My question is, assuming I go with this JSON-based approach, how do I write the avro binary representation of my Record into the "data" field of the AvroContainer schema? For example, I got up to here: ByteArrayOutputStream baos = new ByteArrayOutputStream(); GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(someSchema); Encoder e = new BinaryEncoder(baos); datumWriter.write(resultsRecord, e); e.flush(); GenericRecord someRecord = new GenericData.Record(someSchema); someRecord.put("schema", someSchema.toString()); someRecord.put("data", ByteBuffer.wrap(baos.toByteArray())); datumWriter = new GenericDatumWriter<GenericRecord>(WRAPPER_SCHEMA); JsonGenerator jsonGenerator = new JsonFactory().createJsonGenerator(baos, JsonEncoding.UTF8); e = new JsonEncoder(WRAPPER_SCHEMA, jsonGenerator); datumWriter.write(someRecord, e); e.flush(); PrintWriter printWriter = response.getWriter(); // recall that response is the HttpServletResponse response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); printWriter.print(baos.toString("UTF-8")); I initially tried omitting the ByteBuffer.wrap clause, but then then the line datumWriter.write(someRecord, e); threw an exception that I couldn't cast a byte array into ByteBuffer. Fair enough, it looks like when the Encoder class (of which JsonEncoder is a subclass) is called to write an avro Bytes object, it requires a ByteBuffer to be given as an argument. Thus, I tried encapsulating the byte[] with java.nio.ByteBuffer.wrap, but when the data was printed out, it was printed as a straight series of bytes, without being passed through the avro hexadecimal representation: "data": {"bytes": ".....some gibberish other than the expected format...} That doesn't seem right. According to the avro documentation, the example bytes object they give says that I need to put in a json object, an example of which looks like "\u00FF", and what I have put in there is clearly not of that format. What I now want to know is the following: * *What is an example of an avro bytes format? Does it look something like "\uDEADBEEFDEADBEEF..."? *How do I coerce my binary avro data (as output by the BinaryEncoder into a byte[] array) into a format that I can stick into the GenericRecord object and have it print correctly in JSON? For example, I want an Object DATA for which I can call on some GenericRecord "someRecord.put("data", DATA);" with my avro serialized data inside? *How would I then read that data back into a byte array on the other (consumer) end, when it is given the text JSON representation and wants to recreate the GenericRecord as represented by the AvroContainer-format JSON? *(reiterating the question from before) Is there a better way I could be doing all this? A: As Knut said, if you want to use something other than a file, you can either: * *use SeekableByteArrayInput, as Knut said, for anything you can shoe-horn into a byte array *Implement SeekablInput in your own way - for example if you were getting it out of some weird database structure. *Or just use a file. Why not? Those are your answers. A: The way I solved this was to ship the schemas separately from the data. I set up a connection handshake that transmits the schemas down from the server, then I send encoded data back and forth. You have to create an outside wrapper object like this: {'name':'Wrapper','type':'record','fields':[ {'name':'schemaName','type':'string'}, {'name':'records','type':{'type':'array','items':'bytes'}} ]} Where you first encode your array of records, one by one, into an array of encoded byte arrays. Everything in one array should have the same schema. Then you encode the wrapper object with the above schema -- set "schemaName" to be the name of the schema you used to encode the array. On the server, you will decode the wrapper object first. Once you decode the wrapper object, you know the schemaName, and you have an array of objects you know how to decode -- use as you will! Note that you can get away without using the wrapper object if you use a protocol like WebSockets and an engine like Socket.IO (for Node.js) Socket.io gives you a channel-based communication layer between browser and server. In that case, just use a specific schema for each channel, encode each message before you send it. You still have to share the schemas when the connection initiates -- but if you are using WebSockets this is easy to implement. And when you are done you have an arbitrary number of strongly-typed, bidirectional streams between client and server. A: Under Java and Scala, we tried using inception via code generated using the Scala nitro codegen. Inception is how the Javascript mtth/avsc library solved this problem. However, we ran into several serialization problems using the Java library where there were erroneous bytes being injected into the byte stream, consistently - and we could not figure out where those bytes were coming from. Of course that meant building our own implementation of Varint with ZigZag encoding. Meh. Here it is: package com.terradatum.query import java.io.ByteArrayOutputStream import java.nio.ByteBuffer import java.security.MessageDigest import java.util.UUID import akka.actor.ActorSystem import akka.stream.stage._ import akka.stream.{Attributes, FlowShape, Inlet, Outlet} import com.nitro.scalaAvro.runtime.GeneratedMessage import com.terradatum.diagnostics.AkkaLogging import org.apache.avro.Schema import org.apache.avro.generic.{GenericDatumWriter, GenericRecord} import org.apache.avro.io.EncoderFactory import org.elasticsearch.search.SearchHit import scala.collection.mutable.ArrayBuffer import scala.reflect.ClassTag /* * The original implementation of this helper relied exclusively on using the Header Avro record and inception to create * the header. That didn't work for us because somehow erroneous bytes were injected into the output. * * Specifically: * 1. 0x08 prepended to the magic * 2. 0x0020 between the header and the sync marker * * Rather than continue to spend a large number of hours trying to troubleshoot why the Avro library was producing such * erroneous output, we build the Avro Container File using a combination of our own code and Avro library code. * * This means that Terradatum code is responsible for the Avro Container File header (including magic, file metadata and * sync marker) and building the blocks. We only use the Avro library code to build the binary encoding of the Avro * records. * * @see https://avro.apache.org/docs/1.8.1/spec.html#Object+Container+Files */ object AvroContainerFileHelpers { val magic: ByteBuffer = { val magicBytes = "Obj".getBytes ++ Array[Byte](1.toByte) val mg = ByteBuffer.allocate(magicBytes.length).put(magicBytes) mg.position(0) mg } def makeSyncMarker(): Array[Byte] = { val digester = MessageDigest.getInstance("MD5") digester.update(s"${UUID.randomUUID}@${System.currentTimeMillis()}".getBytes) val marker = ByteBuffer.allocate(16).put(digester.digest()).compact() marker.position(0) marker.array() } /* * Note that other implementations of avro container files, such as the javascript library * mtth/avsc uses "inception" to encode the header, that is, a datum following a header * schema should produce valid headers. We originally had attempted to do the same but for * an unknown reason two bytes wore being inserted into our header, one at the very beginning * of the header before the MAGIC marker, and one right before the syncmarker of the header. * We were unable to determine why this wasn't working, and so this solution was used instead * where the record/map is encoded per the avro spec manually without the use of "inception." */ def header(schema: Schema, syncMarker: Array[Byte]): Array[Byte] = { def avroMap(map: Map[String, ByteBuffer]): Array[Byte] = { val mapBytes = map.flatMap { case (k, vBuff) => val v = vBuff.array() val byteStr = k.getBytes() Varint.encodeLong(byteStr.length) ++ byteStr ++ Varint.encodeLong(v.length) ++ v } Varint.encodeLong(map.size.toLong) ++ mapBytes ++ Varint.encodeLong(0) } val schemaBytes = schema.toString.getBytes val schemaBuffer = ByteBuffer.allocate(schemaBytes.length).put(schemaBytes) schemaBuffer.position(0) val metadata = Map("avro.schema" -> schemaBuffer) magic.array() ++ avroMap(metadata) ++ syncMarker } def block(binaryRecords: Seq[Array[Byte]], syncMarker: Array[Byte]): Array[Byte] = { val countBytes = Varint.encodeLong(binaryRecords.length.toLong) val sizeBytes = Varint.encodeLong(binaryRecords.foldLeft(0)(_+_.length).toLong) val buff: ArrayBuffer[Byte] = new scala.collection.mutable.ArrayBuffer[Byte]() buff.append(countBytes:_*) buff.append(sizeBytes:_*) binaryRecords.foreach { rec => buff.append(rec:_*) } buff.append(syncMarker:_*) buff.toArray } def encodeBlock[T](schema: Schema, records: Seq[GenericRecord], syncMarker: Array[Byte]): Array[Byte] = { //block(records.map(encodeRecord(schema, _)), syncMarker) val writer = new GenericDatumWriter[GenericRecord](schema) val out = new ByteArrayOutputStream() val binaryEncoder = EncoderFactory.get().binaryEncoder(out, null) records.foreach(record => writer.write(record, binaryEncoder)) binaryEncoder.flush() val flattenedRecords = out.toByteArray out.close() val buff: ArrayBuffer[Byte] = new scala.collection.mutable.ArrayBuffer[Byte]() val countBytes = Varint.encodeLong(records.length.toLong) val sizeBytes = Varint.encodeLong(flattenedRecords.length.toLong) buff.append(countBytes:_*) buff.append(sizeBytes:_*) buff.append(flattenedRecords:_*) buff.append(syncMarker:_*) buff.toArray } def encodeRecord[R <: GeneratedMessage with com.nitro.scalaAvro.runtime.Message[R]: ClassTag]( entity: R ): Array[Byte] = encodeRecord(entity.companion.schema, entity.toMutable) def encodeRecord(schema: Schema, record: GenericRecord): Array[Byte] = { val writer = new GenericDatumWriter[GenericRecord](schema) val out = new ByteArrayOutputStream() val binaryEncoder = EncoderFactory.get().binaryEncoder(out, null) writer.write(record, binaryEncoder) binaryEncoder.flush() val bytes = out.toByteArray out.close() bytes } } /** * Encoding of integers with variable-length encoding. * * The avro specification uses a variable length encoding for integers and longs. * If the most significant bit in a integer or long byte is 0 then it knows that no * more bytes are needed, if the most significant bit is 1 then it knows that at least one * more byte is needed. In signed ints and longs the most significant bit is traditionally * used to represent the sign of the integer or long, but for us it's used to encode whether * more bytes are needed. To get around this limitation we zig-zag through whole numbers such that * negatives are odd numbers and positives are even numbers: * * i.e. -1, -2, -3 would be encoded as 1, 3, 5, and so on * while 1, 2, 3 would be encoded as 2, 4, 6, and so on. * * More information is available in the avro specification here: * @see http://lucene.apache.org/core/3_5_0/fileformats.html#VInt * https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types */ object Varint { import scala.collection.mutable def encodeLong(longVal: Long): Array[Byte] = { val buff = new ArrayBuffer[Byte]() Varint.zigZagSignedLong(longVal, buff) buff.toArray[Byte] } def encodeInt(intVal: Int): Array[Byte] = { val buff = new ArrayBuffer[Byte]() Varint.zigZagSignedInt(intVal, buff) buff.toArray[Byte] } def zigZagSignedLong[T <: mutable.Buffer[Byte]](x: Long, dest: T): Unit = { // sign to even/odd mapping: http://code.google.com/apis/protocolbuffers/docs/encoding.html#types writeUnsignedLong((x << 1) ^ (x >> 63), dest) } def writeUnsignedLong[T <: mutable.Buffer[Byte]](v: Long, dest: T): Unit = { var x = v while ((x & 0xFFFFFFFFFFFFFF80L) != 0L) { dest += ((x & 0x7F) | 0x80).toByte x >>>= 7 } dest += (x & 0x7F).toByte } def zigZagSignedInt[T <: mutable.Buffer[Byte]](x: Int, dest: T): Unit = { writeUnsignedInt((x << 1) ^ (x >> 31), dest) } def writeUnsignedInt[T <: mutable.Buffer[Byte]](v: Int, dest: T): Unit = { var x = v while ((x & 0xFFFFF80) != 0L) { dest += ((x & 0x7F) | 0x80).toByte x >>>= 7 } dest += (x & 0x7F).toByte } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7537959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Default non indexer properties in C# How can you create a default - non indexer - property in C#? What I mean by this is I can see that I can create indexer default properties as illustrated on this MSDN page. This allows me to do things like Widgets widgets = new Widgets(); Widget result = widgets[1]; But what if I want to achieve something like what Nullable<T> does? Where you can take Nullable<decimal> nullDec = 1.23m; decimal result = nullDec.Value; OR decimal result = (decimal)nullDec; Which I assume is simply a default property implementation to nullDec.Value??? A: Nullable<T> has special handling in the compiler, but you can do most of that by adding implicit or explicit static conversion operators. For example, for type Foo you can add an operator: public static implicit operator string(Foo value) { return "abc"; } public static implicit operator Foo(int value) { ... } allowing: Foo foo = .. string s = foo; // uses string(Foo value) and int i = 123; Foo foo = i; // uses Foo(int value) A: If you inspect the code of Nullable{T} you will see that the explicit cast implementation is like this: public static explicit operator T(Nullable<T> value) { return &value.Value; } So yes you are right. A: The way Nullable<T> does it is by providing an explicit conversion operator to T. So perhaps you are looking for something like: public static explicit operator Widget(Widgets widgets) { // Argument checks here. return widgets[0]; } which would let you do: Widgets widgets = .. Widget firstWidget = (Widget)widgets; This does look like a really dodgy and unintuitive API to me so I don't recommend doing this at all. Why not just stick to standard indexers? A: Not very sure if I correct understant what you're asking for. Wouldn't be enough to implement cast operators on returning type to achieve what you want? If it's not what you intend, please explain. A: Such kind of features are compiler syntactic sugar (in IL code they all are converted to same low level code), so basically it won't be possible to do this without modifying the C# compiler source.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what is the corresponding matplotlib code of this matlab code I'm trying to go away from matlab and use python + matplotlib instead. However, I haven't really figured out what the matplotlib equivalent of matlab 'handles' is. So here's some matlab code where I return the handles so that I can change certain properties. What is the exact equivalent of this code using matplotlib? I very often use the 'Tag' property of handles in matlab and use 'findobj' with it. Can this be done with matplotlib as well? % create figure and return figure handle h = figure(); % add a plot and tag it so we can find the handle later plot(1:10, 1:10, 'Tag', 'dummy') % add a legend my_legend = legend('a line') % change figure name set(h, 'name', 'myfigure') % find current axes my_axis = gca(); % change xlimits set(my_axis, 'XLim', [0 5]) % find the plot object generated above and modify YData set(findobj('Tag', 'dummy'), 'YData', repmat(10, 1, 10)) A: There is a findobj method is matplotlib too: import matplotlib.pyplot as plt import numpy as np h = plt.figure() plt.plot(range(1,11), range(1,11), gid='dummy') my_legend = plt.legend(['a line']) plt.title('myfigure') # not sure if this is the same as set(h, 'name', 'myfigure') my_axis = plt.gca() my_axis.set_xlim(0,5) for p in set(h.findobj(lambda x: x.get_gid()=='dummy')): p.set_ydata(np.ones(10)*10.0) plt.show() Note that the gid parameter in plt.plot is usually used by matplotlib (only) when the backend is set to 'svg'. It use the gid as the id attribute to some grouping elements (like line2d, patch, text). A: I have not used matlab but I think this is what you want import matplotlib import matplotlib.pyplot as plt x = [1,3,4,5,6] y = [1,9,16,25,36] fig = plt.figure() ax = fig.add_subplot(111) # add a plot ax.set_title('y = x^2') line1, = ax.plot(x, y, 'o-') #x1,y1 are lists(equal size) line1.set_ydata(y2) #Use this to modify Ydata plt.show() Of course, this is just a basic plot, there is more to it.Go though this to find the graph you want and view its source code. A: # create figure and return figure handle h = figure() # add a plot but tagging like matlab is not available here. But you can # set one of the attributes to find it later. url seems harmless to modify. # plot() returns a list of Line2D instances which you can store in a variable p = plot(arange(1,11), arange(1,11), url='my_tag') # add a legend my_legend = legend(p,('a line',)) # you could also do # p = plot(arange(1,11), arange(1,11), label='a line', url='my_tag') # legend() # or # p[0].set_label('a line') # legend() # change figure name: not sure what this is for. # set(h, 'name', 'myfigure') # find current axes my_axis = gca() # change xlimits my_axis.set_xlim(0, 5) # You could compress the above two lines of code into: # xlim(start, end) # find the plot object generated above and modify YData # findobj in matplotlib needs you to write a boolean function to # match selection criteria. # Here we use a lambda function to return only Line2D objects # with the url property set to 'my_tag' q = h.findobj(lambda x: isinstance(x, Line2D) and x.get_url() == 'my_tag') # findobj returns duplicate objects in the list. We can take the first entry. q[0].set_ydata(ones(10)*10.0) # now refresh the figure draw()
{ "language": "en", "url": "https://stackoverflow.com/questions/7537967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: backup/restore from-to Gmail? I would like to implement in my app, written in Lua,the option to save a backup file to Gmail and restore it from there. I just need how to save one file and restore that from the same account again. Several apps use that feature now ( i guess using the Gmail as HD Feature). Any ideas? I could read also PHP, Object-C and Java sources if you have nothing in Lua :) I searched for infos in the net, but did not found a single demo source. A: A google search turned up these IMAP clients: * *luaimap *imapfilter And from the Lua mailing list * *limap
{ "language": "en", "url": "https://stackoverflow.com/questions/7537969", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to schedule tests and store the tests reports? I have a few integration tests (java classes), which test a server application. (the tests just send requests, receive responses and verify them). Now I would like to run the tests periodically (e.g. nightly), store the test reports somehow in a database, and run queries like "which tests failed against build #xxx". Should I use Jenkins? Is there any other open source java software for this task? Is there any web service, which can run my integration tests against my server and store the reports in a database? A: Neither Jenkins nor CruiseControl store your test results in a database. But Jenkins does store the test results of your builds, and displays some graphs where you can see how the test results evolve over time. Also Jenkins can tell since how many builds a test has been broken and similar information. You can take a look on the Jenkins of the Jenkins project, here is a project where you can see some tests failing. A: You can use Cruisecontrol, similiar to jenkins. But if you are running just a script, you can have it executed with periodically with windows schedular or cron jobs. A: Use Jenkins for test scheduling and report creation , Maven (surefire) and TestNG for definition and running the tests - works well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Record voice and save it to mp3 file Is it possible to record (5 seconds) a voice with the microphone and save it as a mp3 file WITHOUT sending data to the server? I would like to save the file with FileReference (some times ago I did an experiment saving a bitmap and it worked). A: You can use MicRecorder class for recording the sound, and as3lameencoder for encoding the recorded byte stream into mp3.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why to use Spring not JSF (Advantages of spring over JSF)? i don't know JSF very well, and i have a friend who is using only JSF and he asked me a very open question, why do you use spring not jsf ? and because of there are a lot of things about spring in my mind i wasn't able to give some straight answers so what are the advantages of spring over JSF ? A: Spring and JSF are quite a different frameworks. JSF is more of a web application framework and you can still use spring with JSF to manage the relationship and creations of the objects. Spring is more of an entire j2ee application framework/plaform. Spring MVC and web flow will help you to design web applications similar to JSF. But spring with its IOC concept also brings a lot of other modules such as dependency injection, aop, DAO, ORM, integration, batch and social tools and much more. You can also check the JSF-Spring combination - http://www.springsource.org/node/422 A: JSF is presentation layer, Spring business layer (roughly said), they can be used together and do not compete. A: As said before, JSF is a request-driven, MVC web-framework, built around a light-weight IoC container and is designed to simplify and standardize the way UI-layer of a web-application is built. Spring, on the other hand, is less concerned with UI-layer but its precise definition is hard to formulate. It can be said that the primary function of SF is to tie together different layers of a web application in a standardized way, at the same time abstracting away the implementation details of a particular web technology from the developer. As one of the consequences, the developer is freed from implementing "plumbing" and instead gets working module interconnections which are tested, implemented and used relatively easily. This should provide a boost to productivity and shortens development cycle. This abstraction can be viewed through various Spring modules - Spring is heavily modularized, so you choose which components of the framework will you be using. Though it features a MVC framework (SpringMVC is mostly written as a reaction to the Jakarta Struts, whom the Spring developers deemed poorly written), Spring lacks a dedicated presentation module so you're free to use most of existing UI technologies (e.g. JSF, GWT-oids, etc.) - once you properly configure them in Spring. In another words, the "scopes" of JSF and Spring are quite different (though not totally disjunct).
{ "language": "en", "url": "https://stackoverflow.com/questions/7537981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Recursion vs For loops - Factorials, Java Which of these two methods of getting a factorial (loop vs recursive) is more efficient/faster? and if that one can be improved, how so? Language: Java private static long factrecur(int n) { if (n == 0) { return 1; } else { return n * factrecur(n-1); } } private static long factloop(int a) { long total = 1; for (int b=a;b>=1;b--) { total *= b; } return total; } A: With 21 calls, your long will overrun, which is very early to measure a difference, which could get relevant. You might need BigInteger to measure a significant difference, when measuring factorial (10*1000*1000) or something that large. If you don't have high numbers to calculate, but calculate low factorials often, a hashmap with precalculated values will be faster than recursion and looping. A: The only problem with recursion is that every time that the function is called it's address is put on the top of the stack, concatenating a lot of call can cause a stack overflow exception if the number of recursion calls is high . A: The for loop will be more efficient because there is no overhead of the method calls. (As a general rule loops are almost always more efficient than recursion) To explain why you have to get into the nitty gritty details of what happens when you call a method and something called the call stack. Basically when you call a method it needs a bit of space to work with (for things like its local variables etc) it also needs space for the incoming parameters being passed to it and a place to store the return address of where it should go when it is done executing. This space is dynamically provided by 'pushing' the values on to a stack. That stack space remains occupied until the method returns at which point it is 'popped off'. So think about recursion in this context: every time you call the method from within itself you push more data onto the stack, without returning from the method you were in (and thus without freeing up the stack space the calling method was occupying). As your recursion goes deeper the amount of memory increases. In contrast the for loop you wrote just uses the fixed amount of memory provided by one stack frame push.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Facebook: Invite to application without using Facebook's dialogue box I have made a custom invite screen in my Flash application, when the send button is clicked I want all the selected facebook Ids to be sent, ideally without a dialogue window popping up. Cheers. A: User to user app requests must use the requests dialog App to user requests can be sent via the app access token but can only be sent to existing app users and are not displayed the same way on Facebook.com You can specify an ids parameter to the requests dialog when firing it to show only the users selected earlier in the workflow if you wish
{ "language": "en", "url": "https://stackoverflow.com/questions/7537990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In an Android application,can more than one Main Activity exist I hope someone will help. In Android manifest file, can we specify more than one activity as the main activity? A: Yes you can. But you should define one as default by CATEGORY_DEFAULT. Without default main activity if you have two activities, Android Market do not know what activity to start. <activity android:name=".FirstMainActivity" android:label="First Activity" android:icon="@drawable/first_icon"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> <activity android:name=".SecondMainActivity" android:label="Second Activity" android:icon="@drawable/second_icon"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> You have to set action=MAIN and category=LAUNCHER to be your entry point showed in launcher. A: Yes you can have more than one main activity and you can have multiple launcher activities but if you do so, you will see as many icons in the applications drawer. A: If you think you have several entry points in your application then why not?
{ "language": "en", "url": "https://stackoverflow.com/questions/7537991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to detect all cursor movements and key presses on a Mac? What is the best method to detect all cursor movements and key presses on a Mac using objective-c on OSX Lion? A: I did it by installing an event monitor - (void)monitorEvents { // Monitor all events NSUInteger eventMasks = NSLeftMouseDownMask | NSRightMouseDownMask | NSMouseMovedMask | NSScrollWheelMask | NSKeyDownMask | NSMouseMovedMask | NSEventTypeBeginGesture | NSEventTypeEndGesture; eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:eventMasks handler:^(NSEvent *incomingEvent) { NSEvent *result = incomingEvent; return result; }]; } A: Typically, you would subclass NSApplication and override the -sendEvent: method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7537996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: html reload without javascript I'm writing a hobby project and i was wondering if I can implement the following functionality: If the browser has JS disabled, the page reloads every X seconds. If the browser has JS enabled, the page receives some JS event from somewhere and reloads. But the page does not reload every X seconds. I'm trying to implement server push in the app and it works, but I also want to have some at least semi-reasonable fallback mechanism. Any suggestions? A different way to phrase the question is: Can I disable this(in a cross-platform way): <META HTTP-EQUIV="refresh" CONTENT="15"> After the page has loaded? A: Why not just put that in a <noscript> tag? Does that not work? I forget whether this is "acceptable" but several years ago it used to work, if I remember correctly. A: You could put a meta-refresh in a noscript tag? <html> <head> <title>Meta refresh if no javascript</title> <noscript> <meta http-equiv="refresh" content="1"> </noscript> </head> <body> ... </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7537997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to create .help file for mac application help? I am trying to make the help support for my mac application. I made the XHTML, HTML and the .helpIndex file. But I dont know how to make the .help file. My question is what is .help file? and how to make the .help file? I am studying in the apple classreference for doing this. Below is the stuff I have copied this link Creating a Basic Help Book Once you create the HTML files containing your help content, you must organize them into a help book. To do this, create a help book folder and include the following items: My Question: How to create a help book folder. I cant understand this. I have just create a folder with somename.help and copied the files to it. But that is not working. whether it is the correct way of creating a help folder. A: The .help is the top level folder of your document set not a file. Like a Mac application is really a folder with a .app extension At a base level you need to create your html based document set like you have done and then add the meta tag named AppleTitle into your top level .html file index.html (SurfWriter.html in the examples) <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Style-Type" content="text/css"> <title>Foobar Help</title> <meta name="AppleTitle" content="Foobar Help"> </head> * *add CFBundleHelpBookFolder with a value of the name of your folder (Surfwriter.help) to your plist *add CFBundleHelpBookName with a value of Foobar Help to your plist (matches the meta tag in your header) *add a custom copy phase to put your .help document folder structure into Resources Should just work after that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Unable to drag my scroll bar The below is chat script. When ever I try to drag up the scroll bar is pulling down. How to allow dragging in my below code. Is there any other way to make my code better and to allow scrolling. default.aspx <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div id="div1" style="height:400px; width:400px; overflow:auto; z-index:1"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"> <Triggers> <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" /> </Triggers> <ContentTemplate> <div id="div2" style="height:300px; width:350px"> <asp:BulletedList ID="BulletedList1" runat="server" /> </div> <div id="div4" style="position:absolute; left:500px; bottom:50px; z-index:10"> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> </div> </div> </ContentTemplate> </asp:UpdatePanel> <div id="div5" style="position:absolute; left:100px; bottom:50px; z-index:10"> <asp:TextBox ID="TextBox1" runat="server"/> </div> </form> <script type="text/javascript"> function _SetChatTextScrollPosition() { var chatText = document.getElementById("div1"); chatText.scrollTop = chatText.scrollHeight; window.setTimeout("_SetChatTextScrollPosition()", 1); } window.onload = function () { _SetChatTextScrollPosition(); } </script> </body> </html> Server code protected void Page_Load(object sender, EventArgs e) { } protected void Timer1_Tick(object sender, EventArgs e) { string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=chatserver;" + "UID=root;" + "PASSWORD=******;" + "OPTION=3"; OdbcConnection MyConnection = new OdbcConnection(MyConString); MyConnection.Open(); OdbcCommand cmd = new OdbcCommand("Select message from shoutbox", MyConnection); OdbcDataReader dr = cmd.ExecuteReader(); ArrayList values = new ArrayList(); while (dr.Read()) { string ep = dr[0].ToString(); values.Add(new PositionData(ep)); BulletedList1.DataSource = values; BulletedList1.DataTextField = "Message"; BulletedList1.DataBind(); } } protected void Button1_Click(object sender, EventArgs e) { string MyConString = "DRIVER={MySQL ODBC 3.51 Driver};" + "SERVER=localhost;" + "DATABASE=chatserver;" + "UID=root;" + "PASSWORD=******;" + "OPTION=3"; OdbcConnection MyConnection = new OdbcConnection(MyConString); OdbcCommand cmd = new OdbcCommand("INSERT INTO shoutbox(name, message)VALUES(?, ?)", MyConnection); cmd.Parameters.Add("@name", OdbcType.VarChar, 255).Value = "gimp"; cmd.Parameters.Add("@message", OdbcType.Text).Value = TextBox1.Text; MyConnection.Open(); cmd.ExecuteNonQuery(); MyConnection.Close(); } } public class PositionData { private string name; public PositionData(string name) { this.name = name; } public string Message { get { return name; } } } A: I think the solution will be to detect if browser window is being scrolled currently by user. If yes then don't set the scroll position, other wise do scroll the div element. Javascript changes var isScrolling; document.observe('user:scrolling', function() { isScrolling = true; }); function _SetChatTextScrollPosition() { if(!isScrolling) { var chatText = document.getElementById("div1"); chatText.scrollTop = chatText.scrollHeight; window.setTimeout("_SetChatTextScrollPosition()", 1); } isScrolling = false; } HTML changes <body onscroll="document.fire('user:scrolling')"> Reference link to detect the browser being window scrolled Hope this helps you. Thanks and Regards Harsh Baid. A: Your scrolling is not working because every 1 millisecond you are telling it to scroll to the bottom of your div1 (that's what your _SetChatTextScrollPosition() function does). Since your timeout wait time is so short, as soon as you let go of the scrollbar, it's going to scroll it down again. So, if you want to be able to scroll up, you'll either have to stop using this function, or set the timeout interval to something longer (it's in milliseconds, so 1000 == 1 second) so that you at least have a chance to scroll and look before it kicks you back to the bottom.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Prevent Windows shutdown with custom message VMWare Workstation does something quite cool when I try to shutdown Windows while a Virtual Machine is running: Normally, we'd see a "This program is preventing Windows from shutting down" message instead of the new "1 Virtual Machine is in use". How does VMWare do this? I haven't been able to find any APIs about it on Google. A: You can read all about the changes introduced in Vista here. You really should read that article very carefully. The APIs you are looking for are ShutdownBlockReasonCreate, ShutdownBlockReasonDestroy and ShutdownBlockReasonQuery. Remember that these APIs are only available on Vista/2008 server up. You'll have to implement fall back behaviour on 2000/XP. If you need to block shutdown you call ShutdownBlockReasonCreate passing the handle to your main window and the reason as a string. This string is what is displayed in the shutdown blocked dialog, i.e. "1 virtual machine is in use" in your screenshot. If the operation that blocks shutdown completes then you call ShutdownBlockReasonDestroy. Note that you must still implement WM_QUERYENDSESSION to make all the pieces fit together. This is the part that actually blocks the shutdown. On XP you should also respond to WM_ENDSESSION and if your app blocked shutdown it is polite to show a message indicating why. If you don't do so then the user is left scratching his/her head as to why the computer is ignoring the instruction to shutdown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: What does _beginthread's second argument stack_size mean? In function _beginthread, what does the second argument (stack_size) mean? Stack size of where? And what does the default value (0) mean? A: The stack size of where? The call stack is a stack that maintains information about active function calls of executing software. It's also known as an execution stack, control stack, or run-time stack. In multi-threaded software, each thread has its own call stack. The primary purpose of the call stack is to manage control flow by keeping track of where each function call returns to. When a function call is made, a new stack frame is pushed onto the stack for that function. When the function returns, its stack frame is popped off and control flow is returned to the address of the caller's next instruction. A stack frame typically includes: * *Return address back to caller *Parameters passed to the function *Saved registers & local variables Parameters can also be passed via CPU registers, but there are drawbacks to this (ie. limited number of parameters, & registers may be needed for computation.) Similarly, all local variables don't have to be allocated on the current stack frame. Languages that support closures require free variables to survive after function return, yet locals on the call stack are deallocated when the current stack frame is popped off and control is returned to the caller. My point here is that parameter passing and allocation of locals are determined by language and compiler implementation; you shouldn't assume they always exist on the stack. What does stack_size mean? What is the default value 0? From the MSDN documentation on _beginthread, found under the Remarks section: The operating system handles the allocation of the stack when either _beginthread or _beginthreadex is called; you do not need to pass the address of the thread stack to either of these functions. In addition, the stack_size argument can be 0, in which case the operating system uses the same value as the stack specified for the main thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Properly running binaries on runtime with safety (seteuid etc) So if I want to run a binary using exec() on a child process after fork, but want to restrict its file access to a certain directory only, how does one safely do that? Does this involve of creating a new user in unix/linux, and then setting the uid to that user?Or would this require creating a group (say, webapps) and then using setguid? Of course, one can just run the binary as is, but it seems that taking some precautions with security is never a bad idea. A: I'd take a look at chroot. It a relatively easy way to separate parts of your system. In a nutshell: you change the root for a particular process, so /path/to/working/dir is now / for that process. Of course you have to add everything that is necessary (utilities, libraries, configuration) to this folder.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Problem looping audio on android app Due to login confusion, i'm repeating this question. If any moderator sees this, i'd like to keep this one current, as I no longer can access my former login. A bit of a problem has presented itself to me. I am trying to play a sound continously looping in my android app. With MediaPlayer: MP3 plays alright, but there is a gap at the end which does not exist in the file. I read it had to do with the decoder, and that ogg should work. Tried using ogg, but still get the gap, which is definitely not on the file. With SoundPool classes and ogg (using this fellow's interesting class: http://www.droidnova.com/creating-sound-effects-in-android-part-1,570.html), the sound starts, and a fraction of a second later, it restarts. so I get a stutering half a second of the beginning of every file, without advancing further, because it is always going back to the beginning. Is there something really wrong with media player and it's ability to loop audio? How about the freakishy stuttering soundpool? Thank you very much for any assistance! Note: Karthi_Heno suggested I do this: MediaPlayer mediaPlayer; setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); try { AssetManager assetManager = getAssets(); AssetFileDescriptor descriptor = assetManager.openFd("music.ogg"); mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); mediaPlayer.prepare(); mediaPlayer.setLooping(true); } catch (IOException e) { textView.setText("Couldn't load music file, " + e.getMessage()); mediaPlayer = null; } However, when i do this, getassets gives filenotfound, even though there IS a filein assets. any thoughts either on thisassets problem, or my audio loop question? thanks. Yep, i'm an android newb alright, can't even get sound to loop alright.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to inspect a method using reflection public void foo(){ throw new Exception("foo"); } public void bar(){ foo(); } Is it possible to inspect the method bar() in order to know that foo() is called without a try catch inside bar()? A: You may be interested in wrapping the whole class inside a Proxy and watch it with an InvocationHandler: http://www.javalobby.org/java/forums/t18631.html Your InvocationHandler would do something special if it sees that "foo" is called immediatly after "bar", I guess. A: It seems like your intention is to have your application code check a method implementation, and conditional branch when that method fails to use try-catch internally. Unless you are writing unit tests, let me discourage doing this for two reasons: 1. A developer should understand his application logic. You should already know what your code is doing. If the method is part of a closed-source API, check the documentation for thrown Exception types. 2. It adds unnecessary complexity. Because flow of execution depends on method implementation, you will have an application whose behavior is dependent upon the state of its own source. (eg. Changing the method can create side-effects, which makes debugging more difficult.) If you can determine method behavior by checking the source code or API documentation, what is the need for verifying at run-time? A: As far as my knowledge is concern, there is no such reflection API which allows to see the inside implementations. You can only inspect the methods present in the Class, but can not the logic written in the method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I shrink the drawable on a button? how can I make the drawable on a button smaller? The icon is too big, actually higher than the button. This is the code I am using: <Button android:background="@drawable/red_button" android:drawableLeft="@drawable/s_vit" android:id="@+id/ButtonTest" android:gravity="left|center_vertical" android:text="S-SERIES CALCULATOR" android:textColor="@android:color/white" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginLeft="25dp" android:layout_marginRight="25dp" android:drawablePadding="10dp"> </Button> The upper is how it should look, the lower how it looks right now. I tried this but there is no image displayed. :-( Resources res = getResources(); ScaleDrawable sd = new ScaleDrawable(res.getDrawable(R.drawable.s_vit), 0, 10f, 10f); Button btn = (Button) findViewById(R.id.ButtonTest); btn.setCompoundDrawables(sd.getDrawable(), null, null, null); A: I have found a very simple and effective XML solution that doesn't require ImageButton Make a drawable file for your image as below and use it for android:drawableLeft <?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/half_overlay" android:drawable="@drawable/myDrawable" android:width="40dp" android:height="40dp" /> </layer-list> You can set the image size with android:width and android:height properties. This way you could at least get the same size for different screens. The drawback is that it is not exactly like fitXY which would scale image width to fit X and scale image height accordingly. A: You should use a ImageButton and specify the image in android:src, and set android:scaletype to fitXY Setting scaled drawable in code Drawable drawable = getResources().getDrawable(R.drawable.s_vit); drawable.setBounds(0, 0, (int)(drawable.getIntrinsicWidth()*0.5), (int)(drawable.getIntrinsicHeight()*0.5)); ScaleDrawable sd = new ScaleDrawable(drawable, 0, scaleWidth, scaleHeight); Button btn = findViewbyId(R.id.yourbtnID); btn.setCompoundDrawables(sd.getDrawable(), null, null, null); //set drawableLeft for example A: Use a ScaleDrawable as Abhinav suggested. The problem is that the drawable doesn't show then - it's some sort of bug in ScaleDrawables. you'll need to change the "level" programmatically. This should work for every button: // Fix level of existing drawables Drawable[] drawables = myButton.getCompoundDrawables(); for (Drawable d : drawables) if (d != null && d instanceof ScaleDrawable) d.setLevel(1); myButton.setCompoundDrawables(drawables[0], drawables[1], drawables[2], drawables[3]); A: My DiplayScaleHelper, that works perfectly: import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.graphics.drawable.ScaleDrawable; import android.widget.Button; public class DisplayHelper { public static void scaleButtonDrawables(Button btn, double fitFactor) { Drawable[] drawables = btn.getCompoundDrawables(); for (int i = 0; i < drawables.length; i++) { if (drawables[i] != null) { if (drawables[i] instanceof ScaleDrawable) { drawables[i].setLevel(1); } drawables[i].setBounds(0, 0, (int) (drawables[i].getIntrinsicWidth() * fitFactor), (int) (drawables[i].getIntrinsicHeight() * fitFactor)); ScaleDrawable sd = new ScaleDrawable(drawables[i], 0, drawables[i].getIntrinsicWidth(), drawables[i].getIntrinsicHeight()); if(i == 0) { btn.setCompoundDrawables(sd.getDrawable(), drawables[1], drawables[2], drawables[3]); } else if(i == 1) { btn.setCompoundDrawables(drawables[0], sd.getDrawable(), drawables[2], drawables[3]); } else if(i == 2) { btn.setCompoundDrawables(drawables[0], drawables[1], sd.getDrawable(), drawables[3]); } else { btn.setCompoundDrawables(drawables[0], drawables[1], drawables[2], sd.getDrawable()); } } } } } A: You can call setBounds on the "compound" drawables to modify the size of the image. Try this code to autosize the drawable of your button: DroidUtils.scaleButtonDrawables((Button) findViewById(R.id.ButtonTest), 1.0); defined by this function: public final class DroidUtils { /** scale the Drawables of a button to "fit" * For left and right drawables: height is scaled * eg. with fitFactor 1 the image has max. the height of the button. * For top and bottom drawables: width is scaled: * With fitFactor 0.9 the image has max. 90% of the width of the button * */ public static void scaleButtonDrawables(Button btn, double fitFactor) { Drawable[] drawables = btn.getCompoundDrawables(); for (int i = 0; i < drawables.length; i++) { if (drawables[i] != null) { int imgWidth = drawables[i].getIntrinsicWidth(); int imgHeight = drawables[i].getIntrinsicHeight(); if ((imgHeight > 0) && (imgWidth > 0)) { //might be -1 float scale; if ((i == 0) || (i == 2)) { //left or right -> scale height scale = (float) (btn.getHeight() * fitFactor) / imgHeight; } else { //top or bottom -> scale width scale = (float) (btn.getWidth() * fitFactor) / imgWidth; } if (scale < 1.0) { Rect rect = drawables[i].getBounds(); int newWidth = (int)(imgWidth * scale); int newHeight = (int)(imgHeight * scale); rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth)); rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight)); rect.right = rect.left + newWidth; rect.bottom = rect.top + newHeight; drawables[i].setBounds(rect); } } } } } } Be aware, that this may not be called in onCreate() of an activity, because button height and width are not (yet) available there. Call this in on onWindowFocusChanged() or use this solution to call the function. Edited: The first incarnation of this function did not work correctly. It used userSeven7s code to scale the image, but returning ScaleDrawable.getDrawable() does not seem to work (neither does returning ScaleDrawable) for me. The modified code uses setBounds to provide the bounds for the image. Android fits the image into these bounds. A: Buttons do not resize their inner images. My solution does not require code manipulation. It uses a layout with TextView and ImageView. The background of the layout should have the red 3d drawable. You may need to define the android:scaleType xml attribute. Example: <LinearLayout android:id="@+id/list_item" android:layout_width="fill_parent" android:layout_height="50dp" android:padding="2dp" > <ImageView android:layout_width="50dp" android:layout_height="fill_parent" android:src="@drawable/camera" /> <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:lines="1" android:gravity="center_vertical" android:text="Hello - primary" /> </LinearLayout> BTW: * *Counting on different resolution icons may result in a non predictable UI (icon too big or too small) *Text in textview (including in buttons) does not fill the component. This is an Android problem and I don't know how to solve it. *You can use it as an include. Good luck A: If you want to use 1 image and display it in different size, you can use scale drawable ( http://developer.android.com/guide/topics/resources/drawable-resource.html#Scale ). A: I am doing it as below. This creates a 100x100 size image in the button independent of the input image. drawable.bounds = Rect(0,0,100,100) button.setCompoundDrawables(drawable, null, null, null) Not using ScaleDrawable either. Not using button.setCompoundDrawablesRelativeWithIntrinsicBounds() solved my problem, as that seems to use intrinsic bounds (source image size) instead of the bounds you just set. A: You can use different sized drawables that are used with different screen densities/sizes, etc. so that your image looks right on all devices. See here: http://developer.android.com/guide/practices/screens_support.html#support A: Did you try wrapping your image in a ScaleDrawable and then using it in your button? A: Here the function which I created for scaling vector drawables. I used it for setting TextView compound drawable. /** * Used to load vector drawable and set it's size to intrinsic values * * @param context Reference to {@link Context} * @param resId Vector image resource id * @param tint If not 0 - colour resource to tint the drawable with. * @param newWidth If not 0 then set the drawable's width to this value and scale * height accordingly. * @return On success a reference to a vector drawable */ @Nullable public static Drawable getVectorDrawable(@NonNull Context context, @DrawableRes int resId, @ColorRes int tint, float newWidth) { VectorDrawableCompat drawableCompat = VectorDrawableCompat.create(context.getResources(), resId, context.getTheme()); if (drawableCompat != null) { if (tint != 0) { drawableCompat.setTint(ResourcesCompat.getColor(context.getResources(), tint, context.getTheme())); } drawableCompat.setBounds(0, 0, drawableCompat.getIntrinsicWidth(), drawableCompat.getIntrinsicHeight()); if (newWidth != 0.0) { float scale = newWidth / drawableCompat.getIntrinsicWidth(); float height = scale * drawableCompat.getIntrinsicHeight(); ScaleDrawable scaledDrawable = new ScaleDrawable(drawableCompat, Gravity.CENTER, 1.0f, 1.0f); scaledDrawable.setBounds(0,0, (int) newWidth, (int) height); scaledDrawable.setLevel(10000); return scaledDrawable; } } return drawableCompat; } A: * *Using "BATCH DRAWABLE IMPORT" feature you can import custom size depending upon your requirement example 20dp*20dp * *Now after importing use the imported drawable_image as drawable_source for your button *It's simpler this way A: It is because you did not setLevel. after you setLevel(1), it will be display as u want A: I made a custom button class to achieve this. CustomButton.java public class CustomButton extends android.support.v7.widget.AppCompatButton { private Drawable mDrawable; public CustomButton(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.getTheme().obtainStyledAttributes( attrs, R.styleable.CustomButton, 0, 0); try { float mWidth = a.getDimension(R.styleable.CustomButton_drawable_width, 0); float mHeight = a.getDimension(R.styleable.CustomButton_drawable_width, 0); Drawable[] drawables = this.getCompoundDrawables(); Drawable[] resizedDrawable = new Drawable[4]; for (int i = 0; i < drawables.length; i++) { if (drawables[i] != null) { mDrawable = drawables[i]; } resizedDrawable[i] = getResizedDrawable(drawables[i], mWidth, mHeight); } this.setCompoundDrawables(resizedDrawable[0], resizedDrawable[1], resizedDrawable[2], resizedDrawable[3]); } finally { a.recycle(); } } public Drawable getmDrawable() { return mDrawable; } private Drawable getResizedDrawable(Drawable drawable, float mWidth, float mHeight) { if (drawable == null) { return null; } try { Bitmap bitmap; bitmap = Bitmap.createBitmap((int)mWidth, (int)mHeight, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return drawable; } catch (OutOfMemoryError e) { // Handle the error return null; } } } attrs.xml <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="CustomButton"> <attr name="drawable_width" format="dimension" /> <attr name="drawable_height" format="dimension" /> </declare-styleable> </resources> Usage in xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.MainActivity"> <com.example.CustomButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableTop="@drawable/ic_hero" android:text="Avenger" custom:drawable_height="10dp" custom:drawable_width="10dp" /> </RelativeLayout> A: I tried the techniques of this post but didnot find any of them so attractive. My solution was to use an imageview and textview and align the imageview top and bottom to the textview. This way I got the desired result. Here's some code: <RelativeLayout android:id="@+id/relativeLayout1" android:layout_width="match_parent" android:layout_height="48dp" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignTop="@+id/textViewTitle" android:layout_alignBottom="@+id/textViewTitle" android:src="@drawable/ic_back" /> <TextView android:id="@+id/textViewBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textViewTitle" android:layout_alignBottom="@+id/textViewTitle" android:layout_toRightOf="@+id/imageView1" android:text="Back" android:textColor="@color/app_red" android:textSize="@dimen/title_size" /> </RelativeLayout> A: Using Kotlin Extension val drawable = ContextCompat.getDrawable(context, R.drawable.my_icon) // or resources.getDrawable(R.drawable.my_icon, theme) val sizePx = 25 drawable?.setBounds(0, 0, sizePx, sizePx) // (left, top, right, bottom) my_button.setCompoundDrawables(drawable, null, null, null) I suggest creating an extension function on TextView (Button extends it) for easy reuse. button.leftDrawable(R.drawable.my_icon, 25) // Button extends TextView fun TextView.leftDrawable(@DrawableRes id: Int = 0, @DimenRes sizeRes: Int) { val drawable = ContextCompat.getDrawable(context, id) val size = context.resources.getDimensionPixelSize(sizeRes) drawable?.setBounds(0, 0, size, size) this.setCompoundDrawables(drawable, null, null, null) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7538021", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "88" }
Q: Show only a part of SlidingDrawer? I want to have the SlidingDrawer show in 2 parts. On the first swipe up it shows only 1 button. and in the other swipe up, it shows the second button. How can I do this? Thanks. A: You could always have a counter in the SlidingDrawer that counts how many times the user have opened the drawer. And depending on the counter you either choose another layout or just use setVisibility on different views. Simple example, lets say you have button1 the first time the user opens the drawer and button2 the second time. If the user draws it a third time set the counter to 0 again. if(counter==0) { button1.setVisibility(View.VISIBLE); button2.setVisibility(View.GONE); } else { button1.setVisibility(View.GONE); button2.setVisibility(View.VISIBLE); } SlidingDrawer For the counter you could use setOnDrawerCloseListener to change the value since you want to have the upcoming counter value before the user have opened the drawer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to get user's facebook pages and apps list after authentication? After a user install my application to his/her facebook page,I want to get his/her facebook pages and apps list. I have read these documents: http://developers.facebook.com/docs/reference/fql/application/ http://developers.facebook.com/docs/reference/fql/developer/ What is the best way to do? Another question: How to check if a user is my app's user? A: It sounds like you haven't really looked at the documentation, but they are fairly clear questions, so... * *After getting the user_likes permission you can query /me/likes to get a list of pages the user likes. A list of apps is not currently possible in the same way. *A call to /me/permissions or /me/?fields=installed will show if the current app is installed by the current user *A call to /me/accounts with the 'manage_pages' permission will show which pages and apps a user admins, but not which pages and apps they use. A: You can use FQL to query this information. select uid, name, is_app_user from user where uid in (select uid2 from friend where uid1=me()) and is_app_user=1 A: The user needs to allow (and be user of) your app in order to be able to authenticate though oauth. You can list the user's pages and apps by accessing: https://graph.facebook.com/me/accounts or https://graph.facebook.com/%user_id%/accounts But you must also provide the user oauth token.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: register new xmpp account with node-xmpp ( node.js ) I'm looking at 'XEP-0077 in-band registration' about how to register a new XMPP account. Here is my code. I use node-xmpp to connect my node.js application to an ejabberd server. var net = require('net'); var xmpp = require('node-xmpp'); var cache = new Object(); net.createServer( function(socket) { socket.setEncoding('utf8'); socket.addListener('data',function(data) { data = data.substr(0,data.length-2); if(cache.admin==undefined && data=='login') { var ejabberd =new xmpp.Client({jid:"admin@mine",password:'12345',host:'192.168.7.202',port:'5222'}); cache.admin = ejabberd; cache.admin.addListener('online',function() { cache.admin.send(new xmpp.Element('presence',{type:'chat'}).c('show').c('status').t('mine status')); cache.admin.send(new xmpp.Element('iq',{type:'get',id:'reg1'}).c('query',{xmlns:'jabber:iq:register'})); }) cache.admin.addListener('stanza',function(stanza) { if(stanza.is('iq')) { console.log(stanza.children[1]); } }) cache.admin.addListener('end',function() { cache.admin.end(); cache.admin = undefined; }) } if(cache.admin!=undefined && data=='logout') { cache.admin.end(); cache.admin = undefined; } else if(cache.admin!=undefined && data=='register') { cache.admin.send(new xmpp.Element('iq',{type:'set',id:'reg1'}).c('query',{xmlns:'jabber:iq:register'}).c('username').t('alow').up().c('password').t('test')); } }); }).listen(5000); If i run this code, I get this error: { name: 'error', parent: { name: 'iq', parent: null, attrs: { from: 'admin@mine', to: 'admin@mine/20108892991316770090454637', id: 'reg1', type: 'error', xmlns: 'jabber:client', 'xmlns:stream': 'http://etherx.jabber.org/streams' }, children: [ [Object], [Circular] ] }, attrs: { code: '403', type: 'auth' }, children: [ { name: '**forbidden**', parent: [Circular], attrs: [Object], children: [] } ] } In 'XEP-0077: In-Band Registration' it says that the forbidden reason means that "The sender does not have sufficient permissions to cancel the registration". How can I get such permissions? A: I have been strugling with something similar, I wanted to register a new user account via in-band registraton from nodejs to an ejabberd server running in ubuntu. Here is what I did and worked for me: //Dependencies var xmpp = require('node-xmpp'); //Host configuration var host = "localhost"; var port = "5222"; var admin = "sebastian@localhost"; var adminPass = "adminPass"; var connection = new xmpp.Client({ jid: admin, password: adminPass, host: host, port: port }); //user to be registered name & pass var newUserName = "pepe"; var newUserPass = "pepePass"; //Stream var iq = "<stream:stream xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:component:accept' to='localhost'><iq type='set' id='reg2'><query xmlns='jabber:iq:register'><username>" + newUserName + "</username><password>" + newUserPass + "</password></query></iq></stream>"; //Send connection.send(iq); //End connection.end(); The var iq is kind of messy, I suppose that if you know how to use Strophe.js in a propper way that part could look a little bit nicer and cleaner. I was missing the section of the xml, it seems that if you want to send a stream, you have to provide a valid ejabberd namespace, that was what was failing for me. Hope this helps you sort your problem out. A: Which server are you using? Are you sure it has XEP-77 enabled? Test with an existing client. Ensure that the account you're trying to create does not already exist. Ensure that the account has the correct domain name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Receiving a Sharing Violation Opening a File Code 32 I have been trying the following piece of code that does not work. What I am trying to do is to start executing my exe (one that I created a simple dialog based application using VC6.0) then from inside this application modify its own contents stored on the hard drive. So there is a running copy of the exe and from this running copy it will open the disk copy into a buffer. Once loaded into a buffer then begin a search for a string. Once the string is found it will be replaced with another string which may not be the same size as the original. Right now I am having an issue of not being able to open the file on disk for reading/writing. GetLastError returns the following error "ERROR_SHARING_VIOLATION The process cannot access the file because it is being used by another process.". So what I did I renamed the file on disk to another name (essential same name except for the extension). Same error again about sharing violation. I am not sure why I am getting this sharing violation error code of 32. Any suggestions would be appreciated. I'll ask my second part of the question in another thread. FILE * pFile; pFile = fopen ("Test.exe","rb"); if (pFile != NULL) { // do something like search for a string } else { // fopen failed. int value = GetLastError(); // returns 32 exit(1); } A: Read the Windows part of the File Locking wikipedia entry: you can't modify files that are currently executing. You can rename and copy them, but you can't change them. So what you are trying to do is simply not possible. (Renaming the file doesn't unlock it at all, it's still the same file after the rename, so still not modifiable.) You could copy your executable, modify that copy, then run that though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i detect multiLanguages in string? I have a string in c# How can i detect if this string contains Chars from Different Languages ? i.e : a person fills his english name in text box and also his local language name. I want to disallow that. something like this : "check the language table of the chars in the string and if it comes from different unicode tables - return ERROR". but i think there is a problem for 'a' in us or uk. maybe im wrong. how can i recognize more than one language ? A: I think you're searching for codepoints. The unique identifiers of a character in codepage. I think this should be useful to you How would you get an array of Unicode code points from a .NET String?. Once you get codepoints array from the string, you can check it against the range of code points you want. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Ajaxify will_paginate in rails 3.1 I am trying to ajaxify will_paginate result in rails 3.1. I have gone through the example of railscasts episode #174 but it is not working for rails 3.1. Is there a simple way to ajaxify will_paginate result in rails3.1? Here is index.js.erb code for loading the user partial (this file is in app/views/users folder) $('#test').html("<%= escape_javascript(render(@users)) %>"); Here is my pagination.js code (this file is in app/assets/javascripts) $(function() { $(".users a").live("click", function() { $.get(this.href, null, null, "script"); return false; }); }); I am using will_paginate both the files are getting loaded and I have tested for it. Any help on where I am making the mistake? Thanks, A: replace the line in pagination.js: $(".users a").live("click", function() { with $(".pagination a").live("click", function() { Then just make sure your index.js.erb is named correctly. For example, if you're using pagination inside the view show.html.erb, your script has to be named show.js.erb
{ "language": "en", "url": "https://stackoverflow.com/questions/7538043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: list all defined constants from a file in php I have some php files that includes some language constants define("_SEARCH","Search"); define("_LOGIN","Login"); define("_WRITES","writes"); define("_POSTEDON","Posted on"); define("_NICKNAME","Nickname"); now I need to read each file and list all constants and their values and to return an output like this : constant name : value is : so I think there should be function to list all defined constants of a given php file. I'm aware of functions like token_get_all or get_defined_constants but i wasn't able to do it. A: If the files do contain nothing but define statements, you can use get_defined_constants: function getUserDefinedConstants() { $constants = get_defined_constants(true); return (isset($constants['user']) ? $constants['user'] : array()); } $constantsBeforeInclude = getUserDefinedConstants(); include('file.php'); $constantsAfterInclude = getUserDefinedConstants(); $newConstants = array_diff_assoc($constantsAfterInclude, $constantsBeforeInclude); What it does is basically: get_defined_constants(true) gives us an array of arrays with all available constants, sorted by sections (core, user, ..) - the array under the key 'user' gives us all user-defined constants that we defined in our php code using define, up to that point. array_diff_assoc gives us the difference between this array before and after the file got included.. and that is exactly a list of all constants that got defined in that specific file (as long as there is none of the declarations a duplicate, meaning a constant with that exact name has been defined before - but this would cause an error anyway). A: this is the php script you need: <?php //remove comments $Text = php_strip_whitespace("your_constants_file.php"); $Text = str_replace("<?php","",$Text); $Text = str_replace("<?","",$Text); $Text = str_replace("?>","",$Text); $Lines = explode(";",$Text); $Constants = array(); //extract constants from php code foreach ($Lines as $Line) { //skip blank lines if (strlen(trim($Line))==0) continue; $Line = trim($Line); //skip non-definition lines if (strpos($Line,"define(")!==0) continue; $Line = str_replace("define(\"","",$Line); //get definition name & value $Pos = strpos($Line,"\",\""); $Left = substr($Line,0,$Pos); $Right = substr($Line,$Pos+3); $Right = str_replace("\")","",$Right); $Constants[$Left] = $Right; } echo "<pre>"; var_dump($Constants); echo "</pre>"; ?> The result will be something similar to this: array(5) { ["_SEARCH"]=> string(6) "Search" ["_LOGIN"]=> string(5) "Login" ["_WRITES"]=> string(6) "writes" ["_POSTEDON"]=> string(9) "Posted on" ["_NICKNAME"]=> string(8) "Nickname" } A: Late to the game here but I had a similar issue. You could use an include() substitute/wrapper function that logs constants in an accessible global array. <?php function include_build_page_constants($file) { global $page_constants ; $before = get_defined_constants(true); include_once($file); $after = get_defined_constants(true); if ( isset($after['user']) ) { if ( isset($before['user']) ) { $current = array_diff_assoc($after['user'],$before['user']); }else{ $current = $after['user']; } $page_constants[basename($file)]=$current; } } include_and_build_page_constants('page1.php'); include_and_build_page_constants('page2.php'); // test the array echo '<pre>'.print_r($page_constants,true).'</pre>'; ?> This will result in something like: Array ( [page1.php] => Array ( [_SEARCH] => Search [_LOGIN] => Login [_WRITES] => writes [_POSTEDON] => Posted on [_NICKNAME] => Nickname ) [page2.php] => Array ( [_THIS] => Foo [_THAT] => Bar ) ) A: Assuming that you want to do this on runtime, you should take a look at PHP Reflection, specifically at the ReflectionClass::getConstants() which lets you do exactly what you seem to want. A: I too had the same problem. I went from jondinham's suggestion, but I prefer to use regex, as it is a bit easier to control and flexible. Here's my version of the solution: $text = php_strip_whitespace($fileWithConstants); $text = str_replace(array('<?php', '<?', '?>'), '', $text); $lines = explode(";", $text); $constants = array(); //extract constants from php code foreach ($lines as $line) { //skip blank lines if (strlen(trim($line)) == 0) continue; preg_match('/^define\((\'.*\'|".*"),( )?(.*)\)$/', trim($line), $matches, PREG_OFFSET_CAPTURE); if ($matches) { $constantName = substr($matches[1][0], 1, strlen($matches[1][0]) - 2); $constantValue = $matches[3][0]; $constants[$constantName] = $constantValue; } } print_r($constants);
{ "language": "en", "url": "https://stackoverflow.com/questions/7538049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Error if i declare constant with #define or const in my C program I use gcc version 4.3.2 (Debian 4.3.2-1.1). I wrote a simple program in C to implement and test a integer stack. Stack is implemented by the STACK structure. I used a constant named STACKSIZE to define the STACK's size. My program code looks like this: #include<stdio.h> #include<stdlib.h> #define STACKSIZE 10; typedef struct { int size; int items[STACKSIZE]; } STACK; void push(STACK *ps, int x) { if (ps->size == STACKSIZE) { fputs("Error: stack overflow\n", stderr); abort(); } else ps->items[ps->size++] = x; } int pop(STACK *ps) { if (ps->size == 0){ fputs("Error: stack underflow\n", stderr); abort(); } else return ps->items[--ps->size]; } int main() { STACK st; st.size = 0; int i; for(i=0; i < STACKSIZE + 1; i++) { push(&st, i); } while(st.size != 0) printf("%d\n", pop(&st)); printf("%d\n", pop(&st)); return 0; } when i used #define STACKSIZE 10; gcc would return following errors: ex_stack1.c:8: error: expected β€˜]’ before β€˜;’ token ex_stack1.c:9: warning: no semicolon at end of struct or union ex_stack1.c: In function β€˜push’: ex_stack1.c:13: error: expected β€˜)’ before β€˜;’ token ex_stack1.c:17: error: β€˜STACK’ has no member named β€˜items’ ex_stack1.c: In function β€˜pop’: ex_stack1.c:26: error: β€˜STACK’ has no member named β€˜items’ ex_stack1.c: In function β€˜main’: ex_stack1.c:33: error: expected β€˜)’ before β€˜;’ token when i used const int STACKSIZE=10; gcc would return following error: ex_stack1.c:8: error: variably modified β€˜items’ at file scope when i used enum {STACKSIZE=10}; gcc would compile my program successfully. What happenned? How should i modify my program to use #define STACKSIZE 10; or const int STACKSIZE=10; A: Drop the semicolon, it's wrong #define STACKSIZE 10; ^ If you keep it the preprocessor will translate int items[STACKSIZE]; into the obviously wrong int items[10;];. For the const bit, there is a C FAQ. The value of a const-qualified object is not a constant expression in the full sense of the term, and cannot be used for array dimensions, case labels, and the like. A: For future reference, you can view the results of the preprocessor by making use of the -E option to gcc. That is, gcc -E ex_stack1.c -o ex_stack1.i Examination of the resulting ex_stack1.i file would have made the problem more obvious. A: #define does textual replacement. Since you have: #define STACKSIZE 10; then typedef struct { int size; int items[STACKSIZE]; } STACK; becomes: typedef struct { int size; int items[10;]; } STACK; In C, const is used to declare variables that can't (easily) be modified. They are not compile-time constants. enum, however, does define a compile-time constant. In general, you should prefer enum over const int over #define where possible. (See Advantage and disadvantages of #define vs. constants? ).
{ "language": "en", "url": "https://stackoverflow.com/questions/7538053", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Return customized UIButton in method? I have a method that takes a UIButton, modifies its properties and returns a UIButton. However, it doesn't ever seem to be initialized. I'm sure I'm doing something wrong with the memory management here, but don't exactly know how to fix it. No runtime errors occur. It is called like so... newGameBtn = [self customButtonFromButton:newGameBtn withText:[NSString stringWithFormat:@"NEW GAME"] withFontSize:22 withBorderColor:[UIColor orangeColor] isSilent:YES]; [dashboardContainer addSubview:newGameBtn]; The method is defined as follows... - (UIButton*) customButtonFromButton:(UIButton*)button withText:(NSString*)text withFontSize:(int)fontSize withBorderColor:(UIColor*)borderColor isSilent:(BOOL)isSilent { button = [[[UIButton alloc] init] autorelease]; // Set properties from parameters // Other conditional custom stuff here return button; } NOTE: newGameBtn is of type UIButton* and is initialized with: newGameBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain]; Another option might be to subclass UIButton, but I figured I'd try to fix this since I've already walked down this path. A: You should use +[UIButton buttonWithType:] when creating buttons to get a properly initialized button. Most classes are not properly initialized by the default -[NSObject init] method. So please look at the class reference, or superclass reference, for a usable initialization method. In this case you should also set a frame. A: You don't modify this button with your method, you're creating a completely new one with alloc-init! If you want to change the button in your first argument just remove the first line of your method
{ "language": "en", "url": "https://stackoverflow.com/questions/7538054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .htaccess rewrite url with parameter I want to change my url with only the parameter. As I am passing only one parameter, so I want the sub url should be changed with my parameter name. I want change the url as the following type- From: http://www.xyz.com/cat.php?slag=season to http://www.xyz.com/season Can anyone help me to do it. I don't know how to do it. Thanks A: Options +FollowSymLinks RewriteEngine On RewriteBase /path/to/your/directory RewriteRule ^(.*)cat/(.*)$ cat\.php?slag=$2&%{QUERY_STRING} [L] put the above in your .htaccess file.. and that would do the magic.. Note : RewriteBase /path/to/your/directory (use this line only if your application is in any of subfolder the folder) A: I suggest you obtain a copy of the .htaccess that WordPress uses. It's a quite powerful starting point that allows you to handle routing internally from within your Application - which you might feel more comfortable with, as it seems to me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does boost::variant work with std::string? I've written a simple program in C++ with use of boost::variant. Program's code is presented below. #include <string> #include <iostream> #include <boost/variant.hpp> int main (int argc, char** argv) { boost::variant<int, std::wstring> v; v = 3; std::cout << v << std::endl; return 0; } But when I try to compile this with command g++ main.cpp -o main -lboost_system i get /usr/include/boost/variant/detail/variant_io.hpp:64: error: no match for β€˜operator<<’ in β€˜((const boost::detail::variant::printer<std::basic_ostream<char, std::char_traits<char> > >*)this)->boost::detail::variant::printer<std::basic_ostream<char, std::char_traits<char> > >::out_ << operand’ followed by a bunch of candidate functions. What I'm missing? The funny thing is When I use std::string instead of std::wstring everything works great. Thanks in advance. A: The problem is that wstring cannot be << in cout. Try using wcout instead. This is not a problem with the variant. A: Use wcout, not cout. Because you're using wstring, not string. std::wcout << v << std::endl; //^^^^ note Demo : http://ideone.com/ynf15
{ "language": "en", "url": "https://stackoverflow.com/questions/7538062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Installing Higher Versions of existing Windows Service in VS 2008 I am installing a Windows Service on my Desktop with a particular version. Then I revise my service and make some changes in the service.I upgrade my installer version.I also make the property RemovePreviousVersion true.When I start to Install the upgraded Windows Service, I get the below mentioned Error. Error: The specified service already exists . Stack Trace : At System.Process.ServiceInstaller.Install(IDictionary)at System.Configuration.Install.Installer.Install at WinDbSync1.Project.Install.
{ "language": "en", "url": "https://stackoverflow.com/questions/7538064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }