text
stringlengths
8
267k
meta
dict
Q: How to check if pid belongs to current user session? I can get the list of running process from the this source code on mac. Now, I want to filter these processes for different users or at least for current user session. A: You can just extend your code like this.. kinfo_proc *mylist; size_t mycount = 0; mylist = (kinfo_proc *)malloc(sizeof(kinfo_proc)); GetBSDProcessList(&mylist, &mycount); char *user = getenv("USER"); for (int i = 0; i < mycount; i++) { uid_t uid = mylist[i].kp_eproc.e_pcred.p_ruid; struct passwd * pwd = getpwuid(uid); char * username = pwd->pw_name; if(strcmp(username, user) == 0) { printf(" %d - %s \n", mylist[i].kp_proc.p_pid, mylist[i].kp_proc.p_comm); } } A: To be more precise you can get username buy this technique SCDynamicStoreRef store; store = SCDynamicStoreCreate(NULL, CFSTR("com.apple.dts.ConsoleUser"), NULL, NULL); CFStringRef currentConsoleUser = CopyCurrentConsoleUsername(store); const int kBufferSize = 256; char logedinusername[kBufferSize]; CFStringGetCString(currentConsoleUser,logedinusername,kBufferSize,kCFStringEncodingMacRoman); as getenv("USER"); may not work if you are running as root user and want logged in user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567140", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: object gets passed to action as string I have a form that has a hidden field wich stores a object. This object is a RoutesValues (I want to store a reference because when I process the form I want to redirect to a route). The action that processes the form is: public ActionResult Añadir(string userName, string codigoArticulo, string resultAction, string resultController, object resultRouteValues, int cantidad) { processForm(codigoArticulo, cantidad); if (!ModelState.IsValid) TempData["Error"] = @ErrorStrings.CantidadMayorQue0; if (!string.IsNullOrWhiteSpace(resultAction) && !string.IsNullOrWhiteSpace(resultController)) return RedirectToAction(resultAction, resultController, resultRouteValues); return RedirectToAction("Index", "Busqueda", new {Area = ""}); } and my form is: @using (Html.BeginForm("Añadir", "Carrito", FormMethod.Get, new { @class = "afegidorCarrito" })) { <fieldset> <input type="hidden" name="codigoArticulo" value="@Model.CodiArticle" /> <input type="hidden" name="resultController" value="@Model.Controller" /> <input type="hidden" name="resultAction" value="@Model.Action" /> <input type="hidden" name="resultRouteValues" value="@Model.RouteValues" /> <input type="text" name="cantidad" value="1" class="anadirCantidad" /> <input type="submit" /> </fieldset> } the problem I have is that resultRouteValues gets passed as a string instead of an object. Is there any way to fix this? Thanks. A: No, there is no easy way if RouteValues is a complex object. You will have to serialize the object into some text representation into this hidden field and then deserialize it back in your controller action. You may take a look at MvcContrib's Html.Serialize helper.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567141", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OpenGL OES Iphone glCopyTexImage2D I am new to openGL OES on iPhone and have a memory issue with glCopyTexImage2D. So far i understood, this function should copy the current framebuffer to the binded texture. But for some reason it always allocates new memory, which i can see in instruments checking the allocations. My goal is to read texture images and draw on it, after drawing i want to save the new texture , so i can scroll through the painting. So here is may code: 1) init opengl and framebuffer: context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1]; if (!context || ![EAGLContext setCurrentContext:context]) { [self release]; return nil; } glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_SRC_COLOR); // Setup OpenGL states glMatrixMode(GL_PROJECTION); CGRect frame = self.bounds; CGFloat scale = self.contentScaleFactor; // Setup the view port in Pixels glOrthof(0, frame.size.width * scale, 0, frame.size.height * scale, -1, 1); glViewport(0, 0, frame.size.width, frame.size.height * scale); glDisable(GL_DEPTH_TEST); glDisable(GL_DITHER); glMatrixMode(GL_MODELVIEW); glEnableClientState(GL_VERTEX_ARRAY); // Set a blending function appropriate for premultiplied alpha pixel data glEnable(GL_POINT_SPRITE_OES); glTexEnvf(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE); glPointSize(64 / kBrushScale); 2) now i load the saved images into the framebuffer: if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { // load texture NSData* data = [[NSData alloc] initWithContentsOfFile:path]; glGenTextures(1, &drawBoardTextures[i]); glBindTexture(GL_TEXTURE_2D, drawBoardTextures[i]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, [data bytes]); // free memory [data release]; } 3) and finally render the texture: glEnableClientState(GL_TEXTURE_COORD_ARRAY); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); int width = 1024; GLfloat quad[] = {0.0,1024.0,1024.0,1024.0,0.0,0.0,1024.0,0.0}; GLfloat quadTex[] = {0.0,1.0,1.0,1.0,0.0,0.0,1.0,0.0}; for (int i=0; i<10; i++) { quad[0] = width * i; quad[2] = quad[0] + width; quad[4] = quad[0]; quad[6] = quad[2]; glBindTexture(GL_TEXTURE_2D, drawBoardTextures[i]); glVertexPointer(2, GL_FLOAT, 0, quad); glTexCoordPointer(2, GL_FLOAT, 0, quadTex); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindTexture(GL_TEXTURE_2D, 0); } 4) for now everything works fine, with gltranslatef i can scroll through the textures and also there is no allocation yet observed in instruments. so now i draw on the current window and want to save the result like followed: int texIndex = offset.x/1024; float diff = offset.x - (1024*texIndex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, drawBoardTextures[texIndex]); glBindTexture(GL_TEXTURE_2D, drawBoardTextures[texIndex]); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, diff, 0, 0, 0, 1024-diff, 1024); glBindTexture(GL_TEXTURE_2D, drawBoardTextures[texIndex + 1]); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 1024-diff, 0, diff, 1024); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glFlush(); No the problems starts. instead of writing it directly into the generated textures, it writes it into client memory. for every copied texture it uses ~4 MB of Ram, but every recopy doesn't need any memory. i really don't know what i did wrong. Does anyone know what the problem is? Thanks alot for your help. cheers chris
{ "language": "en", "url": "https://stackoverflow.com/questions/7567144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make content go over large border I have the following rules: .borderedCanvas{ border-width: 89px 95px; -webkit-border-image: url(/images/canvas_bg.png) 89 95 repeat stretch; -moz-border-image: url(/images/canvas_bg.png) 89 95 repeat stretch; border-image: url(/images/canvas_bg.png) 89 95 repeat stretch; width: 700px; } .borderedContent{ margin: -60px; width: 820px; display: block; } And the following html: <div id="login" class="borderedCanvas"> <div id="loginBox" class="borderedContent"> <form> ... </form> </div> </div> It creates a ~90px wide border around the div I apply it to. Now I want that every content inside borderedCanvas divs gets expanded to inside the border 60px. This is because although I had to use ~90px, the real border appears as if it is only 20px. I tried the adding the following rule to .borderedCanvas it had no effect: padding: -60px; A: Actually, don't forget that you're using CSS3, and while you're using CSS3 you can use CSS2. And CSS2 have pseudo-elements and all other juicy things! So, you can achieve the thing you want without any extra elements just by using pseudo-elements like ::before! So, there is a fiddle: http://jsfiddle.net/kizu/UxJ8H/ The things worth mentioning: * *See how you can use negative z-index on a pseudo-element with positive on the element itself to put the pseudo-element user the content. *With CSS2 you can set the left+right and top+bottom values for absolute positioning at the same time, so you can position the pseudo-element like you want. So, combining pseudo-elements with border-image and positioning you can active a loooot of effect just like this easy. A: Negative padding does not work... Padding is the inner-fill of an element, not the outer. Use margin: -60px instead. A: http://www.w3.org/TR/css3-background/#border-image-outset https://bugzilla.mozilla.org/show_bug.cgi?id=564699 https://bugzilla.mozilla.org/show_bug.cgi?id=497995 this will be shipped in next revisions of browsers, and will work like a negative padding, but only relative to border-image, and only if border-image is supported with negative margins, in fact, you will break appearance in older browsers! for now you need to insert, as you do, a wrapper element inside the bordered content: <div class="borderimg"> <div class="fixpos" style="margin:-20px;"> your content here </div> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7567148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Setting Color Using Number in C# I can set a colors to object using Brush as follows: Brushes.Red How to apply the same using numbers, say, SetColor("#ffffff"); The above is an imaginary example. A: You can use ColorTranslator.FromHtml EDIT - In response to your comment, you can create a brush based on your colour: SolidBrush brush = new SolidBrush(ColorTranslator.FromHtml("#ffffff")); A: You can make Brushes with your own Color: Color col = Color.FromArgb(255, 255, 255); SolidBrush br = new SolidBrush(col); Hope that helps. A: Color color = Color.FromRgb(255, 255, 255); i assume you know how to calculate the values? A: In WPF: var x = (Color)ColorConverter.ConvertFromString("#faffff"); A: I think you are looking for the Color.FromArgb method. It has an overload that allows specifying the color as an integer number. A: Color c = (Color)((new ColorConverter()).ConvertFromString("#ffffff"));
{ "language": "en", "url": "https://stackoverflow.com/questions/7567149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: naudio streaming position I'm playing mp3 file from Internet using BufferedWaveProvider in NAudio library. How can I get information about the current position and the length of the track? Is it possible? A: You can calculate the current position using the number of bytes that have been read from the Read method of your BufferedWaveProvider, and use the WaveFormat's AverageBytesPerSecond property to turn this into a TimeSpan. As for the duration of the MP3 file, unfortunately this will be unknown until streaming has finished.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567150", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirecting bad url links from external sites with .htaccess I have two inbound links that land on 404 pages because the links are squiffy. I have tried 301'ing these links as normal but without success, I believe because of the characters used from this external URL. Column<u>Radiators.html is the page suggested on this external site and Column_Radiators.html is the actual page. also Bath%3Cu%3EFiller.html on the external site and Bath_Filler.html on our actual website. How can I succesfully redirect these pages? A: Simply add these lines in your .htaccess redirect 301 /Column<u>Radiators.html /index.html redirect 301 /Bath<u>Filler.html /index.html Note: I use index.html as the default redirection but you can use a custom 404.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can I use Unicode characters in HTTP headers? Is HTTP headers limited to US-ASCII charset? Can I use unicode characters in HTTP headers? Edit: I want to do like this: WebClient myWebClient = new WebClient(); myWebClient.Headers.Add("Content-Type","یونیکد"); A: First of all, the header field in your example does not allow what you want; media type names are ASCII. In theory, HTTP header field values can transport anything; the tricky part is to get all parties (sender, receiver, and intermediates) to agree on the encoding. Thus, the safe way to do this is to stick to ASCII, and choose an encoding on top of that, such as the one defined in RFC 5987. A: Accept-Charset: iso-8859-5, unicode-1-1;q=0.8 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7567154", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Don't display .pyc files in the Xcode 4 project navigator I'm working on a fairly large django-project in Xcode 4. I prefer not to see all the automatically generated .pyc files in the project navigator. Does anyone know a way to hide the .pyc files from the interface? I don't necessarily want to remove them from disk. Thanks. - What fails: * *Checking "Show only files with source-control status" hides all files except the .pyc files... If only there is a way to invert this selection. *Showing files with matching name will also only give me a solution for solely showing the .pyc files. Typing ".py" also yields .pyc files... A: The best I can come with is the way I do it: By dragging only the .py files into the XCode project at the start. It's not ideal; there should be a way to filter out build files. This method also isn't great for sub-folders, since you have to create each folder and then drag the .py files in for each folder by hand. But it works, and now I have no .pyc files in my project. Also, irritatingly, I can't delete .pyc files from the project once they're in there, so controlling things from the outset is the only solution I found. A: given that this has not been answered directly here is an alternative solution using another programming software which is Coda 2. You can create a rule that will hide those files, here is how to proceed : * *First open your preferences from the main menu *Second go to the rules tab and create a new rule using the lower left "+" button *Give the rule a name, such as "Python compiled Files" *Select "Hide" from the right menu instead of "Skip" *Edit the first rule as showed to apply it to files which "Name" ends with "pyc" *Close the preferences pane and voilà, you are all set to keep being an efficient Coda user This is taken from this website for sourcing purpose. It contains images illustrating this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does List(1,2,3) work in Scala? How does this work in Scala? val something = List(1,2,3) List is abstract, and you can't construct it by invoking new List(), but List(1,2,3) works just fine. A: Because it is a call to the apply method of the list companion object. In scala, a method called apply can be called with the method name ommitted (i.e. just with parens). It is by this mechanism that sequence and Map access works Hence, List(1, 2, 3) is in fact: List.apply(1, 2, 3) So this is then a call to the apply method of List's companion object, the implementation of which is: override def apply[A](xs: A*): List[A] = xs.toList So you can see that apply is a method which takes a repeating parameter (a sequence), and calls the toList method on this sequence. This toList on Seq is inherited from TraversableOnce: def toList: List[A] = new ListBuffer[A] ++= seq toList So you can see that this creates a list via a ListBuffer and the ++= method: override def ++=(xs: TraversableOnce[A]): this.type = if (xs eq this) ++= (this take size) else super.++=(xs) This ultimately gets its implementation of ++= from Growable: def ++=(xs: TraversableOnce[A]): this.type = { xs.seq foreach += ; this } Invoking new List() does not work because List is a trait (and a sealed one at that) - you would have had to apply implementations for the abstract methods. The fact that it is sealed means that it can only be implemented by a class in the same source file. A: List(1,2,3) is "magic syntax" to call the apply method in the companion object of trait or class List.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Using extern variables in visual studio 2010 I tried defining int GlobalVariable; in FileA.cpp and inside FileB.cpp, I tried to use GlobalVariable by declaring extern int GlobalVariable; but when I tried using GlobalVariable, I get 'GlobalVar' : undeclared identifier or some unresolved linking error, how do I go about making it work? A: (Without having your code) Use this pattern: FileA.h extern int GlobalVariable; FileA.cpp int GlobalVariable = 1000; A: First of all, you're defining a variable called GlobalVariable but in the error message the variable GlobalVar is mentioned. Make sure that you don't accidentally get the name wrong. That being said, are you sure that FileA.cpp is compiled into whatever module FileB.obj (the object file generated from FileB.cpp) is built into?
{ "language": "en", "url": "https://stackoverflow.com/questions/7567161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wrong month name in russian I'm working on a site and my customer is from Russia. He said that the month translation in the news is wrong. For example, September: * *I get this from php: Сентябрь *and this from him: Сентября How can I overwrite this? Clarification: When using the locale ru_RU, the name of the month outputted will be Russian. But according to my client the name of the months is wrong. I don't speak Russian so I have no idea if he's right or wrong I just saw that if I translate the date from this: 8th of September 2011 to Russian it will look like this: 8 сентября 2011. See the translation. So the solution to the problem would probably be to rewrite the date format. I haven't fixed this yet; apparently this is a bug/missing feature because of the advance Russian declensions. And the date format I need doesn't exist. I think this affects strftime and PHP date(). Can someone verify this? A: I know it's too late now but hope that will save someone's time. Russian language is considered to be the hardest one in the world. In this case the right variant is definitely Сентября. You can say 'That's September now' which would be 'That's Сенбярь now'. But if you are referring to the date like 'Tomorrow is the 6th of September' then in Russian that would change to 'Tomorrow is the 6 Сентября". Changing the locale to ru_RU apparently does not know this, so here is a simple solution to fulfil this task: (Assume $date is in d.m.Y format) function russianDate($date){ $date=explode(".", $date); switch ($date[1]){ case 1: $m='января'; break; case 2: $m='февраля'; break; case 3: $m='марта'; break; case 4: $m='апреля'; break; case 5: $m='мая'; break; case 6: $m='июня'; break; case 7: $m='июля'; break; case 8: $m='августа'; break; case 9: $m='сентября'; break; case 10: $m='октября'; break; case 11: $m='ноября'; break; case 12: $m='декабря'; break; } return $date[0].'&nbsp;'.$m.'&nbsp;'.$date[2]; } A: Too late I know but you may use a date formatter with "LLLL" it's a stand alone month name. Just wanted to share a piece of information I've just found. :) A: If your customer really wants "Сентября" then a simple str_replace() would do the job. Where you display month names, try : str_replace("Сентябрь", "Сентября", $month); A: You could put a simple if statement in to override the month name: // Shorthand if echo $month_name == "Сентябрь" ? "Сентября" : $month_name; or // Normal if if ($month_name == "Сентябрь") { echo "Сентября"; } else { echo $month_name; } A: @tsabz's answer is probably the solution, because the error is inside PHP. That, or there is some kind of dialect in Russia that needs to be set instead. Implementing @tsabz's answer into Typo3 requires you xclassing tslib_content (ie. tslib_cObj). This can be done by adding the following line to you typo3conf/localconf.php or better yet, in a custom extension inside typo3conf/ext/your_ext/ext_localconf.php: $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['tslib/class.tslib_content.php'] = PATH_typo3conf.'ext/your_ext/xclass/class.ux_tslib_content.php'; Then create the file typo3conf/ext/your_ext/xclass/class.ux_tslib_content.php and put in the following: <?php class ux_tslib_cObj extends tslib_cObj { /** * date * Will return a formatted date based on configuration given according to PHP date/gmdate properties * Will return gmdate when the property GMT returns true * * @param string Input value undergoing processing in this function. * @param array stdWrap properties for date. * @return string The processed input value */ public function stdWrap_date($content = '', $conf = array()) { $content = parent::stdWrap_date($content, $conf); $content = str_replace("Сентябрь", "Сентября", $content); return $content; } } A: I know it's a bit later, but others might come across this question too, so might still be worth answering. The answer from @hraban comes closest to explaining it, all other answers are only providing (partly unsatisfactory) workarounds: Both php and the customer are correct! The issue is that your customer expects the month name (and probably all month names) in the genitive case, see this page. The string formatter you are using is not respecting the Russian grammar :-( This is unfortunately a tricky thing :-( Thus, you will have to do implement some workaround, as provided by others. A: setlocale(LC_ALL, 'ru_RU.UTF-8'); strftime('%B',strtotime($time)); A: Whenever you write a date in Russian a month name must be in genetive. To avoid messing with locale I came up with this solution: $monthGenetive = (new \IntlDateFormatter( 'ru_RU', \IntlDateFormatter::FULL, \IntlDateFormatter::FULL, 'Europe/Moscow', \IntlDateFormatter::GREGORIAN, 'MMMM'))->format(new \DateTime('@' . strtotime($datum))); where $datum is the date in whatever format strtotime would accept. PHP docs and mysterious 'MMMM' explained. Make sure intl extension is on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Android: Question about TTS use I'm using a TTS engine, and i want to disable the buttons until the tts message has finished, so the user can't select an option on the screen until the tts message has been listened completely. I've been trying using while (tts.isSpeaking()) { button.setclickable(false); } button.setclickable(true); but it's not working. I guess that is because tts.isSpeaking doesn't work as i expected. A: check the Utterance concept with this TTS using this you can implement your task check here http://developer.android.com/resources/articles/tts.html http://developer.android.com/reference/android/speech/tts/TextToSpeech.html#setOnUtteranceCompletedListener%28android.speech.tts.TextToSpeech.OnUtteranceCompletedListener%29
{ "language": "en", "url": "https://stackoverflow.com/questions/7567170", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use $.get() inside success: function(data) {... in $.ajax().? Can I use $.get() or $.ajax() inside of success: function(data) {... in $.ajax() ? Like: $.ajax({ url: 'ajax/test1.html', success: function (data) { $('.result').html(data); $.get("test2.php", function (data) { alert("Data Loaded: " + data); }); } }); Or $.ajax({ url: 'ajax/test1.html', success: function (data) { $('.result').html(data); $.ajax({ url: 'ajax/test2.html', success: function (data) { $('.result').html(data); alert('Load was performed.'); } }); } }); Does this work correctly? Which of those is best? If it does not work, how would I do it correctly? A: Yes, it's possible to do both. The $.get() is equivalent to: $.ajax({ url: url, data: data, success: success, dataType: dataType }); See in http://api.jquery.com/jQuery.get/
{ "language": "en", "url": "https://stackoverflow.com/questions/7567173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to specify Character Spacing in SSRS/BIDS? I am trying to create a SSRS report. The report is essentially as certificate which will be printed on Custom Stationary (Some arty paper like certificates). The system we are migrating from used Word mail merge to specify the Certificate holder's name, certification date etc. Now we are creating an SSRS report which would essentially generate the Certificate. The font used in the legacy system was Lucida Calligraphy with a Character spacing of 66%. (Attached comparison image) I could not locate a setting in BIDS to specify character spacing for fonts. Without the spacing things look a little weird and I'd rather not go and tell the client to change their stationary and/or printer because it'll be a logistics havoc. So the question is, is it possible to specify character spacing in SSRS/BIDS? If yes how? If no what are the alternatives? A: I was able to have correct character spacing by adding a space between each character and makeing that space to have a size of 8pt (because my text has a size of 16). It looks good in my report.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to send different sms messages to multiple recipients i have a somewhat challenging task.I have to write an application with PHP and MYSQL This application is intended to be an sms application that sends sms(text messages) to various job supervisors,reporting the messages that their subordinates have received. The application is meant to have a template; E.g :Message From Postmaster: Message From Auditor: etc. The messages for each subordinate are stored in a table and are retrieved for each subordinate for a given time period.Each subordinate has a job role which defines the kind of message he receives. That is:A postman has "pre-defined" people that can send a message.E.g The Postmaster,the Post-office....etc. An example showing the message format is: Message From Auditor:Bring Receipts To General Office Sent On Monday Message From Postmaster:Bring Stamps To Secretariat Sent On Monday Message From Security: Bring Details For Id Card Sent On Tuesday Message From Admin: Message From Supply: Two subordinates with the same job role can have different messages from the same person. E.g: Employee x who is a postman might receive "Report to General Office" from the Postmaster, while Employee y might receive the message "Add New Delivery Routes From Next Week" The phone numbers for the Supervisors are stored in a table. A supervisor can supervise multiple people who have different job roles. The major point where i will need assistance is on how to program the application to pick the phone number of the supervisor for each employee,get the templates for the employee's job role,and populate it with the messages for the employee and send it to the supervisor.Also, the employees can have more than 1 supervisor. I know i will need a loop(a "for-each" loop ??).. I am not also very knowledgeable about the procedure used in sending sms messages to people from a website with php, but i know it has to do with arrays. So in short...i need help on building arrays that will house the phone numbers,message-template and message template for a particular job role with individual messages and loop through them and send them to the recipients. I will really appreciate any help i can get and i will gladly supply my email to interested parties to further correspondence.THANKS A: It sounds like you need to learn some more PHP/MySQL before you'll be able to tackle this... The major part you need help with is straightforward, just some tables and queries... For the SMS, Google for "PHP SMS API" and you will find scads of options. I am not also very knowledgeable about the procedure used in sending sms messages to people from a website with php, but i know it has to do with arrays No this is not true. Arrays may be used to implement portions of the code used in doing so, but that statement is like saying building a website w/ PHP has to do w/ arrays... You might try the php-general mailing list for more help getting off the ground in your PHP coding, but there really isn't a specific question here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Expand path in TreeView using view model I have dates bounded to TreeView. There is a wrapper class for date. Dates groups by years and months. Wrapper class also has IsSelected and IsExpanded properties: public sealed class DateViewModel : NotificationObject, IEditableObject { #region properties bool _isSelected; public bool IsSelected { get { return _isSelected; } set { if (_isSelected != value) { _isSelected = value; RaisePropertyChanged(() => IsSelected); } } } bool _isExpanded; public bool IsExpanded { get { return _isExpanded; } set { if (_isExpanded != value) { _isExpanded = value; RaisePropertyChanged(() => IsExpanded); } } } DateTime _date; public DateTime Date { get { return _date; } set { if (_date != value) { _date = value; RaisePropertyChanged(() => Date); RaisePropertyChanged(() => Year); RaisePropertyChanged(() => Month); RaisePropertyChanged(() => MonthName); RaisePropertyChanged(() => Day); } } } public int Year { get { return Date.Year; } } public int Month { get { return Date.Month; } } public string MonthName { get { return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(Date.Month); } } public int Day { get { return Date.Day; } } #endregion properties } ObservableCollection of DateViewModel is used as ItemsSource for TreeView. Dates groups by CollectionViewSource ans DataTemplates: <DataTemplate x:Key="DayTemplate"> <TextBlock x:Name="textBlock" FontSize="14" Text="{Binding Path=Day}" /> </DataTemplate> <HierarchicalDataTemplate x:Key="MonthTemplate" ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource DayTemplate}"> <TextBlock Text="{Binding Path=Name}" /> </HierarchicalDataTemplate> <HierarchicalDataTemplate x:Key="YearTemplate" ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource MonthTemplate}"> <TextBlock> <Run Text="{Binding Path=Name, Mode=OneWay}" /> <Run Text="y" /> </TextBlock> </HierarchicalDataTemplate> <telerik:RadTreeView Grid.Row="1" ItemsSource="{Binding Path=Dates.View.Groups}" ItemTemplate="{StaticResource YearTemplate}"> <telerik:RadTreeView.ItemContainerStyle> <Style TargetType="{x:Type telerik:RadTreeViewItem}"> <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}" /> <Setter Property="IsExpanded" Value="{Binding Path=IsExpanded, Mode=TwoWay}" /> </Style> </telerik:RadTreeView.ItemContainerStyle> </telerik:RadTreeView> The issue is: I need to expand full path to date using view model by setting IsExpanded property to true. But it doesn't have effect. UPDATE: Yes I created group descriptions in code. The code for expanding is simple: public sealed class DatesViewModel { ObservableCollection<DateViewModel> _dates = new ObservableCollection<DateViewModel>(); public CollectionViewSource Dates {get; set;} public DatesViewModel() { Dates = new CollectionViewSource { Source = _dates } ; // add groups, sorts and fill collection ... } // Just a sample public void ExpandFirstDate() { _dates[0].IsExpanded = true; } } There is missing code above. Also I prepared test sample TreeViewGroupingSample.7z A: Your TreeView is binding to CollectionViewSource.View.Groups, and those PropertyGroupDescription objects do not contain IsSelected or IsExpanded properties, so your TreeViewItem.IsSelected and TreeViewItem.IsExpanded values have an invalid binding Your DatesViewModel.IsExpanded IS getting set to true with the code you are using. You can verify this by changing your Day template to show the value of IsExpanded I would recommend creating classes for each tier (Year, Month, and Day), and having them all inherit from something like a TreeNodeBase class which contains properties for IsSelected, IsExpanded, and ObservableCollection<TreeNodeBase> Children. Don't forget to hook up a PropertyChange notification for your Children so that when TreeNodeBase.IsExpanded gets changed, the parent object's IsExpanded value changes too
{ "language": "en", "url": "https://stackoverflow.com/questions/7567177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jquery- get different page elements I want to get element attribute value which belongs to other html page. For example if I am in file a.html and want to get data like element attribute value from b.html in a.html All I am trying to do in jquery. Please suggest! I read posts but I want like below- something like-> [Code of a.html] var result = get(b.html).getTag(img).getAttribute(src)//not getting exactly $("#id").append(result) any idea how can i achieve this? A: first you will have to fetch the b.html and then you can find the attribute value e.g. //if you dont want to display the data make the div hidden ^ $("#someDivID").load("b.html",function(data){ var value=$(data).find("#elementID").attr("attributeName"); }); A: With jQuery you can load only parts of remote pages. Basic syntax: $('#result').load('ajax/test.html #container'); The second part of the string is a basic jQuery selector. See the jQuery documentation. A: By default, selectors perform their searches within the DOM starting at the document root. If you want to pass alternate context, you can pass to the optional second parameter to the $() function. For eg, $('#name', window.parent.frames[0].document).attr(); A: Keep in mind that you can usually only make direct connections (like with $(..).load() to pages on the same domain you're currently on, or to domains that do not have CORS restrictions. (The vast majority of sites have CORS restrictions). If you want to load the content from a cross-domain page that has CORS restrictions, you'll have to make make the request through your server, and have your server make the request to the other site, then respond to your front-end script with the response. As for this question, if you want to achieve this result without jQuery, you can use DOMParser on the response text instead, to transform it into a document, and then you can use DOM methods on that document to retrieve the element, parse it as desired, and insert it (or data retrieved from it) onto the current page. For example: fetch('b.html') // replace with the URL of the external page .then(res => res.text()) .then((responseText) => { const doc = new DOMParser().parseFromString(responseText, 'text/html'); const targetElementOnOtherPage = doc.querySelector('img'); const src = targetElementOnOtherPage.src; document.querySelector('#id').insertAdjacentHTML('beforeend', `<img src="${src}">`); }) .catch((err) => { // There was an error, handle it here });
{ "language": "en", "url": "https://stackoverflow.com/questions/7567181", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Java split string on third comma I have a string that I need to be split into 2. I want to do this by splitting at exactly the third comma. How do I do this? Edit A sample string is : from:09/26/2011,type:all,to:09/26/2011,field1:emp_id,option1:=,text:1234 The string will keep the same format - I want everything before field in a string. A: If you're simply interested in splitting the string at the index of the third comma, I'd probably do something like this: String s = "from:09/26/2011,type:all,to:09/26/2011,field1:emp_id,option1:=,text:1234"; int i = s.indexOf(',', 1 + s.indexOf(',', 1 + s.indexOf(','))); String firstPart = s.substring(0, i); String secondPart = s.substring(i+1); System.out.println(firstPart); System.out.println(secondPart); Output: from:09/26/2011,type:all,to:09/26/2011 field1:emp_id,option1:=,text:1234 Related question: * *How to find nth occurrence of character in a string? A: a naive implementation public static String[] split(String s) { int index = 0; for(int i = 0; i < 3; i++) index = s.indexOf(",", index+1); return new String[] { s.substring(0, index), s.substring(index+1) }; } This does no bounds checking and will throw all sorts of lovely exceptions if not given input as expected. Given "ABCD,EFG,HIJK,LMNOP,QRSTU" returns ["ABCD,EFG,HIJK","LMNOP,QRSTU"] A: You can use this regex: ^([^,]*,[^,]*,[^,]*),(.*)$ The result is then in the two captures (1 and 2), not including the third comma.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IOS: error in app purchase I use in my app a section with app purchse but when I test it I have a problem and this is my result in console: response for request product data 2011-09-26 19:14:37.601 MyApp[1233:707] Feature: puzzle, Cost: 0.790000, ID: com.mycompany.MyApp.puzzle 2011-09-26 19:14:44.973 MyApp[1233:707] Review request cannot be checked now: (null) 2011-09-26 19:14:44.980 MyApp[1233:707] making paymentQueue updatedTransactions 2011-09-26 19:14:46.095 MyApp[1233:707] making paymentQueue updatedTransactions 2011-09-26 19:14:46.098 MyApp[1233:707] FAILED!!! 4B2D3ECB-784D-415E-B3EA-942D88BD5A23 practically when I start my app and push on in app purchase button I have an alert with "Impossible to connect to apple store" and this result in console. What's the problem? the code where I have the problem is: - (void) buyFeature:(NSString*) featureId onComplete:(void (^)(NSString*)) completionBlock onCancelled:(void (^)(void)) cancelBlock { self.onTransactionCompleted = completionBlock; self.onTransactionCancelled = cancelBlock; [MKSKProduct verifyProductForReviewAccess:featureId onComplete:^(NSNumber * isAllowed) { if([isAllowed boolValue]) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Review request approved", @"") message:NSLocalizedString(@"You can use this feature for reviewing the app.", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"Dismiss", @"") otherButtonTitles:nil]; [alert show]; [alert release]; if(self.onTransactionCompleted) self.onTransactionCompleted(featureId); } else { [self addToQueue:featureId]; } } onError:^(NSError* error) { NSLog(@"Review request cannot be checked now: %@", [error description]); [self addToQueue:featureId]; }]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Winforms Individually Format Double Values in ComboBox I need to individually format items in a combo box in C#/Winforms. The combo box contains a set of doubles taken from a set of objects assigned to it (e.g., 1, 1.01, 1.02, 1.03 etc.) What I need to do is format them so that the read (1.0, 1.01, 1.02, 1.03 etc.) not (1.00, 1.01, 1.02 etc.) I know that the format string property can be used to format the whole collection, but is there a way to do some form of conditional formatting on the item collection by crating a user control? A: You can format each item individually by supplying a handler for the Format event. The event handler looks like this: private void comboBox1_Format(object sender, ListControlConvertEventArgs e) You can then modify e.Value as you so wish.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567198", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: match rows that have a certain count if aggregating on another column I have a single table with these fields: Url, IP, input I would like to retrieve all Urls (and corresponding IPs) that have a different IP with different input example: Url1, IP1, input1 Url2, IP2, input1 Url3, IP3, input1 Url1, IP4, input2 Url2, IP5, input2 Url3, IP3, input2 Url4, IP3, input2 I was trying to get a result like this: Url1, IP1, input1 Url1, IP4, input2 Url2, IP2, input1 Url2, IP5, input2 as Url3 gets the same IP3 on different inputs, I don't want it in the result also, I do not want Url4 because it's only in input2 I've search for subqueries and joins (on same table), but finally ended doing it in an external script: is there a way to do it directly in SQL A: Try using GROUP BY, HAVING and sub selects: create table your_table (Url varchar(50),IP varchar(50), input varchar(50)); insert into your_table (Url, IP, input) values ('Url1', 'IP1', 'input1'); insert into your_table (Url, IP, input) values ('Url2', 'IP2', 'input1'); insert into your_table (Url, IP, input) values ('Url3', 'IP3', 'input1'); insert into your_table (Url, IP, input) values ('Url1', 'IP4', 'input2'); insert into your_table (Url, IP, input) values ('Url2', 'IP5', 'input2'); insert into your_table (Url, IP, input) values ('Url3', 'IP3', 'input2'); select * from your_table where (Url,IP) in ( select Url, IP from ( select Url, IP, count(*) from your_table group by Url, IP having count(*) = 1 ) a ); A: A GROUP BY would do SELECT MIN(Url), IP, input FROM YourTable GROUP BY IP, input
{ "language": "en", "url": "https://stackoverflow.com/questions/7567200", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sql server 2008 r2 ee new query opening problem i am trying to execute a query in a newly installed sql server 2008 r2 express edition it just popup a window asking to connect to sql server compat edition , i am unable to change the server type also, how to avoid this
{ "language": "en", "url": "https://stackoverflow.com/questions/7567201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to check for installed browsers using C# for newbies I am building an app and its a simple one, all I want it to do is display os information in plain english and the architecture as well as check for installed browsers and then I'll add the ability for it to delete cookies and what not. What Im stuck on is the browser detection part. Can anyone point me to some decent tutorials or how tos? Thanks. Edit: OK I managed to finally scratch out some working code using the snippet provided by hcb below and the comments from the others (thanks everyone). So far it is doing exactly what I want so I thought id share what I have for those trying to do the same thing: RegistryKey browserKeys; browserKeys = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Clients\StartMenuInternet"); if (browserKeys == null) { browserKeys = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Clients\StartMenuInternet"); } string[] browserNames = browserKeys.GetSubKeyNames(); foreach (string browser in browserNames) { using (RegistryKey tempKey = browserKeys.OpenSubKey(browser)) { foreach (string keyName in tempKey.GetValueNames()) { if (tempKey.GetValue(keyName).ToString() == "Internet Explorer") { internetExplorerButton.Enabled = true; internetExplorerButton.BackgroundImage = Properties.Resources.iExplorer; if (internetExplorerButton.Enabled == true) { Label ieLabel = new Label(); ieLabel.Text = "Found!"; explorerLable.Text = ieLabel.Text; } } To my extreme annoyance, I noticed that Google want to install their browser in the Local App Data. I managed to work this out writing the code again separately and checking: Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Google\Update\Clients"); Edit2: Checking CurrentUser for Chrome seems to work fine for a few friends so it must be OK. A: Like this: RegistryKey browserKeys; //on 64bit the browsers are in a different location browserKeys = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\WOW6432Node\Clients\StartMenuInternet"); if (browserKeys == null) browserKeys = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Clients\StartMenuInternet"); string[] browserNames = browserKeys.GetSubKeyNames();
{ "language": "en", "url": "https://stackoverflow.com/questions/7567202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Nested group in Orbeon xforms Please anyone let me know if group within a group works in Orbeon xforms. I have tried this but the inner group is not working. The code might look like this: <xforms:group ref=".[condition1]"> //outer group ... ... <xforms:group ref=".[condition2]"> //inner group ... ... </xforms:group> ... ... </xforms:group> A: Yes, you can use groups within groups in XForms, and Orbeon Forms in particular. If you're having a problem with this, I suggest that you update your question with a full but minimal example that shows the issue, so we can further help with this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Overlapping axis labels when setting base_size in ggplot2 I'm changing base_size via theme_set. When I view the resulting plot on screen, it looks great. However, when I save it as a pdf, the x-axis label is a bit too close to the axis numbers. One small thing: theme_set(theme_bw(base_size = 9)) doesn't cause any problems but theme_grey(theme_bw(base_size = 9)) does. Here is an example graph: R Code require(ggplot2) theme_set(theme_bw(base_size = 9)) #Data m = c(0.475, 0.491, 0.4800, 0.4318, 0.4797, 0.5718) m = c(m, 0.00252, 0.00228, 0.00254, 0.00291, 0.00247, 0.00201) m = c(m, 0.306, 0.260, 0.3067, 0.3471, 0.3073, 0.2357) s = c(0.0172, 0.0681, 0.0163, 0.0608, 0.0170, 0.1088) s = c(s, 0.000087, 0.000367, 0.000091, 0.000417, 0.000094, 0.000417) s = c(s, 0.0092, 0.0447, 0.0110, 0.0593, 0.0113, 0.0504) df = data.frame(m=m, s=s) df$data_set = as.factor(c("Data set 1", "Data set 2")) df$est = factor(rep(c("A", "B", "C"), each=2)) df$par = rep(c("c1", "c2", "c3"), each=6) g = ggplot(data =df, aes(y=est, x=m)) + geom_point() + geom_errorbarh(aes(xmax = m + 2*s, xmin = m-2*s), width=0.1) + facet_grid(data_set~par, scales="free_x") + xlab("Parameter value") + ylab("") g pdf("figure3.pdf", width=7.5, height=3.5) print(g) dev.off() A: By default ggplot2 make axis titles so close to axis text. A trick is to insert a newline character \n in the string xlab("\nParameter value") + ylab("") A: I think it could be an issue with pdf. Using ggsave with vjust = -0.5 worked for me. I would replace the last three lines of your code with ggsave('figure3.pdf', g + opts(axis.title.x = theme_text(vjust = -0.5)), width = 7.5, height = 3.5) Here is the output.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Display colon separated values in postgres I am using postgresql 8.1 and i dont have the new functions in that version. Please help me what to do in that case? My first table is as follows unit_office table: Mandal_ids Name 82:05: test sample 08:20:16: test sample Mandal Master table: mandal_id mandal_name 08 Etcherla 16 Hiramandalam 20 Gara Now when I say select * from unit_office it should display: Mandal Name of office Hiramandalam, Gara test sample i.e in place of ids I want the corresponding names (which are in master table)separated by comma I have a column in postgres which has colon separated ids. The following is one record from my table. mandalid 18:82:14:11:08:05:20:16:83:37:23:36:15:06:38:33:26:30:22:04:03: When I say select * from table, the mandalid column should display the names of the mandals in the id place separated by a comma. Now i have the corresponding name for the id in a master table. I want to display the names of the ids in the select query of the first table. like my first table name is unit office. when i say select * from unit office, I want the names in the place of ids. A: I suggest you redesign your tables, but if you cannot, then you may need to define a function, which will split the mandal_ids string into integers, and map them to names. I suggest you read the PostgreSQL documentation on creating functions. The "PL/pgSQL" language may be a good choice. You may use the functions string_to_array and array_to_string. But if you can, I suggest you define your tables in the following way: mandals: id name 16 Hiramandalam 20 Gara unit_offices: id name 1 test sample mandals_in_offices: office_id mandal_id 1 16 1 20 The output from the following query should be what you need: SELECT string_agg(m.name,',') AS mandal_names, max(o.name) AS office_name FROM mandals_in_offices i INNER JOIN unit_offices o ON i.office_id = o.id INNER JOIN mandals m ON i.mandal_id = m.id GROUP BY o.id; The function string_agg appeared in PostgreSQL version 9, so if you are using older version, you may need to write similar function yourself. I believe this will not be too hard. A: Here's what we did in LedgerSMB: * *created a function to do the concatenation *created a custom aggregate to do the aggregation. This allows you to do this easily. CREATE OR REPLACE FUNCTION concat_colon(TEXT, TEXT) returns TEXT as $$ select CASE WHEN $1 IS NULL THEN $2 ELSE $1 || ':' || $2 END; $$ language sql; CREATE AGGREGATE concat_colon ( BASETYPE = text, STYPE = text, SFUNC = concat_colon ); Then you can: select concat_colon(mycol::text) from mytable; Works just fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567220", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: how to merge two or more one dimensional boost::multi_array s? I want to learn how to add an one dimensional multi_array to end of another one dimensional multi_array. How would i do that? A: Boost multi-array has (not very well documented) iterators like any other container, so you can use them as normal. #include <boost/multi_array.hpp> #include <iostream> int main (int ac, char **av) { typedef boost::multi_array<int, 1> array_type; array_type::extent_gen extents; //create some arrays array_type A(extents[3]); array_type B(extents[2]); //assign values A[0] = 4; A[1] = 3; A[2] = 5; B[0] = 1; B[1] = 2; //resize A, (copies original values) A.resize(extents[A.size()+B.size()]); //use iterators for copying std::copy(B.begin(), B.end(), A.end()-B.size()); //check the output. for(size_t i=0;i<A.size();++i){ std::cout<<A[i]<<std::endl; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567226", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hot republishing/deploying of static xhtml files issues I'm noticing a lot of issues operating the "hot deploying" of JSF pages in the following environment: * *Eclipse Indigo(latest version) *Tomcat 5.5 *JSF 1.2 *Facelets View Handler I noticed that, if I modify an already rendered xhtml page (for example the CSS style of an element) and then re-publish(through Eclipse or manually copying the xhtml file inside Tomcat) this page (maintaining the servlet container up), it doesn't show me the current changes. I also, in vain, setup the following configuration on my web application: <Context docBase="mywebapp" path="/mywebapp" reloadable="true" cachingAllowed="false"> My last tought is that the Restore-View Phase of a typical JSF page processing, does not check if the client-view (the xhtml page of course) has changed from the last time it has been loaded in the FacesContext. If so, how can i force the building of a new UIViewRoot object for each submitted request?? I'm a lot frustrating in restarting the tomcat server for each change in jsf pages. Thanks a lot for your support. A: Try adding the following to your web.xml config file: <context-param> <param-name>facelets.DEVELOPMENT</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>facelets.REFRESH_PERIOD</param-name> <param-value>1</param-value> </context-param> It tells JSF to re-render the Facelet. See how I put "1". In a Prod environment you would always put "-1" to disable this feature, since the facelets shouldn't be changing in a Prod environment. You also need to make sure you can Hot Deploy class and JSP resources. You can find how to do that here: http://ducquoc.wordpress.com/2010/11/06/eclipse-wtp-tomcat-hot-deploy/
{ "language": "en", "url": "https://stackoverflow.com/questions/7567228", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Data can be inserted directly from SP but fails if the SP is called from the application I am trying to insert a record through my application by calling a stored procedure. When the stored procedure is executed though, I'm getting the following error: "Error converting data type nvarchar to datetime.Error converting data type nvarchar to datetime." This error is only shown when I send a date, but if I trace each parameter and execute the SP directly from the database, it is executed perfectly without any errors. What might be the reason? I cannot post the code because it is spread across several layers. A: How are you sending in the dates? Are you sending in a DateTime or are you sending in a formatted "date" string? If the later, look at the actual date string being sent in (hint: You can use SQL profiler to watch what is actually being sent in). Then try to run the stored procedure in SQL management studio. Most likely it will bomb due to your date format. Solution (if I have the correct assumptions): Changing to an actual DateTime struct will solve your issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Does Xpath standard support null value in attribute for example is the following xpath string valid: /web:input_text[@value=null] which means the element doest not has a value attribute. A: This XPath returns web:input_text which don't have value attribute: /web:input_text[not(@value)] XPath /web:input_text[@value=null] selects web:input_text which have value of value attribute = null node. A: Try /web:input_text[not(@value)] instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: NHibernate and ADO.NET Connection Pooling It seems that NHibernate does not pool ADO.NET database connections. Connections are only closed when the transaction is committed or rolled back. A review of the source code shows that there is no way to configure NHibernate so that it is closing connections when the ISession is disposed. What was the intent of this behaviour? ADO.NET has connection pooling itself. There's no need to hold them open all the time within the transaction. With this behaviour are also unneccessaryly distributed transactions created. A possible workaround described in http://davybrion.com/blog/2010/05/avoiding-leaking-connections-with-nhibernate-and-transactionscope/ therefore does not work (at least not with NHibernate 3.1.0). I am using Informix. The same problem seems to exisit for every other database (NHibernate Connection Pooling). Is there any other workaround or advice avoiding this problem? Here's a unit test reproducing the problem: [Test] public void DoesNotCloseConnection() { using (SessionFactoryCache sessionFactoryCache = new SessionFactoryCache()) { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromMinutes(10) })) { fixture.Setup(); // Creates test data System.Data.IDbConnection connectionOne; System.Data.IDbConnection connectionTwo; using (ISessionFactory sessionFactory = sessionFactoryCache.CreateFactory(GetType(), new TestNHibernateConfigurator())) { using (ISession session = sessionFactory.OpenSession()) { var result = session.QueryOver<Library>().List<Library>(); connectionOne = session.Connection; } } // At this point the first IDbConnection used internally by NHibernate should be closed using (ISessionFactory sessionFactory = sessionFactoryCache.CreateFactory(GetType(), new TestNHibernateConfigurator())) { using (ISession session = sessionFactory.OpenSession()) { var result = session.QueryOver<Library>().List<Library>(); connectionTwo = session.Connection; } } // At this point the second IDbConnection used internally by NHibernate should be closed // Now two connections are open because the transaction is still running Assert.That(connectionOne.State, Is.EqualTo(System.Data.ConnectionState.Closed)); // Fails because State is still 'Open' Assert.That(connectionTwo.State, Is.EqualTo(System.Data.ConnectionState.Closed)); // Fails because State is still 'Open' } } } The disposing of the NHibernate-Session does nothing since we are still in a transaction SessionImpl.cs: public void Dispose() { using (new SessionIdLoggingContext(SessionId)) { log.Debug(string.Format("[session-id={0}] running ISession.Dispose()", SessionId)); if (TransactionContext!=null) { TransactionContext.ShouldCloseSessionOnDistributedTransactionCompleted = true; return; } Dispose(true); } } Injecting a custom ConnectionProvider will also not work since the ConnectionManager calling the ConnectionProvider has several preconditions checking that closing a connection within a transaction is not allowed. ConnectionManager.cs: public IDbConnection Disconnect() { if (IsInActiveTransaction) throw new InvalidOperationException("Disconnect cannot be called while a transaction is in progress."); try { if (!ownConnection) { return DisconnectSuppliedConnection(); } else { DisconnectOwnConnection(); ownConnection = false; return null; } } finally { // Ensure that AfterTransactionCompletion gets called since // it takes care of the locks and cache. if (!IsInActiveTransaction) { // We don't know the state of the transaction session.AfterTransactionCompletion(false, null); } } } A: NHibernate has two "modes". * *Either you open the connection in your application, then it is up to the application to manage it. This "mode" is used when passing a connection to sessionfactory.OpenSession(connection). *Or the connection is created by NH. Then it is closed when the session is closed. This "mode" is used when not passing a connection to sessionfactory.OpenSession() There is some support for TransactionScope. It is most probably using the first "mode". Probably the connection is not hold by NH, but by the transaction scope. I don't know exactly, I don't use environment transactions. NH is using the ADO.NET connection pool by the way. You can also disconnect the session using ISession.Disconnect() and reconnect using ISession.Reconnect(). In the documentation you find: The method ISession.Disconnect() will disconnect the session from the ADO.NET connection and return the connection to the pool (unless you provided the connection). A: You can accomplish this by adding the following settings to your connection string. Pooling=true; Min Pool Size=3; Max Pool Size=25; Connection Lifetime=7200; Connection Timeout=15; Incr Pool Size=3; Decr Pool Size=5; Pooling: enables pooling for your app Min Pool: The minimum number of connections to keep open even when all sessions are closed. Max Pool: The max number of connections the app will open to the DB. When the max is reached it will wait for the number of seconds specified by Connection Timeout and then throw an exception. Connection Timeout: Maximum Time (in secs) to wait for a free connection from the pool Connection Lifetime: When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by Connection Lifetime. A value of zero (0) causes pooled connections to have the maximum connection timeout. Incr Pool Size: Controls the number of connections that are established when all the connections are used. Decr Pool Size: Controls the number of connections that are closed when an excessive amount of established connections are unused. http://www.codeproject.com/Articles/17768/ADO-NET-Connection-Pooling-at-a-Glance
{ "language": "en", "url": "https://stackoverflow.com/questions/7567233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Get list of all sql servers installed in the system I am trying to get list of all SQL Servers installed in the machine and populate them in a drop downlist. I have searched in google and tried the following: using System; using System.Data; using Microsoft.SqlServer.Management.Smo; namespace SMOTest { class Program { static void Main() { DataTable dt = SmoApplication.EnumAvailableSqlServers(false); if (dt.Rows.Count > 0) { foreach (DataRow dr in dt.Rows) { Console.WriteLine(dr["Name"]); } } } } } However I didn't find a reference for Microsoft.SqlServer.Management.Smo; What is the best way to get all the sqlserver names and populate it in a drop down list? A: If you dont find it than you can google it and than you can pass the reference of it the simplest way to achive it. Check this answer : http://social.msdn.microsoft.com/forums/en-US/sqlsmoanddmo/thread/883d89df-fb19-4b04-ab83-1006a3559476/ Do Install : Microsoft SQL Server 2008 Feature Pack, October 2008
{ "language": "en", "url": "https://stackoverflow.com/questions/7567236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Start video and play movie clip at the same time in Flash Is it possible (in AS2 or AS3) to have a button that starts a video as well as an MC at the same time? The idea being that the video will play alongside a movieclip that contains animated quotes from the dialog of the video, so syncing would be critical to. A: AS3. i presume that you already have a videoPlayer or some netstream and metadata handlers. and you have all the needed items on the stage. var playProgressTimer:Timer; var movieClip:MovieClip; function handlePlayButtonClicked ( e : MouseEvent ) : void { playProgressTimer = new Timer(100); playProgressTimer.addEventListener(TimerEvent.TIMER, onPlayProgressTick); playProgressTimer.start (); } function onPlayProgressTick ( e : TimerEvent ) : void { if (!netStream || !metaData) return; // getting the progress of the video var _playProgress:Number = netStream.time / metaData.duration; // setting the same progress to the movieclip you have. movieClip.gotoAndStop(int(_playProgress * movieClip.totalFrames )); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567237", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trying to create a pop-up UITableView with rounded corners Been racking my brains to no avail with this one - I want to have a UITableView pop up, so it's floating over the stuff underneath, but with rounded corners. I don't know whether I need to use a clipping path in a UIView's drawRect (which I can't get to do anything except show the table with square corners) or if there's something obvious I'm missing. I want to avoid the use of a graphic with rounded corners which I place a slightly smaller table on, though if it comes to it at least I know how to bodge it that way. Any help / pointers much appreciated! A: If I understand you correctly then this should help you: * *In your .m file add #import <QuartzCore/QuartzCore.h> *Add dependency from QuartzCore.framework *Add the below code to your viewDidLoad method: Code: tableView.layer.borderColor = [[UIColor darkGrayColor] CGColor]; tableView.layer.borderWidth = 1.0; tableView.layer.cornerRadius = 10.0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7567241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rotating Three20 TTPhotoViewController inside TabBarController Adding Three20 TTPhotoViewController on an empty UIWindow Rotation were working like a charm. But when I moved the TTPhotoViewController to be created from UINavigationController inside a UITabBarController it does not rotate at all. I made sure I return YES for every shouldAutorotateToInterfaceOrientation function. Does Three20 Photo Gallery work in side UITabBarController with rotation? How am I doing this? [[TTURLRequestQueue mainQueue] setMaxContentLength:0]; TTNavigator *navigator = [TTNavigator navigator]; navigator.persistenceMode = TTNavigatorPersistenceModeAll; navigator.window = [UIApplication sharedApplication].keyWindow; TTURLMap *map = navigator.URLMap; [map from:@"tt://appPhotos" toSharedViewController:[PhotoViewController class]]; [navigator openURLAction:[TTURLAction actionWithURLPath:@"tt://appPhotos"]]; Update 1: after reading some posts I can now rotate the images only inside the TTScrollView but the navigation bar is not rotating. Update 2: I have subclass-ed both UITabBarController and UINavigationController to override shouldAutorotateToInterfaceOrientation, but it did not help. A: I have weirdly solved my issue by removing the TabBarController from the Window object and when going back I add the TabBarController to the window again. A: You could just rotate the scrollView.. Anyway if you rotate the navController it would look weird when you pop the photoviewcontroller (if your gallery isn't rootViewController). I've rotated the scrollView and hided the navBar and bottom bar when going into landscape mode and it looks good.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Parse website in Windows Phone 7 I found that after some modification I can use Html Agility Pack for parsing websites in WP7. I can use LINQ but not XPath. I want to ask if there is some other (maybe) better way to parse websites in WP7 and if there si some tutorial. Thanks A: Scraping websites is generally a bad idea, unless you control them, as they can change their structure faster than you can update your app. If you are scraping your own site you'd be better off building an API to expose the data in a structure way that better meets your applications requirements. If you really must do this then the HtmlAgilityPack is the best solution currently available. If you really must do this then you'll give your users a faster, better experieince by building your own web service which acts as a proxy between your app and the other site. The advantages of this are: - needing to connect to the website less often (probably - assuming you can cache the parsed page) - faster parsing of the site/page/data - A faster app (as it has to do less processing - less data needing to be sent to the app
{ "language": "en", "url": "https://stackoverflow.com/questions/7567248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Problems with OnClickListener Hey am new to android , i just want to handle a click event , but i got problems ...thi sis my code: package karim.test; import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.Button; public class TestActivity extends Activity implements android.view.View.OnClickListener { private Button b1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1 = (Button) this.findViewById(R.id.button1); b1.setOnClickListener(this); } @Override public boolean onTouchEvent(MotionEvent event) { return true; } @Override public void onClick(View v) { } and i got this error : Description Resource Path Location Type The method onClick(View) of type TestActivity must override a superclass method TestActivity.java /Test/src/karim/test line 33 Java Problem can you please tell me whats wrong ???? Please Be specific !! A: My guess is that you're compiling with a Java 5 compiler (or Java 5 compiler settings in the IDE). In Java 5, @Override was only usable on a method overriding a method of a class, not an interface. It was extended to interface method overriding in Java 6. Change the compiler version, or remove the @Override annotation on the onClick method. A: public class TestActivity extends Activity{ private Button b1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1 = (Button) this.findViewById(R.id.button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub } }); } or in your case public class TestActivity extends Activity implements android.view.View.OnClickListener { private Button b1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b1 = (Button) this.findViewById(R.id.button1); b1.setOnClickListener(this); } @Override public boolean onTouchEvent(MotionEvent event) { return true; } @Override public void onClick(View v) { if(v==b1) { //button logic } } A: You don't need to have your Activity class implement OnClickListener. Get rid of that. You just need to define the listener and assign it to your button. Take a look at the official android docs: http://developer.android.com/guide/topics/ui/ui-events.html A: As an extension to "JB Nizet" answer: The neatest way to handle onClick-events is (in my opinion) to add the onClick-attribute to the XML-Layout definition. <Button android:text="Click Me!" android:onClick="doSomething" /> In your java-code: public void doSomething(View v){ // Do stuff here } This way, you can define a single method for every single onClick-event. This is available since API-Level 4 which corresponds to Android 1.6 A: Looks like you are using compiler below java 6 for your project in eclipse. Right click on your project, go to properties-->Java compiler. Make sure you have 1.6 selected in compiler compliance field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WP7 Mango RichTextBox support for copy&paste It seems that the RichTextBox control does not support copy&paste. Is it really so? I created a very simple application that had the control with some text in it and i could not select it. Are there properties that control this or it just does not work? thanks --oleg A: It does not support copy or paste unfortunately. If you want to be able to copy formatted text - allow users to switch the view to a TextBox with plain text.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Differences with CSS positioning between IE9 and Opera, and Firefox and Opera I have a problem with a site I am doing some maintanence on, the latest test version can be found here http://www.smithandgeorg.com.au/new/ If viewed in IE7-9 or Opera this page displays as intended, however in Firefox and Safari the menu is positioned so that it is against the left side of the screen (it's best seen rather than described). The problem seems to stem from my use of positioning. The #content element is positioned position:relative; top:0px; left:0px so that when the #menu element (which is nested inside) is positioned position:absolute; left:0px it will be pushed right up against the left side of the #content element, as happens correctly in IE9 and Opera. However Firefox and Safari seem to ignore the fact that #content is positioned relatively and just push #menu up to the left side of the screen. I tried to reproduce the problem in the simple page below, but everything worked as expected. <html> <body> <div style="border:1px solid red; width:100px; height:100px; position:relative; left:0px"> <div style="border:1px solid black; width:100px; height:100px; position:absolute; top:60px; left:20px"> </div> </div> </body> </html> Any help would be greatly appreciated :) A: Firefox usually ignores position:relative on table elements, but this can be fixed by adding display:block to #content: #content { position:relative; top:0; left:0; display:block; } SO question/answer about position:relative
{ "language": "en", "url": "https://stackoverflow.com/questions/7567256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VBA: Out of memory Error due to memory leak.... Can I manually call Garbage Collection? Novice programmer here. I have a code that copies 12 hours worth of data from a server and displays it in excel. My code takes the displayed code and exports it into a file, appending each 12 hours so that I can have a months worth of data. My problem is that after 20 days or so I run out of memory. Theoretically, it shouldn't take much more data than the original program and it running out of memory after 20 days says to me memory leak. In an old java program I had I just called the garbage collector with some frequency and the problem went away. Is there some way to do this in excel-vba? I've read about setting variables to nothing, but I have a lot of variables and I think the real issue has to do with it storing ALL of the read-in data as ram, and I don't know how to set that to zero. Other curious bit - after it crashed due to memory I cannot begin the program again without shutting down excel. So after crashing it doesn't delete things in memory? Thanks for any help A: As far as I understand your question, your Excel program is still running and remains open every day (that's what I've understood from after 20 days of running). Using a Set myVar = Nothing is still a best practice but let say you don't want to do this. What I can think of is to create a new Excel instance to run your code within and close your application at the end of your running code. Something like: 'Don't forget to add the reference .. 'Microsoft Excel X,X object library Sub myTest() Dim xlAPp As New Application ' your code Set xlApp = Nothing End Sub A: VBA doesn't have garbage collection in the traditional sense -- so the answer to your particular query is no -- but keeps a count of referencing. As such, to free memory, you need to do as you suggest and dereference your objects, whenever they're no longer needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AS3 calling a global function with out 'new' or having a static method I'm creating a utility function for debugging/logs, which I access by importing the class and calling new Log(params); Alternatively I change the function to a static, and rename it to It, then I can call it by Log.It(params) I'm wondering if it possible to set it up so I can simply call Log(params) similar to the trace command? function: package { public class Log { /** Gets the name of the function which is calling */ public function Log(prefix:String = "", suffix:String = "", params:* = null):void { var error:Error = new Error(); var stackTrace:String = error.getStackTrace(); // entire stack trace var startIndex:int = stackTrace.indexOf("at ", stackTrace.indexOf("at ") + 1); //start of second line var endIndex:int = stackTrace.indexOf("()", startIndex); // end of function name var lastLine:String = stackTrace.substring(startIndex + 3, endIndex); var functionSeperatorIndex:int = lastLine.indexOf('/'); var ClassSeperatorIndex:int = lastLine.indexOf(':'); var objectName:String = lastLine.substring(ClassSeperatorIndex+2, functionSeperatorIndex); var functionName:String = lastLine.substring(functionSeperatorIndex + 1, lastLine.length); //TODO: Loop through params trace(prefix +" " + "[" + objectName + "]" + " > " + functionName + " " + suffix); //TODO: Log to Array //TODO: Dispatch Event } } } A: You could create package level methods(I don't know if that's the correct term), here's an example: concat.as: package com.example.utils { public function concat(string1:String, string2:String):String { return string1.concat(string2); }// end function }// end package Main.as(document class): package { import com.example.utils.*; import flash.display.Sprite; import flash.events.Event; public class Main extends Sprite { public function Main():void { if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); }// end function private function init(e:Event = null):void { removeEventListener(Event.ADDED_TO_STAGE, init); var string1:String = "Hello"; var string2:String = "World"; var string3:String = concat(string1, string2); trace(string3); // output: HelloWorld }// end function }// end class }// end package
{ "language": "en", "url": "https://stackoverflow.com/questions/7567263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cant index table - MySQL server has gone away I am trying to index a field called category_id but I keep getting an error saying "MySQL server has gone away" in phpmyadmin About 100,000 rows of data. So what is the solution? Thanks A: If you have access to command line, try to index it from there not from phpmyadmin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Statically initialized array? I was using a the reviewer "codePro Tools" by google and it flagged the flowing: new Object[] { max } with "Statically initialized array" Explanation: An array initializer is being used to initialize an array. Recommendation * *The array should be initialized dynamically. are there a good reason for this? or is just better to ignore. this flag is on a section of rules called "code style". Thanks A: As always: it depends. It's a question of style. I personally can't see anything wrong with this at all. In this case, I think it would just obscure the code to initialise it dynamically. I use statically initialized arrays all of the time. Code style is very subjective and varies from project to project, not just from person to person. It's up to you to decide whether it's a good thing for your project. A: Take all automated code inspection tools with a grain of salt. They make recommendations, not issue commands. If you have a good reason for writing your code that way, and can articulate it well to yourself and others, then stick with your code and ignore CodePro.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NSSound crashing when trying to load a system sound Occasionally my Cocoa app crashes while trying to load a system sound. I've not been able to reproduce this myself, but a few users have sent me crash reports. The stack trace is always the same (see below). The app opens a modal dialog, the user clicks OK, the sound is loaded and crashes: [NSSound soundNamed:@"Hero"]; There are a few mentions of this issue on the web[1], but no resolutions. Please note that I'm loading the sound from the main thread and am not attempting to play it back. It crashes right away. Also, the sound file itself is not corrupted (I had one user email it to me and it matches the one I have installed). Crash log excerpt: Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_ACCESS (SIGBUS) Exception Codes: KERN_PROTECTION_FAILURE at 0x0000000009a0d204 VM Regions Near 0x9a0d204: shared memory 0000000009310000-0000000009511000 [ 2052K] r--/r-- SM=SHM --> MALLOC_TINY 0000000009a00000-0000000009c00000 [ 2048K] rw-/rwx SM=COW MALLOC_LARGE 0000000009c00000-000000000bc9c000 [ 32.6M] rw-/rwx SM=PRV Application Specific Information: objc[8625]: garbage collection is OFF Performing @selector(ok:) from sender NSButton 0x236510 Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 ??? 0x09a0d204 0 + 161534468 1 com.apple.audio.units.Components 0x7000ed9d AUHAL::AUHAL(ComponentInstanceRecord*, unsigned long, bool) + 775 2 com.apple.audio.units.Components 0x7002feff ComponentEntryPoint<DefaultOutputAU>::Dispatch(ComponentParameters*, DefaultOutputAU*) + 144 3 com.apple.CoreServices.CarbonCore 0x98487949 CallComponent + 223 4 com.apple.CoreServices.CarbonCore 0x98487992 CallComponentDispatch + 29 5 com.apple.CoreServices.CarbonCore 0x984f3b6c CallComponentOpen + 43 6 com.apple.CoreServices.CarbonCore 0x98486608 OpenAComponent + 426 7 com.apple.CoreServices.CarbonCore 0x98486688 OpenComponent + 24 8 com.apple.AppKit 0x9b810cd3 _initializeCA + 1115 9 com.apple.AppKit 0x9b811c23 -[NSSound _postInitialization] + 349 10 com.apple.AppKit 0x9b810609 -[NSSound initWithContentsOfURL:byReference:] + 263 11 com.apple.AppKit 0x9b812767 +[NSSound _searchForSoundNamed:] + 1044 12 com.apple.AppKit 0x9b8122de +[NSSound soundNamed:] + 227 1: http://lists.apple.com/archives/Cocoa-dev/2007/Oct/msg01159.html A: The resolutions (or rather workarounds) of the problem you mentionned were applied in Transmission changeset 3540: don't allow custom sounds and later in changeset 5577: supporting custom user sounds on Leopard. Unfortunately, the backtraces don't match and your crash log is from Snow Leopard or Lion so these solutions probably don't apply for you. I would suggest you to file a bug report to Apple.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can anyone tell me what 'fb:admins' could not be parsed as type 'fbid' means? I am doing my best to set up open graph on my website. It's all working ok and looking good on Facebook, but I'm getting this error message on my site: Object at URL 'http://www.thesocialnetworkingacademy.com' of type 'website' is invalid because the given value '159229554128788' for property 'fb:admins' could not be parsed as type 'fbid'. Can anyone tell me in fairly basic terms what I need to do to fix that? A: fb:admins has to be a user ID. This is telling you that the fb:admins value isn't a user ID. You need to put your user ID in there, or use an app ID with fb:app_id https://developers.facebook.com/docs/opengraph/ A: Your ID looks like a page ID rather than an admin ID. You need to supply the user ID of one or more admins for this page, or switch to an fb:app_id instead of an fb:admin meta tag. If you wish to stick with the fb:admin approach you can enter your Facebook username rather than the numeric ID, which is probably easier to debug and manage, you can find your user name on your profile page in the page URL eg if your page is facebook.com/johndoe then your username is johndoe. If you want to get your numeric ID for any reason you can find it by visiting: http://graph.facebook.com/johndoe You can then check that this is all working by using the Facebook debugger to test your site: http://developers.facebook.com/tools/debug Using the debugger is the best way to test it - Facebook will take ages to update it's cache of your pages, so you won't see the results of any changes you make for days otherwise. A: I had the same problem. You need an APP ID for that to work. A website is not an app. You must go to https://developers.facebook.com/apps and create a new APP. After the creation you will recieve an APPID. That is the id that you need. A: You can use multiple admin ids AND also an app id if you wish at the same time <meta property='fb:admins' content='5555555'> <meta property='fb:admins' content='7777777'> <meta property='fb:app_id' content='888777555555'> can find admin id by going to the opengraph page for a user, e.g. http://graph.facebook.com/gbirbilis can find app id by going to https://developers.facebook.com/apps A: In fact, lots of websites use fb_appid rather than fb_admins, like this mac video converter site. If you want to get your fb_admins ID, this page may help you A: I had the same problem and the problem was passing the app_id and admin_id like this: <meta content='{5555555}' property='fb:admins'> <meta content='{555555555555}' property='fb:app_id'> And it should be like this: <meta content='5555555' property='fb:admins'> <meta content='555555555555' property='fb:app_id'>
{ "language": "en", "url": "https://stackoverflow.com/questions/7567271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Python: right way to build a string by joining a smaller substring N times What is the right "pythonic" way to do the following operation? s = "" for i in xrange(0, N): s += "0101" E.g. in Perl it would be: $s = "0101" x $N A: Nearly the same as Perl: "0101" * N A: The most Pythonic way would be s = "0101" * N Other methods include: * *use StringIO, which is a file-like object for building strings: from StringIO import StringIO *use "".join; that is `"".join("0101" for i in xrange(N)` *use your algorithm. In an unoptimised world this is less good, because it is quadratic in the length of the string. I believe recent versions of Python actually optimise this so that it is linear, but I can't find a reference for that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to execute code dynamically in MySQL, similar to "execute immediate" in Oracle? Like EXECUTE IMMEDIATE in Oracle, is there any way to execute code dynamically in a MySQL stored procedure? I really want to use a prepared statement within a MySQL stored procedure, to generate a new SQL statement in each iteration of a loop. A: It actually doesn't work like what I wrote. I just code like: set @preparedstmt = concat('SELECT tid, LENGTH(message) len FROM ? where tid=? and first=1'); prepare stmt from prepared_stmt; execute stmt using v_tid; drop prepare stmt; Just take care of the table name,it shouldn't be replaced with the placeholder.So the @preparedstmt should be generated with concat method to make a statement,which is just replaced the parameters in conditions with placeholder,but not the table name. A: MariaDB is supporting EXECUTE IMMEDIATE ince 10.2 KB doc is : https://mariadb.com/kb/en/execute-immediate/
{ "language": "en", "url": "https://stackoverflow.com/questions/7567277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to apply Style sheet to label/textfield in iPhone? I have lots of labels in my application. Is there any way to apply common style sheet to all label rather than giving style to individual label? A: you can write a stylesheet class if you use THree20 Library by overriding TTDefaultStyleSheet. But if your need is minmal,try with custom class with styles written & reference those to UILabel's Like constants.h #define COLOR_VALUE [UIColor colorWithRed:0.5f green:0.5f blue:0.5f alpha:0.5f] then in your file call lblName.textColor = COLOR_VALUE But not sure you can write all styles using this method! A: Create simple UIFont and UIColor categories in your application, and provide semantic descriptions of the data you want to style. Or make “CASCADING STYLE” classes. This article will explain how: http://akosma.com/2010/06/03/objective-c-categories-as-stylesheets/ A: You cannot apply 'style sheet' to your native app UI. You can subclass a UILabel. Style it as you want (although there isn't much you can change other than font, color and background image) and use the custom label objects instead of default UILabel...
{ "language": "en", "url": "https://stackoverflow.com/questions/7567280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: STL set and map for the same user defined type I have a class for which I have defined comparison operator. Following is the code I wrote #include <set> #include <map> #include <list> template <typename _TyV> class Element { public: Element(_TyV in) : m_Label(in){} ~Element() {} bool operator < ( const Element & right) const { return m_Label < right.m_Label; } private: _TyV m_Label; protected: }; typedef Element<int> ElementType; int main ( int argc, char **argv) { std::set<ElementType> mySet; for ( int i = 0; i < 10; i++) { mySet.insert(ElementType(i)); } std::map<ElementType*, std::list<ElementType*> > myMapList; return 0; } I am confuse on how my std::map will work since the element I am interested in the std::map is pointer to the ElementType. What I actually want is to store actual data in std::set and use pointers to these element in the std::map Major confusion is around the less than operator A: Your map, std::map<ElementType*, std::list<ElementType*> > uses std::less on the key type as its comparator, as normal. std::less for pointer types is defined to produce a consistent ordering, but the ordering is based on the address only, not on anything that it might point to. So, your set sorts its contents according to the operator< in Element, but the map sorts them according to the actual pointer value of the key. That probably isn't what you want: (1) it makes different Element<int> objects containing the same m_Label value act as different keys in the map, and (2) it means the map will be in a different order from the set. But std::map can take an extra template argument to provide a comparator, so you can change that. You could write a comparator that takes two pointers, and compares the objects they point to. This assumes of course that once you've used a pointer as a key in the map, you ensure that the object it points to sticks around (in the set, I assume, but if not then insert boilerplate lecture about shared_ptr here). Since Element<int> is cheap to copy, it would almost certainly be better to use ElementType as the key instead of ElementType*. But if int is just standing in for something you'll use in future that's expensive to copy, then change the map comparator. You might not care about the order of elements in the map. If you don't, and if the only things you ever look up in the map are pointers to objects in the set, then using ElementType* as the map key without specifying a comparator should be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Own drag function in AS3 I need to develop my own drag function in AS3 (instead of using startDrag) because I'm resizing a MovieClip. I'm doing this: public class resizeBR extends MovieClip { var initialScaleX, initialScaleY; public function resizeBR() { this.addEventListener(MouseEvent.MOUSE_DOWN, initResize); this.addEventListener(MouseEvent.MOUSE_UP, stopResize); } public function initResize(e:MouseEvent):void { initialScaleX = e.target.scaleX; initialScaleY = e.target.scaleY; e.target.addEventListener(MouseEvent.MOUSE_MOVE, startResize); } public function startResize(e:MouseEvent):void { e.target.x += e.localX; e.target.y += e.localY; e.target.parent.parent.width += mouseX; e.target.parent.parent.height += mouseY; // Keep its own scale e.target.scaleX = initialScaleX; e.target.scaleY = initialScaleY; } public function stopResize(e:MouseEvent):void { e.target.removeEventListener(MouseEvent.MOUSE_MOVE, startResize); } } But the drag feature is not working fluently. I mean, when I drag a MovieClip from class resizeBR I need to move slowly my mouse cursor or it's not going to work propertly. resizeBR is a MovieClip as a child of another MovieClip; the second one is which I have to resize. What am I doing wrong? Thanks! A: Thanks all for your answers, but I found a great classes to do what I want. http://www.senocular.com/index.php?id=1.372 http://www.quietless.com/kitchen/transform-tool-drag-scale-and-rotate-at-runtime/ A: I'm not really sure if I completely understand what you mean. But I think your problem lies with your MOUSE_MOVE handler. In your current example you're resizing your target only when moving your mouse over the target. When you're moving your mouse fast enough it's possible your mouse leaves the target, casuing it to stop resizing. When I'm writing my own drag handlers I usually set the MOUSE_MOVE and MOUSE_UP listeners to the stage. Your class would end up looking something like this: public class resizeBR extends MovieClip { var initialScaleX, initialScaleY; public function resizeBR() { addEventListener(MouseEvent.MOUSE_DOWN, initResize); addEventListener(MouseEvent.MOUSE_UP, stopResize); } public function initResize(e:MouseEvent):void { initialScaleX = scaleX; initialScaleY = scaleY; stage.addEventListener(MouseEvent.MOUSE_MOVE, startResize); } public function startResize(e:MouseEvent):void { x += e.localX; y += e.localY; parent.parent.width += mouseX; parent.parent.height += mouseY; // Keep its own scale scaleX = initialScaleX; scaleY = initialScaleY; } public function stopResize(e:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_MOVE, startResize); } } A: There are a couple reasons the resizing is jumpy. First, like rvmook points out, you'll need to make sure you support the mouse rolling off of the clip while its being resized. Since there is not an onReleaseOutside type of event in AS3, you have to set listeners to the stage, or some other parent clip. If you have access to the stage, that is best. If not, you can use the root property of your resizable clip, which will reference the highest level display object you have security access to. Setting mouse events to the root is a little wonky, because for them to fire, the mouse needs to be on one of the root's child assets - whereas the stage can fire mouse events when the mouse is over nothing but the stage itself. Another reason you might be seeing some strange resizing behavior is because of using the localX/Y properties. These values reflect the mouseX/mouseY coordinates to the object being rolled over - which might not necessarily be your clip's direct parent. I tend to avoid having classes access their parent chain. You might want to consider placing the resizing logic in the clip you want resized, and not in one of its children. Here is simple self resizing example: package { import flash.display.MovieClip; import flash.events.MouseEvent; import flash.events.Event; public class ResizableBox extends MovieClip { public function ResizableBox() { addEventListener(MouseEvent.MOUSE_DOWN, startResize); } private function startResize(evt:MouseEvent):void { stage.addEventListener(MouseEvent.MOUSE_MOVE, handleResize); stage.addEventListener(MouseEvent.MOUSE_UP, stopResize); } private function stopResize(evt:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_MOVE, handleResize); stage.removeEventListener(MouseEvent.MOUSE_UP, stopResize); } private function handleResize(evt:MouseEvent):void { this.scaleX = this.scaleY = 1; this.width = this.mouseX; this.height = this.mouseY; } } } ResizableBox is set as the base class of a MC in the library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Remove layer from renderInContext I use this code to make a screenshot, CGFloat breed = 768; CGFloat hoogte = 975; CGSize afmeting = CGSizeMake(breed, hoogte); UIGraphicsBeginImageContext(afmeting); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)]; There are some layers (buttons and textlabels) that I don't want in the image. Is there a way to remove some layers from renderincontext? Now I use textLabel.hidden = YES before making the screenshot and set hidden to NO when finished. Also for the buttons and other labels. A: All the buttons and labels have their own layers. All these layers can be rendered to some graphical context. Now you are generating your self.view.layer as image, you could try to make another view that would consist only of items you do want to render (keeping your labels and buttons separate in another view that would overlap your "picture view") or you can in fact render all components one by one not including your buttons (though that would probably be more work than you do now). If you will consider making one view on top of another, bear in mind that all the inputs (touches and events) in the top view must be sent to bottom view if you want it to react accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EF4 Hiding / Substitution of underlying fields I have a data model like this in SQL Server: table Note - varchar NoteText - tinyint PriorityLevel In my code, Entity Framework turns it into a class like: class Note - string NoteText - byte PriorityLevel Also in code I have a PriorityLevel enum which makes my code more readable: public enum PriorityEnum : byte { NORMAL = 10, IMPORTANT = 20, URGENT = 30 } So, I would like to use that enum directly with my Note objects, like myNote.PriorityLevel = PriorityEnum.NORMAL rather than having to cast all the time like myNote.PriorityLevel = (byte)PriorityEnum.NORMAL. I already have a solution via use of Partial class declaration, but I wind up with two similarly-named properties that map to the underlying PriorityLevel, which is messy: class Note - string NoteText - byte PriorityLevel - PriorityEnum PriorityLevelEnum (gets/sets PriorityLevel) Naturally I would like my EF class to be defined simply like: class Note - string NoteText - PriorityEnum PriorityLevel FYI I'm using POCO generation of my EF entity classes, so I figure the solution may involve a change to the T4 templates that generate them, but I'm concerned I'm missing out on something simple. I think there may be a solution by changing field definitions in the EDMX designer but I worry that they might be overwritten next time I update the EDMX from the database definition. A: With current version of entity framework you will always need both properties because EF is not able to convert enums automatically and use them in mapping (that will change in future version). So your entity defined in EDMX must have byte property and your partial class must expose second property using the enum and make conversion to byte internally within getter and setter. What you can do is reduce accessibility of your former mapped property. The disadvantage of this scenario is that Linq-to-entities queries cannot use your enum property - they must use original byte property and code defining the queries must have access to that property. Modifying template to create enum properties for you would not be so easy because the template needs some information to differ between standard byte property and enum like property. You can involve some naming convention to infer enums but if you really like generic solution you must modify EDMX manually and use structural annotations to tell T4 template what enum type should be used for a related property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: No item in ListView Hy! I load data from my Db and I will show it in a ListView. Tha problem is that no item is shown. The Listcount is 1. The list gets the data from the db. No error occures. I have no idea why. Code: public class Main extends Activity { private ListView lv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); lv = ((ListView)findViewById(R.id.list)); Log.e("XXX List View",lv.toString()); onCreateDBAndDBTabled(); } private void onCreateDBAndDBTabled() { myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null); myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE + " (_id integer primary key autoincrement, name varchar(100), rate integer(1), eattime datetime)" +";"); List<String> list = new ArrayList<String>(); Cursor cursor = this.myDB.query(MY_DB_TABLE, new String[] { "name" }, null, null, null, null, null, null); if (cursor.moveToFirst()) { do { Log.e("XXX", "Courser Enter: " + cursor.getString(0)); list.add(cursor.getString(0)); } while (cursor.moveToNext()); } if (cursor != null && !cursor.isClosed()) { cursor.close(); } Log.e("XXX", "Coung:" + list.size()); ArrayAdapter<String> aa = new ArrayAdapter<String>(Main.this, android.R.layout.simple_list_item_1, list); lv.setAdapter(aa); } } Log: 09-23 08:49:30.030: ERROR/XXX(6673): Start 09-23 08:49:30.030: ERROR/XXX List View(6673): android.widget.ListView@43d13918 09-23 08:49:30.080: ERROR/XXX(6673): Courser Enter: EditText 09-23 08:49:30.090: ERROR/XXX(6673): Coung:1 Please help A: The code you have posted shows that you are creating an empty table, which means that the cursor will not contain any value. First insert something into the DB, then read it. A: First check your list object is null or not ......... then http://sudarmuthu.com/blog/using-arrayadapter-and-listview-in-android-applications http://www.dotnetexpertsforum.com/populate-listview-using-arrayadapter-in-android-t1437.html https://github.com/sudar/android-samples also check List list = new ArrayList(); size there are list is empty or not if empty try to get element.............
{ "language": "en", "url": "https://stackoverflow.com/questions/7567291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ViewFlipper with only 1 layout? Following is the xml code/ layout used for my activity: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:background="@color/white" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ViewFlipper android:layout_margin="6dip" android:id="@+id/layoutswitcher" android:layout_width="fill_parent" android:layout_height="fill_parent"> <RelativeLayout android:layout_width="match_parent" android:id="@+id/relativeLayout1" android:layout_height="match_parent"> <TextView android:textSize="27dp" android:text="Word" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:id="@+id/wordText" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="54dp"></TextView> <TextView android:textSize="20dp" android:text="Meaning" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:id="@+id/meaningText" android:layout_below="@+id/wordText" android:layout_alignParentLeft="true" android:layout_marginTop="34dp"></TextView> <EditText android:id="@+id/meaningBox" android:layout_width="wrap_content" android:editable="false" android:layout_height="wrap_content" android:layout_below="@+id/meaningText" android:layout_alignParentLeft="true" android:layout_alignParentRight="true"> <requestFocus></requestFocus> </EditText> <TextView android:textSize="20dp" android:text="Usage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:id="@+id/usageText" android:layout_below="@+id/meaningBox" android:layout_alignParentLeft="true"> </TextView> <EditText android:id="@+id/usageBox" android:layout_width="wrap_content" android:editable="false" android:layout_height="wrap_content" android:layout_below="@+id/usageText" android:layout_alignParentLeft="true" android:layout_alignParentRight="true"></EditText> <CheckBox style="?android:attr/starStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/bookmark" android:layout_alignBottom="@+id/wordText" android:layout_toRightOf="@+id/wordText"> </CheckBox> </RelativeLayout> </ViewFlipper> </LinearLayout> I have only 1 layout in viewflipper. I change only values in same layout when user swipes finger on screen for next and previous. Then i have added animations for next and previous. I am doing it with following code vs.setInAnimation(this, R.anim.in_animation1); vs.setOutAnimation(this, R.anim.out_animation1); vs.showNext(); In this animations are not working as stated in animations xml file. When user swipes 1st view is not fading away , it just disappears and next view come. But same animations files are working when I add another layout in view flipper. Can anyone tell me what is problem ? or How should I work when there is only one layout in view flipper ? A: I'm confused about why you only have 1 view inside of the ViewFlipper. I believe that the point of the flipper is to transition between several views. Your java code looks correct, however when you call vs.showNext() there is nothing there for your ViewFlipper to transition to. No transitions means now animations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is a DispatcherTimer Tick event not occurring on time? I want to disable a button -to prevent double click: On a tablet PC you push once, it clicked twice and this is the easiest hack that I know- for a short period but I noticed/debugged the interval might be too long in practice; 50 ms vs > 2 seconds. There is in only one line starts the timer and one line stops it. Randomly the interval is 50 ms or much bigger. There is no CPU consume, I just click the button with mouse on my 4 core desktop PC. What would be the reason? DispatcherTimer timerTouchDelay = new DispatcherTimer(); protected override void OnMouseDown(MouseButtonEventArgs e) { //Init if (timerTouchDelay.Interval.Milliseconds == 0) { timerTouchDelay.Tick += new EventHandler(timerTouchDelay_Tick); timerTouchDelay.Interval = new TimeSpan(0, 0, 0, 0, 50); //ms } if(timerTouchDelay.IsEnabled) return; timerTouchDelay.Start(); HandleKeyDown(); base.OnMouseDown(e); } private void timerTouchDelay_Tick(object sender, EventArgs e) { timerTouchDelay.Stop(); } A: To understand why this is the case, I would highly recommend the following article: Comparing the Timer Classes in the .NET Framework Class Library For reference, DispatcherTimer is very similar to System.Windows.Forms.Timer, for which the author states "If you're looking for a metronome, you've come to the wrong place". This timer is not designed to 'tick' at exact intervals. A: Instead of running a timer, why not just record the time at which the button was last pressed. If it's more than 50 milliseconds ago, go ahead and perform the action, otherwise just exit. DateTime lastMouseDown = DateTime.MinValue; protected override void OnMouseDown(MouseButtonEventArgs e) { if(DateTime.Now.Subtract(lastMouseDown).TotalMilliseconds < 50) return; lastMouseDown = DateTime.Now; HandleKeyDown(); base.OnMouseDown(e); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is possible to create a text with click action (like a Action link ) in blackberry mainscreen? This is seems like a pretty simple question. Is it possible to set a custom action for a text link (those blue texts that are underlined) inside mainscreen in blackberry. In other words, is it possible to have a handler do something on an event like feildchangelistner on the text? thanks A: Yes, the various fields that display text are children of the class field As you can see from the doc you can override navigationClick, unclick. You may also set the font as one that is underlined and override the default color in paint. You will also need to code touch events if you are supporting the older touchscreen devices (Storms OS5 and below) I would advise against doing any of this because RIM provide a class that seems to fit your exact needs in the advanced UI pack. Take a look at HyperlinkButtonField
{ "language": "en", "url": "https://stackoverflow.com/questions/7567298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript group by array content I have some problems figuring out how to group to certain variables in javascript. Here is the deal. I have one array containing categories in my case right now categories A-Z but it could be anything (Animals - dogs - cats - etc). In another array I have a result from an xml file with different content (title, content and category). In my case the category containing letters from A-Z corresponding to the category in my other array. So what I want to do is first of all output one div for each category from the category array. When that is done I want to add inside each div the matching category items form my other array. This is an example First output from my category array: <div id="A"></div> <div id="B"></div> <div id="C"></div> <div id="D"></div> Second I want to add inside those divs the array objects that has a matching category inside them A, B, C etc. <div id="A"> <div id="contentFromMyOtherArray"> this object comes from my other array and had the content category A </div> <div id="contentFromMyOtherArray"> this object also comes from my other array and had the content category A still inside the A div </div> </div> <div id="B"> <div id="contentFromMyOtherArray"> this object comes from the array and had the content category B </div> </div> And so on... Is this even possible? EDIT: My First array only holds A, B, C, D, E etc so when iterating thru it array[i] i will get A B C D etc My second array holds title category etc so if i want to have only the category i could iterate thru it like this arrMarkers[i].category. That would output ex. A A A B B E E F F F etc based on what categories the content of each array holds A: Assuming you have your arrays defined something like this: var categories = ['A', 'B', 'C', 'D']; var other = []; other['A'] = ['item 1', 'item 2', 'item 3']; other['B'] = ['item 4', 'item 5']; other['C'] = ['item 6']; Then try the following jQuery code to create the divs: $(document).ready(function() { $.each(categories, function(index, category) { var categoryId = category.replace(/ /gi, '_'); var newCategory = $('<div />').attr('id', categoryId); // you can set any other properties on this new div here using .attr() $.each(other[category], function(index, item) { var itemId = category + '_' + item.replace(/ /gi, '_'); var newInnerDiv = $('<div />').attr('id', itemId); // set any other properties like text content, etc here newInnerDiv.appendTo(newCategory); }); newCategory.appendTo('body'); }); }); You can see a working example here: http://jsfiddle.net/greglockwood/8F8hv/ Let me know if you have any problems. A: If the array from the xml can be set to a two dimensional one, things can go fine. Please look at his example: html: <div id="containerDiv"> <div id="A"></div> <div id="B"></div> <div id="C"></div> </div> javascript/jQuery var resultArray = [ ["A", "Title1", "this object comes from my other array and had the content category A"], ["B", "Title2", "this object comes from my other array and had the content category B"], ["C", "Title3", "this object comes from my other array and had the content category C"], ["D", "Title4", "this object comes from my other array and had the content category D"], ["A", "Title5", "this object comes from my other array and had the content category A"], ["A", "Title6", "this object comes from my other array and had the content category A"], ["C", "Title7", "this object comes from my other array and had the content category C"], ["D", "Title8", "this object comes from my other array and had the content category D"], ["C", "Title9", "this object comes from my other array and had the content category C"], ["D", "Title10", "this object comes from my other array and had the content category D"], ["A", "Title11", "this object comes from my other array and had the content category A"], ["D", "Title12", "this object comes from my other array and had the content category D"], ["C", "Title13", "this object comes from my other array and had the content category C"], ["B", "Title14", "this object comes from my other array and had the content category B"] ]; $(document).ready( function() { var holderMap = new Array(); $("div#containerDiv").children("div").each( function() { holderMap[$(this).attr("id")]=$(this); } ); var elem = null; var value = null; $(resultArray).each(function() { elem = holderMap[$(this)[0]]; value = $(this)[2]; if(elem) { $(elem).html($(elem).html() + '<div id="contentFromMyOtherArray">' + value + '</div>'); } }); } ); This code goes dynamic so that if a non categorized item is encountered, it skips automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MouseWheel event doesn't fire in SWT-AWT component I am stuck at mousewheel event that just doesn't fire. I use swt_awt bridge, so I am able to use swing component in my RCP application. I tested everything I was able to find, but with no success. Because my application is awfully complex, I created a simplified version of my problem, which should also help you to orientate if you would like to help me. Now this simplified problem is, that I want my textarea (or scrollpane) to catch mousewheel events. But these events are lost. import java.awt.Frame; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import javax.swing.JScrollPane; import javax.swing.JTextArea; import org.eclipse.swt.SWT; import org.eclipse.swt.awt.SWT_AWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Shell; public class Main { protected Shell shell; /** * Launch the application. * @param args */ public static void main(String[] args) { try { Main window = new Main(); window.open(); } catch (Exception e) { e.printStackTrace(); } } /** * Open the window. */ public void open() { Display display = Display.getDefault(); createContents(); shell.open(); shell.layout(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } /** * Create contents of the window. */ protected void createContents() { shell = new Shell(); shell.setSize(450, 300); shell.setText("SWT Application"); shell.setLayout(new GridLayout(3, false)); List list = new List(shell, SWT.BORDER); list.setLayoutData(new GridData(GridData.FILL_VERTICAL)); list.add("Something"); Composite composite = new Composite(shell, SWT.EMBEDDED); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); Frame graphFrame = SWT_AWT.new_Frame(composite); final JTextArea textarea = new JTextArea(60, 80); JScrollPane scrollpane = new JScrollPane(textarea); graphFrame.add(scrollpane); textarea.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { textarea.setText(textarea.getText() + "Mouse clicked.\n\r"); } @Override public void mouseEntered(MouseEvent arg0) { textarea.setText(textarea.getText() + "Mouse is in.\n\r"); } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); textarea.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent arg0) { textarea.setText(textarea.getText() + "Mouse wheel activated.\n\r"); } }); } } EDIT: I found out, that Panel is able to catch awt events, however any class, that extends JComponent (just like my component do) somehow loose these events. I also managed to create an ugly hack, where I forceFocus on my swt composite after I click on my JComponent. Then I can at least listen to swt events and work with my JComponent directly from swt event listener. I would still aprreciate the solution where I will be able to catch awt mouse events directly on JComponent. A: You may be running into this issue: http://code.google.com/p/gama-platform/issues/detail?id=84. A workaround is described in http://code.google.com/p/gama-platform/issues/detail?id=84#c13 (linked to this very question).
{ "language": "en", "url": "https://stackoverflow.com/questions/7567305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to make following layout with the help float,position ...if possible without setting any ht/wd of A and B divs! A and B contain transparent images which overlap the bg main div. |-------------------| | -- Main ------- | |--- ---------- ---- | |-|A| ---------|B|- | |-------------------| Thanks for response I am improving my que :: [sorry for confussion] This is the following layout which I'm trying .. <div id="main" style="width:200px;height:200px;overflow:hidden;"> <div id="a" style="position:absolute;z-index:2;float:left;"> left side img </div> <div id="in" style="float:left;"> main image </div> <div id="b" style="position:absolute;z-index:2;float:left;"> rt side image </div> </div> where "a" and "b" contain the transparent iamges which need to overlap the "in" div image. Is it possible? A: Lets say you have following layout structure <div class="main"> <div class="a"></div> <div class="b"></div> </div> If I understood your question, you want to make a and b transparent without exact width and height. Right? No it's impossible without exact width at least. So, you need to write following css rules. Here are the some variants % values (Width:20%. height100%) .main {width:100%; height:100%} .a {width:20%; height:100%; background-image:transparent.png; float:left;} .b {width:20%; height:100%; background-image:transparent.png; float:right;} OR % values (Width:20%. height20%) and with exact positioning (you can place whatever you want instead 50px it's distance from top and left/right for a/b divs) .main {width:100%; height:100%} .a {width:20%; height:20%; background-image:transparent.png; float:left; position:absolute; top:50px; left:50px;} .b {width:200px; height:200px; background-image:transparent.png; float:right; position:absolute; top:50px; right:50px;} OR pixel values .main {width:100%; height:100%} .a {width:200px; height:200px; background-image:transparent.png; float:left; position:absolute; top:50px; left:50px;} .b {width:20%; height:20%; background-image:transparent.png; float:right; position:absolute; top:50px; right:50px;}
{ "language": "en", "url": "https://stackoverflow.com/questions/7567306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: TOGAF 9: Example Implementation of Deliverables, Artifacts, and Building Blocks I am reading v9 of TOGAF and couldn't understand the illustration of Deliverables, Artifacts, and Building Blocks. Could anyone give a real example to help me understand these? A: Artifacts: Any chart or diagram, that shows an aspect of an architecture. For example a use case diagram, ERD etc. Deliverable: work product that is contractually specified and in turn formally reviewed, agreed, and signed off by the stakeholders. For example a "A statement of architecture work" is an output of Architecture Vision that needs to be reviewed and signed off by stake holders. So a "Statement of architecture work" is a deliverable. Building Blocks: A reusable component of business, IT, or architectural capability that can be combined with other building blocks to deliver architectures and solutions. A building block has a type that corresponds to the TOGAF content metamodel (such as actor, business service, application, or data entity). For example an "OpenId Authentication" will be used as a SBB to secure the system and is a solution for the ABB "Secure access to portal.". A: Artifacts can be charts, diagrams. Deliverables may contain artifacts. Deliverables are work products that typically require approval/signatures. Building Blocks are components of an architecture. Check http://wiki.glitchdata.com and search for TOGAF for more study notes. A: Relationship between Artifacts, Building Blocks and Deliverable Artifacts are documents contains catalogs and diagrams of building blocks and artifacts support building blocks. Solutions are the deliverable's generated from artifacts. A: Artifacts can be charts, diagrams. Deliverables may contain artifacts. Deliverables are work products that typically require approval/signatures. Building Blocks are components of an architecture. Try this: http://www.togaf.info/togaf9/togafSlides9/TOGAF-V9-Sample-Catalogs-Matrics-Diagrams-v2.pdf A: Something that may help you understand a little better is a sample set of TOGAF 9 deliverables. The Open Group provides a set of templates, including examples of all catalogs, matrices, and diagrams, and template deliverables. They can be downloaded here. If the link is ever broken, search their site for I093.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make a list of n numbers in Python and randomly select any number? I have taken a count of something and it came out to N. Now I would like to have a list, containing 1 to N numbers in it. Example: N = 5 then, count_list = [1, 2, 3, 4, 5] Also, once I have created the list, I would like to randomly select a number from that list and use that number. After that I would like to select another number from the remaining numbers of the list (N-1) and then use that also. This goes on it the list is empty. A: You can try this code import random N = 5 count_list = range(1,N+1) random.shuffle(count_list) while count_list: value = count_list.pop() # do whatever you want with 'value' A: You can create the enumeration of the elements by something like this: mylist = list(xrange(10)) Then you can use the random.choice function to select your items: import random ... random.choice(mylist) As Asim Ihsan correctly stated, my answer did not address the full problem of the OP. To remove the values from the list, simply list.remove() can be called: import random ... value = random.choice(mylist) mylist.remove(value) As takataka pointed out, the xrange builtin function was renamed to range in Python 3. A: As for the first part: >>> N = 5 >>> count_list = [i+1 for i in xrange(N)] >>> count_list [1, 2, 3, 4, 5] >>> As for the second, read 9.6. random — Generate pseudo-random numbers. >>> from random import choice >>> a = choice(count_list) >>> a 1 >>> count_list.remove(a) >>> count_list [2, 3, 4, 5] That's the general idea. By the way, you may also be interested in reading Random selection of elements in a list, with no repeats (Python recipe). There are a few implementations of fast random selection. A: You don't need to count stuff if you want to pick a random element. Just use random.choice() and pass your iterable: import random items = ['foo', 'bar', 'baz'] print random.choice(items) If you really have to count them, use random.randint(1, count+1). A: You can use: import random random.choice(range(n)) or: random.choice(range(1,n+1)) if you want it from 1 to n and not from 0. A: After that I would like to select another number from the remaining numbers of the list (N-1) and then use that also. Then you arguably do not really want to create a list of numbers from 1 to N just for the purpose of picking one (why not just ask for a random number in that range directly, instead of explicitly creating it to choose from?), but instead to shuffle such a list. Fortunately, the random module has you covered for this, too: just use random.shuffle. Of course, if you have a huge list of numbers and you only want to draw a few, then it certainly makes sense to draw each using random.choice and remove it. But... why do you want to select numbers from a range, that corresponds to the count of some items? Are you going to use the number to select one of the items? Don't do that; that's going out of your way to make things too complicated. If you want to select one of the items, then do so directly - again with random.choice. A: Maintain a set and remove a randomly picked-up element (with choice) until the list is empty: s = set(range(1, 6)) import random while len(s) > 0: s.remove(random.choice(list(s))) print(s) Three runs give three different answers: >>> set([1, 3, 4, 5]) set([3, 4, 5]) set([3, 4]) set([4]) set([]) >>> set([1, 2, 3, 5]) set([2, 3, 5]) set([2, 3]) set([2]) set([]) >>> set([1, 2, 3, 5]) set([1, 2, 3]) set([1, 2]) set([1]) set([]) A: Create the list (edited): count_list = range(1, N+1) Select random element: import random random.choice(count_list)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Using ActiveRecord's scope instruction to return a single result I have the following class that works fine in my unit tests but I feel it could be simpler. class License < ActiveRecord::Base scope :active, lambda { where("active_from <= ?", Date.today).order("version_number DESC") } end def current_license return License.active.first end public :current_license I have tried appending the .first into the lambda clause but that causes an error. How do I tell the scope I only want the first result, and thus eliminate the method current_license completely? A: Make it a method, and you can get this: class License < ActiveRecord::Base def self.current_license return License.where("active_from <= ?", Date.today).order("version_number DESC").first end end As for the number of results, try to add a .limit(1). For more info, have a look here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: image attach option is not coming after taking image from camera frnds,on clicking on button i open camera for taking picture ,i take picture successfull and now only two option is coming after clicking pic,"save" and "Discard",there is not any option for attaching the camera clicked image so how to attach image and display image in next view? my code is ... public void function2(int id){ Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAMERA_PIC_REQUEST||requestCode == SELECT_PICTURE) { try{ try{ selectedImageUri = data.getData(); //OI FILE Manager String filemanagerstring = selectedImageUri.getPath(); //MEDIA GALLERY selectedImagePath = getPath(selectedImageUri); //DEBUG PURPOSE - you can delete this if you want if(selectedImagePath!=null){ Intent i=new Intent(MainMenu.this,Imageprview.class); startActivity(i); System.out.println(selectedImagePath); } else System.out.println("selectedImagePath is null"); if(filemanagerstring!=null) System.out.println(filemanagerstring); else System.out.println("filemanagerstring is null"); //NOW WE HAVE OUR WANTED STRING if(selectedImagePath!=null) System.out.println("selectedImagePath is the right one for you!"); else System.out.println("filemanagerstring is the right one for you!"); }catch (NullPointerException e) { // TODO: handle exception } }catch (ArrayIndexOutOfBoundsException e) { // TODO: handle exception } } } //UPDATED! public String getPath(Uri uri) { String[] projection = {MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); if(cursor!=null) { //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } else return null; } A: Button btnCam=(Button)findViewById(R.id.camBtn); btnCam.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intent detailActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class); //startActivity(detailActivity); saveImage(); } }); } public void saveImage() { try { FileOutputStream fos = openFileOutput("MyFile.jpeg", Context.MODE_WORLD_WRITEABLE); fos.close(); File f = new File(getFilesDir() + File.separator + "MyFile.jpeg"); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90); startActivityForResult(intent,IMAGE_CAPTURE); //startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),IMAGE_CAPTURE); } catch(IOException e) { } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0) { if (resultCode == RESULT_OK){ finish(); //imageView=(ImageView)findViewById(R.id.imageView1); //imageView.setImageURI(imageUri); Intent detActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class); startActivity(detActivity); //Log.d("ANDRO_CAMERA","Picture taken!!!"); // } } } IN DETAIL PROFILE ACTIVITY public class detailProfile extends Activity{ String fname=new File(getFilesDir(),"MyFile.jpeg").getAbsolutePath(); //USING THIS FILE PATH YOU CAN LOAD THE IMAGE IN THIS ACTIVITY } YOU HAVE ANOTHER OPTION YOU CAN PASS THE IMAGE TO THROUGH THE INTENT AT THE TIME OF CREATING THE NEW INTENT AND AFTER THAT YOU CAN ACCESS THAT IMAGE THROUGH THE BUNDLE OBJECT IN THE NEW INTENT. bytes[] imgs = ... // your image Intent intent = new Intent(this, YourActivity.class); intent.putExtra("img", imgs); startActivity(intent) in detailprofile bytes[] receiver = getIntent().getExtra("imgs"); //using Byte array you can display your image in ur imageview A: There is no such option available.you can save file in to sdcard or any external storage c the code i have done for saving image in external storage. public void onClick(View v) { if(v == imgForPhotograph) { path = Environment.getExternalStorageDirectory() + "/photo1.jpg"; File file = new File(path); Uri outputFileUri = Uri.fromFile(file); Intent intent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY); } } public void onActivityResult(int requestCode, int resultCode, Intent data) { System.gc(); if (requestCode == CAPTURE_IMAGE_ACTIVITY) { if (resultCode == Activity.RESULT_OK) { try { // Call function MakeFolder to create folder structure if // its not created if(imageBitmap != null) { imageBitmap = null; imageBitmap.recycle(); } BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 3; imageBitmap = BitmapFactory.decodeFile(path, options); ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // bm byte[] bmpbyte = baos.toByteArray(); // Imagebase64= Base64.encodeToString(bmpbyte, Base64.DEFAULT); // set imgForPhotograph.setImageBitmap(imageBitmap); isImageTaken = true; // Name for image IMAGEPATH = getString(R.string.Image) + System.currentTimeMillis(); SaveImageFile(imageBitmap,IMAGEPATH); } catch (Exception e) { Toast.makeText(this, "Picture Not taken", Toast.LENGTH_LONG).show(); e.printStackTrace(); } } } } All The Best.... A: Hi guys, this code is working. For camera and stored into sd card: public class CampicsaveActivity extends Activity { /** Called when the activity is first created. */ FrameLayout frm; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); frm=(FrameLayout)findViewById(R.id.preview); Button btnCam=(Button)findViewById(R.id.buttonClick); btnCam.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Intent detailActivity = new Intent(getBaseContext(),com.rodasys.profile.detailProfile.class); // startActivity(detailActivity); saveImage(0); } }); } public void saveImage(int IMAGE_CAPTURE) { try { FileOutputStream fos = openFileOutput("MyFile.jpeg", Context.MODE_WORLD_WRITEABLE); fos.close(); File f = new File(getFilesDir() + File.separator + "MyFile.jpeg"); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)); intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90); startActivityForResult(intent,IMAGE_CAPTURE); //startActivityForResult(new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f)),IMAGE_CAPTURE); } catch(IOException e) {;} } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0) { if (resultCode == RESULT_OK) { finish(); //imageView=(ImageView)findViewById(R.id.imageView1); //imageView.setImageURI(imageUri); Intent detActivity = new Intent(getBaseContext(),CampicsaveActivity.class); startActivity(detActivity); //Log.d("ANDRO_CAMERA","Picture taken!!!"); // } } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Resubmitting the binary data into AppStore issue I am stuck at this point. Scenario is like that - I have already uploaded my application in apple Appstore and reflecting status is "Ready for sale",This is great. but there is one issue,now i want to update the binary file. How should i go around it? can anyone help me out ? Thanking you in advance ... A: You have to release the currently approved app for sale before you can update it. You can release it for sale for one hour in only one microscopic country for one hour, or maybe zero countries, then remove it from sale if you don't want it distributed widely before you update it. A: Hey this is very Easy Should i help u now?? Once your app is Ready for Sale, after that if you want to upgrade your Binary, then you have to release your Apps New Version.If previously your version was 1.0 then it should be Now 1.1 or 2.0 then Modify the Code you had written for that app and Compress the binary and click on New Version for the Corresponding app. That's it. If you still face any problem then let me know... I will be happy to Help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Horizontal Scrolling when Scrollview inside Scrollview I have two horizontal paging scroll views where a one is smaller and a subview of the the other. Is there a setup that consistently allows a horizontal drag to move the outer scroll view when there is no more paging to do in the inner scroll view? A: Apparently you have to turn off the rubberbanding in the inner scroll view for this to work properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linux Multiple virtual interfaces access through snmp We had configured net-snmp in a linux machine and configured around 100 virtual interfaces (eth0:x). And i could not access virtual interfaces through MIB browser. Can you guide me to discover all virtual interfaces as the part of Linux machine discovery? Thanks in advance ! ~Prabhakar A: Use OID .1.3.6.1.2.1.2.2.1.2. It will output all interfaces (both physical and logical) with their SNMP indexes. For example: snmpwalk -v 2c -c private 127.0.0.1 .1.3.6.1.2.1.2.2.1.2 IF-MIB::ifDescr.1 = STRING: lo IF-MIB::ifDescr.2 = STRING: eth0
{ "language": "en", "url": "https://stackoverflow.com/questions/7567336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to restrict EditText to two lines in android Hi i need to restrict the EditText to two lines and i am using the following code <EditText android:layout_toRightOf="@+id/valettext" android:layout_centerVertical="true" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginRight="70dp" android:maxLines="2" android:ellipsize="end" android:id="@+id/note"/> but its not working ,its going to the next line on pressing the Next button. How to do this. Thanks in advance. A: You need to add this: android:singleLine="false" Also, set the number of lines prior to display: android:lines="2" A: override your edittext's addaddTextChangedListener() and inside afterTextChanged() method try this code. @Override public void afterTextChanged(Editable editable) { if (null != edittext.getLayout() && edittext.getLayout().getLineCount() > 2) { edittext.getText().delete(edittext.getText().length() - 1, edittext.getText().length()); } } A: <EditText android:id="@+id/edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" android:maxLines="1" /> You just need to make sure you have the attribute "inputType" set. It doesn't work without this line. android:inputType="text"
{ "language": "en", "url": "https://stackoverflow.com/questions/7567338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Finding duplicates in List In a list with some hundred thousand entries, how does one go about comparing each entry with the rest of the list for duplicates? For example, List fileNames contains both "00012345.pdf" and "12345.pdf" and are considered duplicte. What is the best strategy to flagging this kind of a duplicate? Thanks Update: The naming of files is restricted to numbers. They are padded with zeros. Duplicates are where the padding is missing. Thus, "123.pdf" & "000123.pdf" are duplicates. A: You probably want to implement your own substring comparer to test equality based on whether a substring is contained within another string. This isn't necessarily optimised, but it will work. You could also possibly consider using Parallel Linq if you are using .NET 4.0. EDIT: Answer updated to reflect refined question after it was edited void Main() { List<string> stringList = new List<string> { "00012345.pdf","12345.pdf","notaduplicate.jpg","3453456363234.jpg"}; IEqualityComparer<string> comparer = new NumericFilenameEqualityComparer (); var duplicates = stringList.GroupBy (s => s, comparer).Where(grp => grp.Count() > 1); // do something with grouped duplicates... } // Not safe for null's ! // NB do you own parameter / null checks / string-case options etc ! public class NumericFilenameEqualityComparer : IEqualityComparer<string> { private static Regex digitFilenameRegex = new Regex(@"\d+", RegexOptions.Compiled); public bool Equals(string left, string right) { Match leftDigitsMatch = digitFilenameRegex.Match(left); Match rightDigitsMatch = digitFilenameRegex.Match(right); long leftValue = leftDigitsMatch.Success ? long.Parse(leftDigitsMatch.Value) : long.MaxValue; long rightValue = rightDigitsMatch.Success ? long.Parse(rightDigitsMatch.Value) : long.MaxValue; return leftValue == rightValue; } public int GetHashCode(string value) { return base.GetHashCode(); } } A: I understand you are looking for duplicates in order to remove them? One way to go about it could be the following: Create a class MyString which takes care of duplication rules. That is, overrides Equals and GetHashCode to recreate exactly the duplication rules you are considering. (I'm understanding from your question that 00012345.pdf and 12345.pdf should be considered duplicates?) Make this class explicitly or implictly convertible to string (or override ToString() for that matter). Create a HashCode<MyString> and fill it up iterating through your original List<String> checking for duplicates. Might be dirty but it will do the trick. The only "hard" part here is correctly implementing your duplication rules. A: I have a simple solution for everyone to find a duplicate string word and cahracter For word public class Test { public static void main(String[] args) { findDuplicateWords("i am am a a learner learner learner"); } private static void findDuplicateWords(String string) { HashMap<String,Integer> hm=new HashMap<>(); String[] s=string.split(" "); for(String tempString:s){ if(hm.get(tempString)!=null){ hm.put(tempString, hm.get(tempString)+1); } else{ hm.put(tempString,1); } } System.out.println(hm); } } for character use for loop, get array length and use charAt() A: Maybe somthing like this: List<string> theList = new List<string>() { "00012345.pdf", "00012345.pdf", "12345.pdf", "1234567.pdf", "12.pdf" }; theList.GroupBy(txt => txt) .Where(grouping => grouping.Count() > 1) .ToList() .ForEach(groupItem => Console.WriteLine("{0} duplicated {1} times with these values {2}", groupItem.Key, groupItem.Count(), string.Join(" ", groupItem.ToArray())));
{ "language": "en", "url": "https://stackoverflow.com/questions/7567340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Firefox automatically closing form straight away EDIT : Fixed, I just removed the tables and made it tableless, it will require abit of css to sort the layout but is working cross browser, thank you everyone. I have a really weird issue, I'm trying to do a AJAX quick order form in oscommerce. All is going well apart from this code: while ($sql_results = tep_db_fetch_array($sql_query)) { $sout2 = "<tr>"; $sout2 .= '<form id="pp'. $sql_results['products_id'] . '" method="get" action="quickorder.php"></tr><tr>'; $sout2 .= "<td valign=\"top\" width=\"100\"><b><a href=\"" . tep_href_link(FILENAME_PRODUCT_INFO, 'products_id=' . $sql_results['products_id']) . "\">" . $sql_results['products_model'] . "</a></b></td>"; $sout2 .= "<td valign=\"top\" width=\"300\">" . $sql_results['products_name'] . "</td>"; //$sout .= "<td valign=\"top\" width=\"100\">" . tep_image(DIR_WS_IMAGES . $sql_results['products_image'], $sql_results['products_name'], 50, 50) . "</td>"; $sout2 .= "<td valign=\"top\" width=\"150\"><input type=\"hidden\" id=\"pid\" name=\"pid\" value=\"" . $sql_results['products_id'] . "\" /><input id=\"pqty\" name=\"pqty\" type=\"text\" value=\"1\" /></td>"; $sout2 .= "<td valign=\"top\" width=\"50\"><input type=\"submit\" value=\"Add\" /></td>"; $sout2 .= "</form>"; $sout2 .= "</tr>"; echo $sout2; } This makes firefox close the form tags straight away: <form id="pp266" method="get" action="quickorder.php"></form> IE does the forms correctly. A: Examine your markup thoroughly. You have something like <tr><form ...></tr> This closes the tr right away, causing all nested elements to close as well (FF behaviour, IE behaves differently). So, replace $sout2 .= '<form id="pp'. $sql_results['products_id'] . '" method="get" action="quickorder.php"></tr><tr>'; with $sout2 .= '<form id="pp'. $sql_results['products_id'] . '" method="get" action="quickorder.php"><tr>'; Also, it might be a good idea to move the form outside the row, as some browsers do not allow form tag to appear inside the tr, only td and th.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Disadvantages of Lazy? I recently started using Lazy throughout my application, and I was wondering if there are any obvious negative aspects that I need to take into account when using Lazy<T>? I am trying to utilize Lazy<T> as often as I deem it appropriate, primarily to help reduce the memory footprint of our loaded, but inactive plugins. A: Here's not quite a negative aspect, but a gotcha for lazy people :). Lazy initializers are like static initializers. They get run once. If an exception is thrown, the exception is cached and subsequent calls to .Value would throw the same exception. This is by design and is mentioned in the docs ... http://msdn.microsoft.com/en-us/library/dd642329.aspx: Exceptions that are thrown by valueFactory are cached. Hence, code as below will never return a value: bool firstTime = true; Lazy<int> lazyInt = new Lazy<int>(() => { if (firstTime) { firstTime = false; throw new Exception("Always throws exception the very first time."); } return 21; }); int? val = null; while (val == null) { try { val = lazyInt.Value; } catch { } } A: I've come to use Lazy<T> mainly because of it's concurrency capabilities while loading resources from database. Thus I got rid of lock objects and arguable locking patterns. In my case ConcurrentDictionary + Lazy as a value made my day, thanks to @Reed Copsey and his blog post This looks like the following. Instead of calling: MyValue value = dictionary.GetOrAdd( key, () => new MyValue(key)); We would instead use a ConcurrentDictionary>, and write: MyValue value = dictionary.GetOrAdd( key, () => new Lazy<MyValue>( () => new MyValue(key))) .Value; No downsides of Lazy<T> noticed so far. A: As with anything, Lazy<T> can be used for good or for evil, hence a disadvantage: when used inappropriately, it can cause confusion and frustration. However, lazy initialization pattern has been around for years, and now that .NET BCL has an implementation developers don't need to reinvent the wheel yet again. What's more, MEF loves Lazy. A: What exactly do you mean with "throughout my application"? I think it should only be used when you're not sure if the value will be used or not, which may only be the case with optional parameters that take a long time to compute. This could include complex calculations, file-handling, Webservices, database access and so on. On the other hand, why use Lazy here? In most cases you can simply call a method instead of lazy.Value and it makes no difference anyway. BUT it's more simple and obvious to the programmer what's happening in this situation without Lazy. One obvious upside may be already implemented caching of the value, but I don't think this is such a big advantage. A: Lazy is used to preserve resources while not really needed. This pattern is pretty good but implementation can be useless. Bigger the resource is, usefull is this pattern. A disavantage to use Lazy class is the non transparency of usage. Indeed, you have to maintain everywhere an additional indirection (.Value). When you just need an instance of real type, it is forced to load even if you dont need to use it directly. Lazy is for lazy developpement gaining productivity but this gain can be lost by high usage. If you have a real transparent implementation (using proxy pattern for exemple) it get rid of disavantage and it can be very usefull in many case. Concurrency must be consider in an other aspect and not implemented by default in your type. It must be included only in client code or type helpers for this concept. A: I'll expand a bit on my comment, which reads: I've just started using Lazy, and find that it's often indicative of bad design; or laziness on the part of the programmer. Also, one disadvantage is that you have to be more vigilant with scoped up variables, and create proper closures. For example, I've used Lazy<T> to create the pages the user can see in my (sessionless) MVC app. It's a guiding wizard, so the user might want to go to a random previous step. When the handshake is made, an array of Lazy<Page> objects is crated, and if the user specifies as step, that exact page is evaluated. I find it delivers good performance, but there are some aspects to it that I don't like, for example many of my foreach constructs now look like this: foreach(var something in somethings){ var somethingClosure = something; list.Add(new Lazy<Page>(() => new Page(somethingClosure)); } I.e. you have to deal with the problem of closures very proactively. Otherwise I don't think it's such a bad performance hit to store a lambda and evaluate it when needed. On the other hand this might be indicative that the programmer is being a Lazy<Programmer>, in the sense that you'd prefer not thinking through your program now, and instead let the proper logic evaluate when needed, as with example in my case - instead of building that array, I could just figure out just what that specific requested page would be; but I chose to be lazy, and do an all in approach. EDIT It occurs to me that Lazy<T> also has a few peculiars when working with concurrency. For example there's a ThreadLocal<T> for some scenarios, and several flag configurations for your particular multi-threaded scenario. You can read more on msdn. A: In my opinion, you should always have a reason for choosing Lazy. There are several alternatives depending on the use case and there are definitely cases where this structure is appropriate. But don't use it just because it's cool. For example I don't get the point in the page selection example in one of the other answers. Using a list of Lazy for selecting a single element can be well done with a list or dictionary of delegates directly without using Lazy or with a simple switch statement. So the most obvious alternatives are * *direct instantiation for cheap data structures or structures that are anyway needed *delegates for things that are needed zero to few times in some algorithm *some caching structure for items that should free the memory when not being used for some time *some kind of "future" structure like Task that already may start initializing asynchronously before actual usage consuming idle CPU time in cases where the probability is quite high that the structure will be required later on In contrast to that, Lazy is often suitable when * *computationally intense data structures *are needed zero to many times in some algorithm where the zero case has a significant probability *and the data is local to some method or class and can be garbage collected when not in use any more or the data should be kept in memory for the whole program's runtime
{ "language": "en", "url": "https://stackoverflow.com/questions/7567342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: Posting larger image on facebook How to post large image on facebook wall through iphone programmatically.I am using FBConnect API how can i acheive this. Thanks A: Facebook docs said: It is strongly recommended that you scale the image in your application before adding it to the request. The largest dimension should be at most 720 pixels (the largest display size Facebook supports). A: -(void)postMessageWithPictureOnFB{ NSString *urlString = [[NSString alloc] initWithFormat:@"https://graph.facebook.com/me/photos"]; NSURL *url = [[NSURL alloc] initWithString:urlString]; NSData *picture_data = UIImagePNGRepresentation([UIImage imageNamed:@"apple.png"]); NSMutableData *body = [[NSMutableData alloc] initWithCapacity:1]; NSString *boundary = [[NSString alloc] initWithString:@"----1010101010"]; NSString *contentType = [[NSString alloc] initWithFormat:@"multipart/form-data; boundary=%@",boundary]; [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"message\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[textView.text dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"media\";\r\nfilename=\"media.png\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:picture_data]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[@"Content-Disposition: form-data; name=\"access_token\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[facebook.accessToken dataUsingEncoding:NSUTF8StringEncoding]]; [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; serverRequest = [ASIHTTPRequest requestWithURL:url]; [serverRequest addRequestHeader:@"Content-Type" value:contentType]; [serverRequest appendPostData:body]; [serverRequest addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%d", body.length]]; //[serverRequest setDelegate:self]; //[serverRequest setDidFinishSelector:@selector(postMessageWithPictureOnFBRequestDone:)]; //[serverRequest setDidFailSelector:@selector(postMessageWithPictureOnFBRequestWentWrong:)]; [serverRequest startAsynchronous]; [urlString release]; [url release]; [body release]; [boundary release]; [contentType release]; } A: Try this with Graph API - (IBAction)uploadPhoto:(id)sender { NSString *path = @"http://www.facebook.com/images/devsite /iphone_connect_btn.jpg"; NSURL *url = [NSURL URLWithString:path]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [[UIImage alloc] initWithData:data]; NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: img, @"picture", nil]; [_facebook requestWithGraphPath:@"me/photos" andParams:params andHttpMethod:@"POST" andDelegate:self]; [img release]; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: creating facebook fan pages I'm trying to understand open graph objects behind facebook pages. Actually I get there are basically these types of pages: * *facebook fan pages (i.e. https://www.facebook.com/HuffingtonPost https://graph.facebook.com/HuffingtonPost ) *websites fan pages og:type != "article"(i.e. http://wp.damore.it/?p=16 https://graph.facebook.com/?ids=http://wp.damore.it/?p=16 ) *websites fan pages og:type == "article" (i.e. http://www.repubblica.it/politica/2011/09/26/news/brunetta_certificati-22244909/ https://graph.facebook.com/?ids=http://www.repubblica.it/politica/2011/09/26/news/brunetta_certificati-22244909/ ) As far as I know, I can update my fans only in case 1 and 2. In case 2 a fan page is created into facebook, but is reachable only to admin users. The questions are: * *This explanation is correct or am I missing something? *Are these all existing fan pages types? *Where I can find a comprehensive documentation that explain how to updates facebook pages fans? Thanks to everybody want make clear such questions :) A: Yes, all your assumptions are correct. In the case of 3, we don't allow you to update fans, since an article is a transient thing, not something you'd push further info into News Feed about. Updating fans is covered in the Publishing section of this page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FindBugs RV_ABSOLUTE_VALUE_OF_RANDOM_INT warning I'm trying to do a code review for our project using FindBugs. we have a method to generate unique id (randomly) : public static String generateUUID(int base){ return String.valueOf(getCurrentTimeInNanos((long)base)) + String.valueOf(Math.abs(random.nextInt())); } and findBugs indicates RV_ABSOLUTE_VALUE_OF_RANDOM_INT warning (RV: Bad attempt to compute absolute value of signed 32-bit random integer ) , i guess the problem is in String.valueOf(Math.abs(random.nextInt()). Does anyone have an explanation for why is this and how to fix it ? A: Maybe it is because Math.abs can actually return negative results for integer inputs: assertTrue( Math.abs(Integer.MIN_VALUE) < 0 ); It only does this for MIN_VALUE, though, because -MIN_VALUE cannot be represented. Kind of an overflow problem. As for how to fix it: * *don't make your own UUID. Use java.util.UUID. *cast the random number to long before calling Math.abs *use random.nextInt(Integer.MAX_VALUE) to get a number from 0 to MAX_VALUE - 1
{ "language": "en", "url": "https://stackoverflow.com/questions/7567350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Tabbing mysteriously disabled in Flash application I'm compiling a SWF using FlexSDK 4.1. I am not disabling any tab functionality. Swf is being embedded with the following via swf object: swfobject.embedSWF("Main.swf", "flashcontent", "984", "550", "10.0.0", params,flashvars, attributes, "expressInstall.swf"); Expected outcome when tabbing is to see "yellow boxes" on all items with click events. I don't see anything all browsers. WMODE is 'window' Any help would be appreciated. Thanks A: If you are on MS Windows, you can obtain the Windows 7 SDK and pull Inspect32 to see what the OS is providing you when you can't see the focus. It could be off screen or a non-visual focus. A: Is this a FLASH object embedded in a web page? If so - the problem is that various browsers differ on whether they let you tab into a FLASH object (or any plugin, not just FLASH) in the first place. * *Try it with IE - IE lets you tab in, through, and back out of FLASH objects. *Chrome and Firefox - these tab right over the object. The only way you can tab through FLASH objects in these is to click the object to force focus there - which somewhat defeats the purpose of using the keyboard in the first place... (It might be possible to use element.focus() to get focus there - but then the typical problem is that focus is stuck within the FLASH object and never returns back to the page...) As a reference, try playing with a youtube page. They've done the work to make their FLASH plugin accessible, but it only works in some browsers, as outlined above. Note that if/when you do get focus to the object, the focus highlight is drawn by flash itself; so you won't see the browser's focus style (eg. dotted line for IE, yellow rectangle for chrome), but you should see something. On top of all of this, if you're extending from one of the very base classes (rather than deriving from an existing higher-level control such as a button), you might need to set some properties on your class to make the item keyboard-tabable, and also visible to accessibility clients (such as screen readers). You might need to also provide your own visuals to indicate when the element has focus yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed this is the error code: 09-27 11:56:01.425: WARN/System.err(10324): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed 09-27 11:56:01.435: WARN/System.err(10324): at android.database.sqlite.SQLiteStatement.native_execute(Native Method) 09-27 11:56:01.435: WARN/System.err(10324): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61) 09-27 11:56:01.435: WARN/System.err(10324): at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1809) 09-27 11:56:01.435: WARN/System.err(10324): at de.enough.appmate.dbase.CMSResource.updateItem(CMSResource.java:1103) 09-27 11:56:01.435: WARN/System.err(10324): at de.enough.appmate.dbase.CMSResourceUpdater.updateItems(CMSResourceUpdater.java:178) 09-27 11:56:01.435: WARN/System.err(10324): at de.enough.appmate.dbase.CMSResourceUpdater.loadUpdates(CMSResourceUpdater.java:102) 09-27 11:56:01.435: WARN/System.err(10324): at de.enough.appmate.dbase.CMSResourceUpdaterRunnable.run(CMSResourceUpdaterRunnable.java:32) 09-27 11:56:01.435: WARN/System.err(10324): at java.lang.Thread.run(Thread.java:1019) and this is the method that is used this.db.execSQL("INSERT INTO itemGalleryItems (id, imageCaption, imageUrl,itemID,orderIndex,displayInGallery) VALUES (?,?,?,?,?,?); ", bindArgs); the binArgs looks like: String[] bindArgs = { (String) imageItem.get("id"), (String) imageItem.get("imageCaption"), (String) imageItem.get("imageName"), (String) item.get("id"), (String) imageItem.get("orderIndex"), (String) imageItem.get("displayInGallery")}; hope someone can help thanx newone A: I have fixed this error; instead of long sucess = db.insert(TABLE_NAME_CONTACT_EXTRA, null, row); use this to insert data in database long sucess = db.insertWithOnConflict(TABLE_NAME_CONTACT_EXTRA, null, row, SQLiteDatabase.CONFLICT_IGNORE); A: I think if you have autoincrement field, you shouldn't include it in the query... is the "id" autoincrement? A: Have a look at your insert statement. Does it have all the columns that are declared to be not null in table create statement? And try no to use "id" column, use "_id" instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python: return output of ksh function On Unix, how can Iretrieve the output of a ksh function as a Python variable? The function is called sset and is defined in my ".kshrc". I tried using the subparser module according to comment recommendations. Here's what I came up with: import shlex import subprocess command_line = "/bin/ksh -c \". /Home/user/.khsrc && sset \"" s = shlex.shlex(command_line) subprocess.call(list(s)) And I get a Permission denied error. Here's the traceback: Traceback (most recent call last): File "./pymss_os.py", line 9, in <module> subprocess.call(list(s)) File "/Soft/summit/tools/Python-2.7.2/Lib/subprocess.py", line 493, in call return Popen(*popenargs, **kwargs).wait() File "/Soft/summit/tools/Python-2.7.2/Lib/subprocess.py", line 679, in __init__ errread, errwrite) File "/Soft/summit/tools/Python-2.7.2/Lib/subprocess.py", line 1228, in _execute_child raise child_exception OSError: [Errno 13] Permission denied Extra details: * *Python 2.7 *Ksh Version M-11/16/88i *Solaris 10 (SunOS 5.10) A: shlex is not doing what you want: >>> list(shlex.shlex("/bin/ksh -c \". /Home/user/.khsrc\"")) ['/', 'bin', '/', 'ksh', '-', 'c', '". /Home/user/.khsrc"'] You're trying to execute the root directory, and that is not allowed, since, well, it's a directory and not an executable. Instead, just give subprocess.call a list of the program's name and all arguments: import subprocess command_line = ["/bin/ksh", "-c", "/Home/user/.khsrc"] subprocess.call(command_line)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: access a java class from within groovy I have a simple java class: package test; class Hello { public static void main(String[] args) { System.out.println("Hi"); } } on which I do a javac Hello.java Problem: Now I would like to access this class from a groovy script (access.groovy) ... import test.* Hello.main(null) but groovy -cp . access.groovy will result in a MissingPropertyException . What am I doing wrong? A: Your class Hello needs to be declared as public to be accessible from other packages. As a dynamic language, Groovy can't identify such errors and ends up looking for a variable named Hello. It's generally a bad idea to use wildcard imports; in this case, using import test.Hello; would have given you a better error message.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: C# : How to change windows registry and take effect immediately I am trying to make a application that can change registry values. I Can Change registry Values well but problem is need a restart to get it`s effect. I want to do it without restart. I want change OS registry Value like as wallpaper and others. A: Registry changes already take effect immediately, however many applications (and some operating system components) only read registry settings once when they first start, so the registry changes won't have any effect until the application / machine is restarted. If you are responsible for maintaining an application that uses registry settings and you want your application to respond to registry changes immediately without needing to be restarted then you can use the WMI to recieve notifications when the registry is modified. See Registry Watcher C# If you are attempting to update a registry key for another application (or operating system component) and want the changes to take effect immediately then this is down to the specific application - be aware that there probably isn't a whole load that you can do unless this is already supported by that application, or you can persuade the application maintainers to modify the application for you. Update: If you are attempting to update OS settings like the wallpaper then usually the registry is the wrong place to look! As well as the problems you are currently facing you will probably find that the registry keys will change in future versions of Windows, breaking your application. Instead you should use the defined Windows APIs to do these sorts of things, for example the SystemParametersInfo function can be used to update the wallpaper, see Wallpaper in c#: For setting a wallpaper you can use SystemParametersInfo to set a wallpaper image programmaticly. This works for Bitmap's only, so when you want to set a other image-format you must first convert this to a Bitmap image. [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern Int32 SystemParametersInfo(UInt32 uiAction, UInt32 uiParam, String pvParam, UInt32 fWinIni); private static UInt32 SPI_SETDESKWALLPAPER = 20; private static UInt32 SPIF_UPDATEINIFILE = 0x1; private String imageFileName = "c:\\sample.bmp"; public void SetImage( string filename ) { SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, filename, SPIF_UPDATEINIFILE); } A: Registry changes will take immediate effect unless your application has cached the setting. In this case, you have 2 options: * *Read the value from the registry each time you want to use it, or *Subscribe to receive notifications of registry changes. There is a good discussion on SO. A: I suppose it does depend on the effect. The registry value gets changed immediately, but the reboot forces all programs to reload their registry values. A: Shut down and restart all apps/services that read your registry key/s when started. If an app/whatever reads a key at startup and never again, (like most of them), I cannot see any other way of propagating your change. Get ready for a lot of UAC popups... Rgds, Martin A: Just start task manager and in processes tab select explorer and end that task (shown in right corner). Then go up and select new task option from file tab and type explorer.....tasa here you are enjoy. A: Like many people have replied, some apps will only read a specific registry key once, so changing it will not have effect until that application is restarted. However, many windows registry settings can have their effects applied by broadcasting a notification of a settings change. Hopefully this can be of some help to others who come to this thread. [DllImport("user32.DLL")] public static extern bool SendNotifyMessageA(IntPtr hWnd, uint Msg, int wParam, int lParam); public static IntPtr HWND_BROADCAST = (IntPtr)0xffff; public static uint WM_SETTINGCHANGE = 0x001A; private static void ApplyRegistryChanges() { SendNotifyMessageA(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7567387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery: is there a reason not to always use live() for click and other functions? I really like using .live() in jQuery for click() focus() blur() and other interaction events. I do a lot of prototyping, so I find it gives me great flexibility if I want to dynamically add elements. For that reason, I find myself drawn to the idea of using it by default all the time. Is this a good idea, or is this bad performance? Does using .live('click',function(){}) slow things down in a way that .click(function(){}) doesn't? A: I think following answer will be suitable for the performance impact it does create How does jQuery .live() work? A: Regarding the performance, using the live is better in most cases. However live has several pitfalls, which are described in the documentation here http://api.jquery.com/live/#caveats. A: I remember that .live uses event bubbling. In my experience, I've seen noticeable performance hit using .live in big document with a frequently triggered event like mouseover. jQuery Doc: But as of jQuery 1.4, event bubbling can optionally stop at a DOM element "context". So, you can use that to minimize the performance effect. A: If you don't need your events to bubble up to the top of the DOM and you know the context in which your event will occur then delegate() is a much better choice in terms of performance. See this stackoverflow post on why delegate() is better than live() in this regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to apply constraint satisfaction problem to vertical/horizontal automated layouts? like swing and flex layouts I need to build a vertical and horizontal automated layout system. There is very little documentation on the internet about how to implement it, but I hardly found something that might help me "Constraint satisfaction problem". But I don't really know how to apply it to what I'm doing... Somebody has some information about this rare topic?
{ "language": "en", "url": "https://stackoverflow.com/questions/7567390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Placing Google Analytics code in Wordpress specific page I'm trying to get Google Analytics Code to work on the thank-you page after customer has filled in the contact form and I've tried putting it in the thank-you page which is in the pages under admin in Wordpress backend using HTML tab but it seems to generate unnecessary p and br tags in between codes especially before closing tag. I'm not sure whether that is causing the issue or not. Is there a way we can do this for just one page? A: I'm not 100 % sure whether it's possible at all to insert javascript with the tinyMCE Editor of Wordpress. If that's true, then you can try the following: * *Get the posts' ID: Look at the linking in your admin menu when you are in the view where you can see all your posts, e.g. http://www.your-url.com/wp-admin/post.php?post=796&action=edit 796 would be your ID here. *Enter the following in your header.php of your wordpress theme (to find at /wp-content/themes/theme-name): . <?php if (is_page(796)) { ?> //YOUR ANALYTICS CODE IN HERE <?php } ?> Replace 796 with your ID here, and put your analytics code in between the PHP code. A: It sounds like you're trying to add it using the "Visual" view, which formats whatever you put in into paragraphs, etc. Try switching to "HTML" view (the tab is at the top right of the input box) and add it there - hopefully that should allow you to add it without converting it! Edit: As per my comments below, I made a mistake - it seems even the HTML tab adds some degree of formatting. In this case, you may find some use with this plugin: http://wordpress.org/extend/plugins/raw-html/ This allows you to displable to auto formatting on a per-post basis. So on that specific page you could turn off the autoformatting simply to allow you to add that Analytics snippet. The only other way I can think off offhand would be to write a custom page_template just for that thankyou page and add it to there. Instructions are here: http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates
{ "language": "en", "url": "https://stackoverflow.com/questions/7567391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why you cannot use onRelease in a class I am trying set up a simple onRelease function of a button in AS2 within a class file but this is not allowed... public function callFunction(functionString:String) { var functionItems:Array = functionString.split(","); var functionName = functionItems.shift(); var functionParams = functionItems; EventBroadcaster.getInstance().broadcastEvent(functionName, {param:functionParams}); } _myButtonBtn.onRelease = function() { targetObject[targetFunction](); } public function setCloseAction(targetObject:Object, targetFunction:String) { _closeButton.onRelease = function() { targetObject[targetFunction](); } _closeButton._visible = true; } Could someone please tell me why this is and how do I go about setting getting my button click event to work? As mentioned in a previous post I have been tossed into this project and my knowledge of classes are very limited. When I publish the Swf file I get this Compiling error: This statement is not permitted in a class definition. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7567394", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: match a regular expression to get attribute I'm already so desperate with this one. I need to be able to match the following pieces of text but: 1) despite of any garbage before the text staveb and 2) I need to match every <OPTION ....</OPTION> with occurence of the text staveb that means, I need to match these pieces of text: <OPTION value="39"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Stavebníctvo</OPTION> <OPTION value="39">staveb</OPTION> <OPTION value="39">staveb</OPTION> from this text: <OPTION value="25"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Anglicky</OPTION> <OPTION value="19">Auto, moto</OPTION> **<OPTION value="39"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Stavebníctvo</OPTION>** <OPTION value="26">Školstvo</OPTION> **<OPTION value="39">staveb</OPTION>** Pleease help! A: try this: <OPTION\s+value="\d+">[^>]*staveb[^<]*</OPTION>
{ "language": "en", "url": "https://stackoverflow.com/questions/7567398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to add multilanguage Posts in PHPBB forum I add Multilanguage support in PHPBB forum (English/Spanish). English is default language. How I add Spanish posts. Only one editor is available for English. I already add language successfully. All forum translate to Spanish language except Post that are still in English language. I don't know how to add Spanish Version for the post. A: PHPBB Language Packs are available and can be downloaded here http://www.phpbb.com/languages/ A: Posts that are submitted by a user are not translated by the software into any other language without a MOD. Also, if you wish to have a second textarea to allow users to enter a spanish version of their post, that cannot be done withotu a MOD. I am not currently aware of existing MODs to either of the above.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: LazyInitializationException with OneToMany in the simpliest way I'm using Hibernate with jpa and I'm getting LazyInizializationException trying to do a very simple thing. I know what does LazyInizializationException means but I can't understand why it comes while i'm doing everything in the most common and simple way. This is the "one" side of the relationship: @Entity public class User implements Serializable{ @Id @GeneratedValue private int idUser; private String name; private String surname; private String username; @OneToMany(mappedBy="user") private List<Device> dev; ...getters and setters... and this is the "Many" side: @Entity public class Device implements Serializable { @Id @GeneratedValue private int idDevice; private String brand; private String model; @ManyToOne @JoinColumn(name="user_fk") private User user; ...getters and setters... the jUnit test that throws the exception is: @Test public void testLazyUserSnd() { User u = uDao.getUser(2); List<Device> devList = u.getDev(); Device aDevice = devList.get(0); // <--- Here the exception is thrown aDevice.getModel(); I made the relationship as explained in the Hibernate Documentation. Any hint? Am I making some big and stupid mistakes? A: While @Xavi's answer is perfectly reasonable, you may not always want to load the devices for a user. If you don't, there are 2 ways of fixing this. * *Create an additional method uDao.getUserWithDevices(id) and call that when you know you need devices, otherwise call the uDao.getUser(id). *Encapsulate the test method, and therefore any production code that uses the method, in a transaction. In other words keep the session open as long as you need to. Personally I'd use the transaction method since as it allows more flexibility and allows JPA to lazy load whenever it needs to. See also http://community.jboss.org/wiki/OpenSessionInView for more interesting information around session lifecycle. A: The exception is telling you that you're trying to get some of the lazy-loaded association's elements when the session is closed. Probably you should call u.getDev() or Hibernate.initialize(u.getDev()) inside the dao's method, when the hibernate session is still open. Or, if you're using Criteria, you could also use setFetchMode to force eager fetching. public User getUser(String id) { Session session = getSession(); Criteria criteriaQuery = session.createCriteria(User.class); criteriaQuery.add(Expression.eq("id", id)); criteriaQuery.setFetchMode("dev", FetchMode.JOIN); return criteriaQuery.uniqueResult(); } A: The entity is probably detached from the session (transaction context) when you access the relation. Try to enclose your test method in a transaction.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: disable/enable compilation errors in Netbeans I've made the terrible mistake of telling Netbeans always to ignore compilation errors when running my Maven application. Now that I want to revoke this, I can't seem to find an option anyway in the various configuration panels. Does somebody know where this option can be changed ? TIA ! Jan A: For NetBeans 8.0.2 (in my case): C:\Users\username\AppData\Roaming\NetBeans\8.0.2\config\Preferences\org\netbeans\modules\java\source\BuildArtifactMapperImpl.properties file contains: askBeforeRunWithErrors=false Set to true or file can be deleted, to reset. A: Don't bother - found it after making a directory diff : Stop Netbeans, remove the file underneath and start Netbeans again. .netbeans/7.0/config/Preferences/org/netbeans/modules/java/source/BuildArtifactMapperImpl.properties Simple, no ? :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Backbone.js : repopulate or recreate the view? In my web application, I have a user list in a table on the left, and a user detail pane on the right. When the admin clicks a user in the table, its details should be displayed on the right. I have a UserListView and UserRowView on the left, and a UserDetailView on the right. Things kind of work, but I have a weird behavior. If I click some users on the left, then click delete on one of them, I get successive javascript confirm boxes for all users that have been displayed. It looks like event bindings of all previously displayed views have not been removed, which seems to be normal. I should not do a new UserDetailView every time on UserRowView? Should I maintain a view and change its reference model? Should I keep track of the current view and remove it before creating a new one? I'm kind of lost and any idea will be welcome. Thank you ! Here is the code of the left view (row display, click event, right view creation) window.UserRowView = Backbone.View.extend({ tagName : "tr", events : { "click" : "click", }, render : function() { $(this.el).html(ich.bbViewUserTr(this.model.toJSON())); return this; }, click : function() { var view = new UserDetailView({model:this.model}) view.render() } }) And the code for right view (delete button) window.UserDetailView = Backbone.View.extend({ el : $("#bbBoxUserDetail"), events : { "click .delete" : "deleteUser" }, initialize : function() { this.model.bind('destroy', function(){this.el.hide()}, this); }, render : function() { this.el.html(ich.bbViewUserDetail(this.model.toJSON())); this.el.show(); }, deleteUser : function() { if (confirm("Really delete user " + this.model.get("login") + "?")) this.model.destroy(); return false; } }) A: This is a common condition. If you create a new view every time, all old views will still be bound to all of the events. One thing you can do is create a function on your view called detatch: detatch: function() { $(this.el).unbind(); this.model.unbind(); Then, before you create the new view, make sure to call detatch on the old view. Of course, as you mentioned, you can always create one "detail" view and never change it. You can bind to the "change" event on the model (from the view) to re-render yourself. Add this to your initializer: this.model.bind('change', this.render) Doing that will cause the details pane to re-render EVERY time a change is made to the model. You can get finer granularity by watching for a single property: "change:propName". Of course, doing this requires a common model that the item View has reference to as well as the higher level list view and the details view. Hope this helps! A: To fix events binding multiple times, $("#my_app_container").unbind() //Instantiate your views here Using the above line before instantiating the new Views from route, solved the issue I had with zombie views. A: I blogged about this recently, and showed several things that I do in my apps to handle these scenarios: http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/ A: I think most people start with Backbone will create the view as in your code: var view = new UserDetailView({model:this.model}); This code creates zombie view, because we might constantly create new view without cleanup existing view. However it's not convenient to call view.dispose() for all Backbone Views in your app (especially if we create views in for loop) I think the best timing to put cleanup code is before creating new view. My solution is to create a helper to do this cleanup: window.VM = window.VM || {}; VM.views = VM.views || {}; VM.createView = function(name, callback) { if (typeof VM.views[name] !== 'undefined') { // Cleanup view // Remove all of the view's delegated events VM.views[name].undelegateEvents(); // Remove view from the DOM VM.views[name].remove(); // Removes all callbacks on view VM.views[name].off(); if (typeof VM.views[name].close === 'function') { VM.views[name].close(); } } VM.views[name] = callback(); return VM.views[name]; } VM.reuseView = function(name, callback) { if (typeof VM.views[name] !== 'undefined') { return VM.views[name]; } VM.views[name] = callback(); return VM.views[name]; } Using VM to create your view will help cleanup any existing view without having to call view.dispose(). You can do a small modification to your code from var view = new UserDetailView({model:this.model}); to var view = VM.createView("unique_view_name", function() { return new UserDetailView({model:this.model}); }); So it is up to you if you want to reuse view instead of constantly creating it, as long as the view is clean, you don't need to worry. Just change createView to reuseView: var view = VM.reuseView("unique_view_name", function() { return new UserDetailView({model:this.model}); }); Detailed code and attribution is posted at https://github.com/thomasdao/Backbone-View-Manager A: I always destroy and create views because as my single page app gets bigger and bigger, keeping unused live views in memory just so that I can re-use them would become difficult to maintain. Here's a simplified version of a technique that I use to clean-up my Views to avoid memory leaks. I first create a BaseView that all of my views inherit from. The basic idea is that my View will keep a reference to all of the events to which it's subscribed to, so that when it's time to dispose the View, all of those bindings will automatically be unbound. Here's an example implementation of my BaseView: var BaseView = function (options) { this.bindings = []; Backbone.View.apply(this, [options]); }; _.extend(BaseView.prototype, Backbone.View.prototype, { bindTo: function (model, ev, callback) { model.bind(ev, callback, this); this.bindings.push({ model: model, ev: ev, callback: callback }); }, unbindFromAll: function () { _.each(this.bindings, function (binding) { binding.model.unbind(binding.ev, binding.callback); }); this.bindings = []; }, dispose: function () { this.unbindFromAll(); // Will unbind all events this view has bound to this.unbind(); // This will unbind all listeners to events from // this view. This is probably not necessary // because this view will be garbage collected. this.remove(); // Uses the default Backbone.View.remove() method which // removes this.el from the DOM and removes DOM events. } }); BaseView.extend = Backbone.View.extend; Whenever a View needs to bind to an event on a model or collection, I would use the bindTo method. For example: var SampleView = BaseView.extend({ initialize: function(){ this.bindTo(this.model, 'change', this.render); this.bindTo(this.collection, 'reset', this.doSomething); } }); Whenever I remove a view, I just call the dispose method which will clean everything up automatically: var sampleView = new SampleView({model: some_model, collection: some_collection}); sampleView.dispose(); I shared this technique with the folks who are writing the "Backbone.js on Rails" ebook and I believe this is the technique that they've adopted for the book. Update: 2014-03-24 As of Backone 0.9.9, listenTo and stopListening were added to Events using the same bindTo and unbindFromAll techniques shown above. Also, View.remove calls stopListening automatically, so binding and unbinding is as easy as this now: var SampleView = BaseView.extend({ initialize: function(){ this.listenTo(this.model, 'change', this.render); } }); var sampleView = new SampleView({model: some_model}); sampleView.remove(); A: One alternative is to bind, as opposed to creating a series of new views and then unbinding those views. You'd accomplish this doing something like: window.User = Backbone.Model.extend({ }); window.MyViewModel = Backbone.Model.extend({ }); window.myView = Backbone.View.extend({ initialize: function(){ this.model.on('change', this.alert, this); }, alert: function(){ alert("changed"); } }); You'd set the model of myView to myViewModel, which would be set to a User model. This way, if you set myViewModel to another user (i.e., changing its attributes) then it could trigger a render function in the view with the new attributes. One problem is that this breaks the link to the original model. You could get around this by either using a collection object, or by setting the user model as an attribute of the viewmodel. Then, this would be accessible in the view as myview.model.get("model"). A: Use this method for clearing the child views and current views from memory. //FIRST EXTEND THE BACKBONE VIEW.... //Extending the backbone view... Backbone.View.prototype.destroy_view = function() { //for doing something before closing..... if (this.beforeClose) { this.beforeClose(); } //For destroying the related child views... if (this.destroyChild) { this.destroyChild(); } this.undelegateEvents(); $(this.el).removeData().unbind(); //Remove view from DOM this.remove(); Backbone.View.prototype.remove.call(this); } //Function for destroying the child views... Backbone.View.prototype.destroyChild = function(){ console.info("Closing the child views..."); //Remember to push the child views of a parent view using this.childViews if(this.childViews){ var len = this.childViews.length; for(var i=0; i<len; i++){ this.childViews[i].destroy_view(); } }//End of if statement } //End of destroyChild function //Now extending the Router .. var Test_Routers = Backbone.Router.extend({ //Always call this function before calling a route call function... closePreviousViews: function() { console.log("Closing the pervious in memory views..."); if (this.currentView) this.currentView.destroy_view(); }, routes:{ "test" : "testRoute" }, testRoute: function(){ //Always call this method before calling the route.. this.closePreviousViews(); ..... } //Now calling the views... $(document).ready(function(e) { var Router = new Test_Routers(); Backbone.history.start({root: "/"}); }); //Now showing how to push child views in parent views and setting of current views... var Test_View = Backbone.View.extend({ initialize:function(){ //Now setting the current view.. Router.currentView = this; //If your views contains child views then first initialize... this.childViews = []; //Now push any child views you create in this parent view. //It will automatically get deleted //this.childViews.push(childView); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7567404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "83" }
Q: create a common converter for objects from different packages I have 5 webservices, A, B, C, D, and E. Each has autogenerated objects of the exact same structure, but with different names and in different packages. com.ws.a.carA contains parameters and com.ws.a.wheelA com.ws.b.carB contains parameters and com.ws.b.wheelB com.ws.c.carC contains parameters and com.ws.c.wheelC com.ws.d.carD contains parameters and com.ws.d.wheelD com.ws.e.carE contains parameters and com.ws.e.wheelE I want to create one function that can convert each of these objects (and the inner wheel) to a object named com.model.car, but I dont wan't many functions like : com.model.car convert(com.ws.a.objA obj) com.model.car convert(com.ws.b.objB obj) ... The problem is, I can't give all the objects a common interface to implement, because I don't want to manually change the autogenerated classes (they are recreated frequently). I need a way, probably with generics, to create a common function com.model.car convert(T obj) that will work for all the car types but I'm not sure how to implement it. A: You can use reflection for this. The easiest and cleanest way would probably be to use Apache Common BeanUtils, either PropertyUtils#copyProperties or BeanUtils#copyProperties. PropertyUtils#copyProperties copies the values from one object to another, where the field names are the same. So with copyProperties(dest, orig), it calls dest.setFoo(orig.getFoo()) for all fields which exist in both objects. BeanUtils#copyProperties does the same, but you can register converters so that the values get converted from String to Int, if necessary. There are a number of standard converters, but you can register your own, in your case com.ws.a.wheelA to com.model.wheel, or whatever. A: You can also check out Dozer A: I think you should consider using reflection. A: Using commons beanutils library you may do this utility class: public class BeanUtilCopy { private static BeanUtilsBean beanUtilsBean; private static ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean(); static { convertUtilsBean.register(new Converter() { //2 public <T> T convert(Class<T> type, Object value) { T dest = null; try { dest = type.newInstance(); BeanUtils.copyProperties(dest, value); } catch (Exception e) { e.printStackTrace(); } return dest; } }, Wheel.class); beanUtilsBean = new BeanUtilsBean(convertUtilsBean); } public static void copyBean(Object dest, Object orig) throws Exception { beanUtilsBean.copyProperties(dest, orig); //1 } When (1) beanUtilsBean use the converter (2) to pass the Wheel**X** values to the Wheel in destination bean. Use sample: CarB carB = new CarB(); carB.setName("car B name"); carB.setWeight(115); WheelB wheelB = new WheelB(); wheelB.setName("wheel B name"); wheelB.setType(05); carB.setWheel(wheelB); Car car1 = new Car(); BeanUtilCopy.copyBean(car1, carB); System.out.println(car1.getName()); System.out.println(car1.getWeight()); System.out.println(car1.getWheel().getName()); System.out.println(car1.getWheel().getType()); The output: car B name 115 wheel B name 5
{ "language": "en", "url": "https://stackoverflow.com/questions/7567409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Magento SOLR doesn't return results I am trying to integrate SOLR with Magento on my development machine. We are upgrading Magento and I want to test if SOLR is working as well. I am able to feed SOLR, the stats say that it has documents. In SOLR admin, when I put in : as query string, I do get the list of documents. But when I search for "maria mosters" for example, no results are returned. I have tried SOLR 1.4.1 (which we run in production) and 3.4.0. My schema.xml: http://pastebin.com/3a2J99re A: Thank you for your replies. I finally got my answer, for my case. I found out by checking the query string that was being logged by SOLR. This was for example: 127.0.0.1 - - [28/09/2011:09:05:34 +0000] "GET /solr/select?sort=score+desc&fl=id&spellcheck=true&spellcheck.count=2&qt=magento_nl&spellcheck.collate=true&spellcheck.dictionary=magento_spell_nl&spellcheck.extendedResults=true&fq=visibility%3A4+AND+store_id%3A1&version=1.2&wt=json&json.nl=map&q=%28maria+mosterd%29&start=0&rows=1 HTTP/1.0" 400 1405 When I requested this query the first time, it said that the field visibility was unknown. Apparently this field was added by Magento in the upgraded release. I added the field to the config, and ran the query again. Now it said that the dictionairy magento_spell_nl did not exist. What happened? The new Magento has a option called "Enable Search Suggestions". In my previous Magento version, this option didn't exist, so this spellchecker thing was not passed to the query string. When I turned this setting of, I was able to use my exact copy of the production server. A: *:* would work as its matching all on all fields. Search for maria mosters is going to search in the default field, if you are using the standard request handler. The default search field set in the schema is fulltext and I don't see any copyfields into it. So are you sure the field is populated. If you are using any custom request handler via the qt param, are the proper fields included in it ? sharing you solrconfig and full query might help for others to help you further. A: Looks like your issue is that in your schema, you have the fulltext field defined as the default search field, but you are not populating that field. I would recommend either setting the default field to another field that you are populating or when you execute your query, specify the field that you want to search against... Example text_en:"maria monsters" Please also see the SolrQuerySyntax page on the Solr Wiki for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect mail client : desktop or mobile, and platform if mobile? This question is similar to Standard way to detect mobile mail client? but not sure there's a solution inside. I understand how to handle mobile format with specific, screen-size-dependent css. But what about content AND/OR images ? Case study : - if mail is opened on desktop client app (Thunderbird,...) or web app (Gmail, ...), images say "download our iPhone app or Android app" with specific links to each app. - if mail is opened on iOS, image says "get our iPhone app" with app store link. - if mail is opened on Android, image says "get our Android app" with market link attached. Is this even possible ? Are there tools to do it ? How would you proceed ? Thanks ! A: You probably want some html tricks, but if this worked, such behavior would be most likely very dependent on email client used. Various mail clients may display content rather differently. Some may show plain-text alternative, some may choose to display html form. Html rendering may also vary. And no, there's no special filtering based on platform incorporated to email message format. Some links about email message specifiaction: rfc 2822 rfc 2045
{ "language": "en", "url": "https://stackoverflow.com/questions/7567413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Alternative to range.getBoundingClientRect I need an alternative to range.getBoundingClientRect() for FF3.6 (XULRunner 1.9.2). I cannot update to a newer XULRunner version. Any help? A: Try looking into jQuery Plus Plus (jQuery++), specifically the Range object. http://www.jquerypp.com
{ "language": "en", "url": "https://stackoverflow.com/questions/7567414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to call a excel macro from .net Web service? I am trying to call a excel macro from the my web service but it is unable to initialize the Excel.Application object. This is giving error at following line: Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application(); Even for publish the web service i am using the service account in the Application pool in the IIS. Can anyone tell me how can we call a macro in c#.net web service. Thanxs in Advance. A: The error you are getting might be from: * *Excel not installed on server *The user executing your IIS application pool doesn't have enough privileges to run excel. After coping with that, you can check how to run a macro here
{ "language": "en", "url": "https://stackoverflow.com/questions/7567415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing the XML to print a string with formatting attributes per word I have an XML which contains a field of the type: <mytext><![CDATA[ My name is <color value="FF0000">Bill</color>. ]]></mytext> Since I'm new to E4X methods, I wonder if there is a simple methodology (using E4X methods) in order to print the inner text: "My name is Bill." in a text area and having the word "Bill" colored i.e. red. The generalized situation is, if i can print the inner text and use XML tags to specify formatting attributes of the text per word. Do E4X supports this type of parsing, or do I have to program my own "little" parser for this situation? A: First, let's normalize the html content (I added a <content> tag to make it valid): var mytext:XML = XML("<mytext><![CDATA[<content>My name is <color value="FF0000">Bill</color>.</content>]]></mytext>"); Next step is to parse the given XML: var roughXML:XML = XML(mytext.text().toString()); Then you have to substitute your custom tags with standard tags: var output:XML = XML("<span/>"); for each(var tag:XML in roughXML.children()) { if (tag.name() == "color") { var fontTag:XML = XML("<font/>"); fontTag.@color = tag.@value.toString(); fontTag.appendChild(tag.text()); output.appendChild(fontTag); } //you can add here any rule for substitution that you need else { output.appendChild(tag); } } And finally, you can use an s:RicheEditableText to display your text var textFlow:TextFlow = TextConverter.importToFlow(output.toXMLString(), TextConverter.TEXT_FIELD_HTML_FORMAT); myRichEditableText.textFlow = textFlow;
{ "language": "en", "url": "https://stackoverflow.com/questions/7567416", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Chrome issue - Unable to retrive button(HTML tag) value while submitting form I have a scenario in which a button value is not being posted while submitting form in ASP.NET MVC controller. This is happening only for Google Chrome browser. For all other browsers Firefox, IE, I am getting Submit_0 value in Controller. //Server side public ActionResult Answers(string id, SurveyViewModel model, string Submit, string button) { string[] buttonParts = button.Split(new char[]{'_'}); .. ... } //Client Side @using (Html.BeginForm("Answers", "Survey")) { <button value="Submit_0" name="button" onclick="document.forms[0].submit();"><span><span>Submit</span></span></button> } Kindly suggest. A: I wonder if it is because the way you wired the button. Why don't you use something like this instead? <button type="submit" name="button" value="submit_0">Submit</button> Notice that the button has a type of submit (which eliminate the need to call document.forms[0].submit() manually)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I write Alt+Enter to a spreadsheet using PHP? I want to place Alt+Enter (line break) in a cell in an Excel spreadsheet. How do I write a character which is equivalent to Alt+Enter? A: \n is the escape-sequence for a line-break in a String. A: \n is for line break <br/>is for html break A: For Windows only (you mention Excel) the escape-sequence is \r\n. A: Try using CHAR(10) <string1> & CHAR(10) & <string2> it will produce <string1> <string2> in the excel cell. A: Please try to insert in following form: "\="."\"string1\""."&char(10)&"."\"string2\"" After saving it xls through PHP Apply wrap text on each column where your insert data
{ "language": "en", "url": "https://stackoverflow.com/questions/7567432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Slightly Distorted Bitmaps on some Android Devices I have a problem that occurs on some displays (HTC Hero, Motorola Defy, HVGA emulator) where some bitmaps are distorted in a peculiar way: The image apparently is shifted by one or two pixels, e.g. to the left, and the resulting gap on the right side is filled by duplicating pixels from the right border of the bitmap. I use pre-computed LDPI/MDPI/HDPI versions of these bitmaps, e.g. a notification icon that fits the specs for notification icons. I attached two images that show the effect. Please note: even though it might appear that the bitmap is tiled, this is not the case, other images consistently show that the pixels are not wrapped around but duplicated/stretched. Has anybody ever had a similar problem? Thanks in advance for any clues that could help me solve this issue, Arne
{ "language": "en", "url": "https://stackoverflow.com/questions/7567435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Javascript - emulating document.ready() on HTML object I have a main site A onto which I load content with AJAX from sub-site B. There is a jQuery file that alters elements on the site A (adds events to them, classes, re-renders them if needed etc) that is being launched on document.ready() Now I need to load content from site B into site A. I do it with a function: $.get("/some/url/",{},function(e){ $(".some_div").html(e); }); The problem is if I include jQuery in site B, the following happens: jQuery loads the content, puts it into site A and then triggers all the scripts that were fetched within it. Which causes re-render of the site and whole lot of mess. What I need to do is to emulate the document.ready() on the HTML object e right after it was pulled out of the site B but before it is appended to the site A (so I will have re-rendered HTML code with all events, classes and listeners ready). A: Can't you just put your code in the function, and run your stuff before calling: $(".some_div").html(e); Just above that line all the html from b is ready but not loaded or run. Or do you mean you want to put in the html and not the scripts? Just use the jquery function to strip out script tags (do e.find('script').appendTo(new_div);). Or add some code in b. Make a function called init() in b that calls everything. Everything else is in functions and nothing runs. When you are ready call init(). A: So after some research and time spent on this problem I've found a solution. In jQuery 1.4 there was a method .live() introduced. The problem is it works only on direct user interactions with UI (i.e. click(), hover() methods etc.). It wont work in methods such as .each() and it wont work with methods that are introduced by third party plugins (such as .accordion(), .tabs(), .datatable() etc. So right when I decided to extend .live() method on my own I found a wonderful library called livequery. Documentation to it is really good so you shouldn't have any problems figuring out how it works. It solved my problem and thus the case is closed. (Posting it here so if someone stumbles across similar problem he will find an answer)
{ "language": "en", "url": "https://stackoverflow.com/questions/7567437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handle Web Server with multiple clients I am working on a web application which can serve only one client.Now I need to include functionality to serve multiple clients. For that one mechanism should be there in which all the clients can see OR will be notified if any changes are done by some another client in the application. So my job is now to notify all the clients once any changes are done from the back end by another client. I found one solution in which I will call one cgi script from javascript at a particular period of time and it will let the other users know about the notifications done (i.e by alerts). But I think that it will be an overhead to server to continuously call that script repeatedly. Is there any other solution in which I can resolve my purpose ??? Thanks in advance...
{ "language": "en", "url": "https://stackoverflow.com/questions/7567462", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is a right CLS-compliant naming convention for protected fields? I am developing a CLS-compliant types library and I have a class inside It, which contains private, protected and public fields and properties. I use underscore symbol (_) as prefix for private or protected fields and little first letter to distinct their from properties with same names. It looks so: class SomeClass { private int _age; //Here is OK public int Age { get { return this._get; } } } But when I try to use protected fields I collide with a next problem: class SomeClass { protected int _age; //Here is NOT CLS-compliant (because of _ can't be the first symbol of identifier) public int Age { get { return this._get; } } } Then I tried to do in such way: class SomeClass { protected int age; //Here is NOT CLS-compliant (because of age and Age differ only in one symbol) public int Age { get { return this._get; } } } Please, tell me, what is right CLS-compliant notation or convention between developers for such cases? Have I to use prefixes in C-style like l_age? A: To back up Marc's answer, the guidance on Field Design from Microsoft states: Public and protected fields do not version well and are not protected by code access security demands. Instead of using publicly visible fields, use private fields and expose them through properties. This is probably why you will not find any useful guidance on naming them (in fact, the naming guidelines just point back at the Field Design page). A: Here's a more correct version, IMO: private int _age; public int Age { get { return this._age ; } protected set { this._age = value; } } or simply: public int Age { get; protected set; } If you properly encapsulate it, then it doesn't matter what the field is called, as nothing outside that type can see it. In comments, the question of events is then raised, with the example: protected EventHandler<StateChangedEventArgs> _stateChanged; public event EventHandler<StateChangedEventArgs> StateChanged { add { lock (this.StateChanged) { this._stateChanged += value; } } remove { lock (this.StateChanged) { this._stateChanged -= value; } } } Here I again assert that there is no reason for this field to be protected; the event does not belong to the derived class. It has 2 sensible operations it can want to perform: * *invoke the event *subscribe/unsubscribe to the event The former should be done via the On* pattern; the latter should just use the regular accessors (otherwise it violates the lock). Also, even if we assume that lock(this.StateChanged) is a typo (that would be a really, really bad thing to use as the lock object -it would not work at all), note that in C# 4.0 the compiler has a much more efficient lock strategy inbuilt (that uses Interlocked rather than Monitor) when you write a "field-like" event (i.e. no explicit add/remove). Consequently, the preferred approach here would be: public event EventHandler<StateChangedEventArgs> StateChanged; protected virtual void OnStateChanged(StateChangedEventArgs args) { var snapshot = StateChanged; // avoid thread-race condition if(snapshot != null) shapshot(this, args); } and... that's it! * *if the subclass wants to subscribe/unsubscribe (not ideal, but meh) it just uses StateChanged += and StateChanged -= *if the subclass wants to invoke the event, it calls OnStateChanged(...) *if the subclass wants to tweak the event logic, it adds an override to OnStateChanged no need for any non-private fields.
{ "language": "en", "url": "https://stackoverflow.com/questions/7567464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }