text
stringlengths
8
267k
meta
dict
Q: Postfix and Amazon S3 I have a Postfix mail server running on a Amazon instance. Is there a way to interact with Postfix and save every mail that comes to server in a file on Amazon S3 and to save email details in a Amazon SQS queue (mail details: to, from, subject, etc, and Amazon S3 file name)? I'm new in Linux and Postfix. Maybe a script or something? Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Joomla: multiple joomola sites under 1 domain/1 installation of joomla? Basically I am wondering if i can have 1 main site (e.g. 'www.mysite.com') with one look/template applied and articles associated with that site, then a completely different site with a different look/different articles for a sub domain 'www.mysite.com/someotherpage' Is this possible? and if so is it possible under 1 installation of joomla or will I have to install and setup joomla for every new sub domain? A: Its possible..i have done before. i have refer following thinks for that site.i hope following links are more useful to you.Link1 Link2 All the Best .. With Regards, R.Ram kumar. A: Do you simply want to have a different design for different menu items or do you actually want to have two completely seperate sites? Because you can assign different templates to different menu items and in Joomla 1.6/1.7, you can even have the same template but with different parameter sets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Hiding code in ASP.NET application I have an ASP.NET application that i deployed to a server by copying the project to the server and then configuring IIS. What happens now is that i need to prevent the access to the code. Is there any way to do this? Do i need to deploy in a different way or is there a way to somehow "encrypt" the code thus rendering it unreadable? Regards, A: Yes you should only publish. inside Visual Studio, in solution explorer, right click on the web project and select publish. this will create all you need to deploy ( pages, assemblies, resources...) but will not include the source code. A: A simple way is to obfuscate the code. This doens't hide the code per se, but it makes it very difficult to read and understand. See this wiki page for more information. On another note, if you publish the application by using the release configuration, you'll only upload assemblies and other parts vital for the site, not the source code in readable form. Be wary though, the dll's can be reverse engineered. A: You can use an obfuscator such as dotFuscator on your assemblies. The better obfuscators will stump most decompilers (such as Reflector), but are normally not free. Update: Seeing as you mean that you simply do not want code to be deployed with your application: Publishing should be enough, so long as you don't use the app_code folder - code in this folder will be deployed as is.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526269", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php script downloads after form submission instead of execution The site have a form where pdf is uploaded and form is submitted. For small pdf file size 345KB. it works fine. But for large pdf size the php script ids downloaded instead of execution. I have chnaged the .htaccess as per below for large file support. But for large files same happens. .htaccess - php_value upload_max_filesize 32M php_value post_max_size 32M php_value max_execution_time 3600 php_value max_input_time 3600 php_value memory_limit 32M Any help will be appreciated Thanks in advance Mangesh A: Even if a php file fails to run, it should NEVER be downloaded (I assume the downloaded script shows all your php code). This is a serious (apache) problem. Contact your webhost with this!
{ "language": "en", "url": "https://stackoverflow.com/questions/7526276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sencha touch: Issue with adding items dynamically I have the following control: app.views.MapControl = Ext.extend(Ext.Panel, { style: { background:'white' }, items: [{ xtype: 'panel', id: 'mapContainer', width: 1700, height: 1124, html: "<img class='mapImg' style='width:100%; height:100%; padding:0; margin:0' src='imagery/tube_map.gif'>" }], After the control's rendering I am adding a few items dynamically like that: var newPin = new app.views.Pushpin({x:pinPosX, y:pinPosY}); this.theMap.add(newPin); The Pushpin control looks like this: app.views.Pushpin = Ext.extend(Ext.Panel, { xtype: 'panel', style: { background: 'url(imagery/pin.png)' }, width: 50, height: 50, x: 0, y: 0 The problem: When I don't add any pins dynamically then the tube map image show fine. But if I add any, then for every pin I add there is a 50px offset appearing above from the tube map. Why is that? Could anyone please suggest any work-around? Thank you in advance. A: The pins are still taking up space. Add position: absolute; to their style.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can a session carry long text? In ASP.NET C# Session["transfer_item_1"] can this function carry a very long text of 1Mn chars? or do it have any limits? A: You can do that but it is not recommended neither serves the purpose. It degrades server performance. Check this for your complete options. http://msdn.microsoft.com/en-us/library/z1hkazw7.aspx A: If you're not using SQL server to hold your session, the limit of your session in the server varies according to the available memory you have available. You may successfully store it when in local development machine, but may get out of memory errors when trying it on the production server. Using sql server may solve your needs, but performance is terrible and not a good idea. If it's a same object that many users will be accessing and sharing, you may try looking into storing it in the Cache. A: A session is typically stored in memory (although it can be configured to be stored in sql server etc) so yes it has limits but 1mn characters will probably be less than 5mb of data. Although if this data will be created per request and is unique per user, you might run out of memory depending on the number of hits you get on your application. If this information is typically used by all requests you might consider using the Cache object or the Application object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Incrementing javascript problem I'm extremely new to javascript so I've no idea if I'm doing this correctly. I've got some php that is filling a javascript variable array: <?php $pages = get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order')); $data = array(); foreach($pages as $post){ setup_postdata($post); $fields = get_fields(); $data[] = '<p>'.$fields->company_name.'</p>'; } wp_reset_query(); // the js array echo 'var marker_data = ["'.implode('","', $data).'"];'; ?> This then feeds this javascript: infowindow.setContent(marker_data[i]); The problem is that it's not incrementing. If I change the "i" to "0" or "1" then it works. But obviously I need it to increment through. A: You need to increment i in JavaScript, not in php, like this: <script type="application/javascript"> <?php $pages =get_pages(array('child_of' => $post->ID, 'sort_column' => 'menu_order')); $data = array(); foreach($pages as $post){ setup_postdata($post); $fields = get_fields(); $data[] = '<p>'.htmlspecialchars($fields->company_name).'</p>'; } wp_reset_query(); echo 'var marker_data = ' . json_encode($data) . ';'; // Instead of implode ?> for (var i = 0;i < marker_data.length;i++) { infowindow.setContent(marker_data[i]); } </script> A: Once your PHP runs and returns the page, have a look at the source and look at your JS. It should look something like this var marker_data = ['<p>Comp 1</p>', '<p>Comp 2</p>', '<p>Comp 3</p>']; This means you've built your array of strings. Now you'll need to use a javascript loop to iterate through it, something like this. var length = marker_data.length; for (var i = 0; i < length; i++) { infowindow.setContent(marker_data[i]); } Remember that all of this iteration should happen in your JS code and not your PHP code. They are not to be mixed like that. A: Good answears given above. This is a general old school instructional way how you mix php and javascript arrays, it can also be adjusted to your needs but I also suggest you go beyond it and look for new schoold things too. <html> <head> <script type="text/javascript"> var myRandoms = new Array(); <?php $dbq="\""; for($i=0;$i<9;$i++) echo 'myRandoms[',$i,']=',$dbq,rand(1,999),$dbq,';'; ?> var len=myRandoms.length; var i; for(i=0;i<len;i++) alert(myRandoms[i]); </script> </head> <body> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7526294", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Indy DnsResolver Invalid Packet Size Delphi XE2 i am working in delphi XE2 i want to run dnsresolver over tcp as it throws error when ever data is greater than 512 byte i think due to udp size limit. so what configration is needed for dnsresolver to work over tcp with increased size limit. thanks A: TIdDNSResolver only uses TCP for AXFR and IXFR queries, everything else uses UDP instead. When using UDP, TIdDNSResolver uses a hard-coded 8192 byte buffer to receive the server's answer, so it can certainly handle more than 512 bytes. Where exactly are you hitting the 512 byte limit? What does the call stack look like when the error occurs?
{ "language": "en", "url": "https://stackoverflow.com/questions/7526301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Touch Events on SVG with JQuery mobile I work on a web app which contain SVG in each page, in order to turn a page, I must to use swipe (left and right). Swipe events are detected without any problem on a div or img, etc. But it is impossible to detect touches event on included SVG file :( I'm using JQuery 1.6.4 and JQuery mobile 1.0b3. JS : $('.touchPad object').live('swipeleft swiperight',function(event){ var currentPage = getVar("page"); if(currentPage == "0") { currentPage = 1; } if (event.type == "swiperight") { currentPage ++; var page = "page="+currentPage; $.mobile.changePage({ url: "http://asample.com/JQueryMobileTests/index.php", type: "get", data: page}, "slide", true ); } if (event.type == "swipeleft") { currentPage --; var page = "page="+currentPage; $.mobile.changePage({ url: "http://asample.com/JQueryMobileTests/index.php", type: "get", data: page }); } event.preventDefault(); }); HTML : <div role-data="page" class="touchPad"> <div role-data="header"></div> <div role-data="content"> <div> <h1>Page : </h1> <object type="image/svg+xml" data="pict.SVG" width="800" height="800"></object> </div> </div> </div> A: I have exactly the same problem when trying to get swipe Events on svg which contains animation on click. The only way I have found to get the swipe event is to put a div overlaying the svg with opacity at 0 but I lose the click event on SVG then. <svg style="width:100px; height:100px" /><div style="position:absolute; width:100px; height:100px; opacity:0">&nbsp;</div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7526305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use a second database for user authentication in Symfony2? In my Symfony 2.0 application, I have to access a second database which contains the user data. Accordingly, I've got two database connections defined in config_*.yml. My approach to this problem was to pretty much duplicate the existing EntityUserProvider and registering it as a service in services.yml like this: services: security.user.provider.concrete.acme_provider: class: Acme\MyappBundle\Security\Core\Authentication\Provider\AcmeUserProvider arguments: [@doctrine.orm.entity_manager, Acme\MyappBundle\Entity\Users, 'username'] This works fine so far, except that it provides me with the default entity manager. How can I inject an entity manager which uses the other database connection? I guess that I'll have to set it up as a service, but I don't know how. A: If you want to use a specific EntityManager in a service, inject the whole Doctrine Registry as an argument, like this : services: security.user.provider.concrete.acme_provider: class: Acme\MyappBundle\Security\Core\Authentication\Provider\AcmeUserProvider arguments: [@doctrine, Acme\MyappBundle\Entity\Users, 'username'] Then, in your service constructor, affect the EntityManager you want to use as a class property : namespace Acme\MyappBundle\Security\Core\Authentication\Provider; use Symfony\Bundle\DoctrineBundle\Registry; // .... class AcmeUserProvider implements UserProviderInterface { private $em; // ... public function __construct(Registry $doctrine, $class, $property) { $this->em = $doctrine->getEntityManager('your_em'); // .... } // .... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7526306", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: The Weblogic server shuts down on closing the script window? I have installed the Fusion SOA 11.1.1.5 on a remote linux (64 bit) machine and successfully started the weblogic server by using the startWeblogic.sh command from the DOMAIN_HOME/ folder (not from the DOMAIN_HOME/bin/ folder). I have a couple of doubts wrt this: * *Is this the correct startWeblogic.sh script that should be executed, i.e. the one in the domain_home or the one in the domain_home/bin ? *I could get the server up by just running the startWeblogic.sh from the domain_home folder, but on closing the window running the script the server alos goes down. What is the correct way to start the server ? A: 1.Is this the correct startWeblogic.sh script that should be executed, i.e. the one in the domain_home or the one in the domain_home/bin ? Yes - the startWeblogic.sh in DOMAIN_HOME is the right one to run, it internally will call the bin/startWeblogic.sh. Just check it out by reading the file in the DOMAIN_HOME 2.I could get the server up by just running the startWeblogic.sh from the domain_home folder, but on closing the window running the script the server alos goes down. What is the correct way to start the server ? SO you are running the Weblogic sh in the foreground, which is why it temrinates when you close the window. You can send this to background by doing command & i.e. startWeblogic.sh & see more at http://www.washington.edu/computing/unix/startdoc/shell.html#run Later you can recover the running processes and bring it back into foreground, but I guess you only need to tail the running logs to see what's happening within Weblogic.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to check device is ipod when send sms inapps in iphone how to check device is ipod when send sms inapps in iphone. i want to diasable sending sms when device is ipod touch   here is my code smsComposer = [[MFMessageComposeViewController alloc] init]; smsComposer.navigationController.navigationBarHidden = NO; smsComposer.wantsFullScreenLayout = YES; if([MFMessageComposeViewController canSendText]) { smsComposer.body = [NSString stringWithFormat:@"Join me : %@",urlStr]; smsComposer.recipients = numberArr; smsComposer.messageComposeDelegate = self; [self.view.superview addSubview:smsComposer animated:NO]; } this wrking well for iphone For ipod sms sending facility not available . i want to chek if device is ipod .is antbody hav idea abt chking device type . Thanks A: use this one: for detecting device NSLog(@"name:%@\n model:%@ \n localizedModel:%@ \n systemName:%@ \n systemVersion:%@ \n uniqueIdentifier:%@",[[UIDevice currentDevice] name], [[UIDevice currentDevice] model], [[UIDevice currentDevice] localizedModel], [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion], [[UIDevice currentDevice] uniqueIdentifier]); A: You should check if the device can send SMS, not if the device is an iPod. Class messageClass = (NSClassFromString(@"MFMessageComposeViewController")); BOOL canSendSMS = false; if (messageClass != nil) { if ([messageClass canSendText]) { canSendSMS = true; [self displaySMSComposerSheet]; } } if(!canSendSMS) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Device not configured to send SMS." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; [alert release]; NSLog(@"Device not configured to send SMS."); } FYI, how I display the SMS compose sheet: - (void)displaySMSComposerSheet { MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init]; picker.messageComposeDelegate = self; picker.recipients = [[NSArray alloc] initWithArray:tickedArray]; picker.body = @"Put the default message in here..."; [self presentModalViewController:picker animated:YES]; [picker release]; } Then this method is fired when trying to display the view: - (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result { switch (result) { case MessageComposeResultCancelled: NSLog(@"Result: SMS sending canceled"); break; case MessageComposeResultSent: NSLog(@"Result: SMS sent"); break; case MessageComposeResultFailed: NSLog(@"Result: SMS sending failed"); break; default: NSLog(@"Result: SMS not sent"); break; } [self done:self]; } Again, I don't recommend this but if you want to check what device it is then you could use this: - (NSString *) platformString { NSString *platform = [self platform]; if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G"; if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G"; if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS"; if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4"; if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G"; if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G"; if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G"; if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G"; if ([platform isEqualToString:@"iPad1,1"]) return @"iPad"; if ([platform isEqualToString:@"iPad2,1"]) return @"iPad"; if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator"; return platform; } A: NSString *deviceType = [UIDevice currentDevice].model; if([deviceType isEqualToString:@"iPhone"]){ //Make ur decision here.... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7526316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use both blank and default date in date_select in Rails? The following code works as expected, using the @the_date as the default selected date. <%= date_select("the_date", "", :default => @the_date ) %> However, in the case there is no date, it needs to show blanks. The following code displays blanks, but also forces the default selection to be blank even when the date is defined. <%= date_select("patient_details[birth_date]", "", { :default => @the_date, :include_blank => true } ) %> How do you set the default selection to a date, and to blank if the date is nil? Working in Rails 3.07. Thanks. A: Just, :include_blank => @the_date.nil? , it should do the trick. See example below date_select(:patient_details, :birth_date, { :default => @the_date, :include_blank=> @the_date.nil? }) A: Rails ignores your :default if you also use either :include_blank or :prompt. IMO this is a bug but there we go.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526318", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: WebGL geometry interactions I have a dynamic surface in WebGL, that is animated in vertex shader. I want other objects to interact with this surface (for example, an object riding on dynamic terrain). What's the best way to do this? Should all these calculations be done on CPU? Is there a way to calculate this stuff on GPU? Basically, what I want is vertex shader with access to other (already transformed) vertices -- that would be perfect. A: I'm not sure you can do this on the shader, unfortunately. The closest I can think of is passing in a second set of attributes, but the vertex count would have to be identical, and you could only validate one vertex of one model against a vertex with the same index of the other model (because you have no way of iterating through them all). Somehow, I don't think this is what you're looking for. Your best bet is to implement these sorts of things (collision detection, for instance) on the CPU. It's very slow in JavaScript, and you'll need to think long and hard about the best algorithm to use for your scene, but it's the only thing I can think of that would actually work. A good start would be to use spatial partitioning (examples: octree, BSP -- binary space partitioning -- tree). I've not done any sort of benchmarking, yet, but I have a hunch BSP trees would be more effective than octrees in most JavaScript scenes. There are often fewer checks to make overall, and potentially much less recursion. Also, BSP trees afford you the nearly unique ability to process geometry from back-to-front or front-to-back relative to any arbitrary point in space without having to constantly sort and re-sort the geometry. The drawback to BSP trees (and octrees to a lesser, but still nontrivial, extent) is that their geometry must remain static. That is, moving individual triangles on the fly doesn't work all that well with these trees, because then the geometry does have to be re-sorted. I don't think the static nature of spatial partitioning is a particularly troublesome issue if your meshes' animations are relatively simple, slight and predictable (such as a flag waving in the wind), but if they are more complex (such as a crumbling building or falling rocks), then these types of spatial partitions may not be viable for you at all. Update: If your models consist of part-static and part-dynamic triangles, such as windmills (whose towers are static and fins are dynamic), then you could use spatial partitioning for the static parts, so that if you only take unnecessary performance hits for dynamic triangles, and reap the benefits of spatial partitioning for those triangles that aren't moving too much. Update: Actually, there is one way you might be able to "kinda" do this at least partly on the shader. Specifically in reference to your example of an object riding on dynamic terrain, you could feasibly render that dynamic terrain to an offscreen framebuffer, then plot the object's position onto the same framebuffer, and use readpixels() to read in the height of the terrain at that position. This would only work for height maps, and the framebuffer would obviously need to be updated every time the terrain changes (if ever). However, it'd be a relatively simple way to see how high the object should be positioned on dynamic terrain without having to do the terrain generation itself on the CPU. This wouldn't be true collision detection though, and the object would still be subject to other issues (like having one wheel on or under the terrain and one wheel in midair). You could work around these issues but the solution would be nontrivial, probably involving multiple checks against the framebuffer data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JS/jQuery number increasing in for According to the example, i want in each times adding new input with putting number in fields(1, 2, 3), number increasing in each one from new input adding to name[+number increasing here+][] in the input. Now i have this in my code: Example: if put to "field 1" number 2 we get tow new input that name it is name[0][], name[1][]. in "field 2" put number 3 we get name[0][], name[1][], name[2][] in "field 3" put number 2 we get name[0][], name[1][] I want thie: if put to "field 1" number 2 we get tow new input that name it is name[0][], name[1][] in "field 2" put number 3 we get name[2][], name[3][], name[4][] in "field 3" put number 2 we get name[5][], name[6][] and etc. Code: $('input').live("keyup", function () { var id = '#'+$(this).closest('b').attr('id'); $(id+' .lee').empty(); var $val = $(this).val(); for (var i = 0; i < $val; i++) { $(id+' .lee').append('<input type="text" name="hi['+i+'][]">'); } }); A: Since you want to update all of the inputs on change, you could loop through all inputs after appending the elements. Just add a classname to them so you know which ones to count. Example: $('input').live("keyup", function () { var id = '#'+$(this).closest('b').attr('id'), val = $(this).val(); $(id+' .lee').empty(); for (var i = 0; i < val; i++) { $(id+' .lee').append('<input type="text" class="input_generated">'); } $('input.input_generated').each(function(i) { $(this).attr('name', 'hi[' + i + '][]'); }); }); Fiddle: http://jsfiddle.net/rHUqS/1/ A: By using a variable outside the function, you can solve this simply. However, it would always just increment the index numbers; if you typed the counts in in the wrong order, your indexes would be in the wrong order. But maybe that's okay. var counter = 0; $('input').live("keyup", function () { var id = '#'+$(this).closest('b').attr('id'); $(id+' .lee').empty(); var val = int($(this).val()); for (var i = counter; i < val + counter; i++) { $(id+' .lee').append('<input type="text" name="hi['+i+'][]">'); } counter = val + counter; }); EDIT: fixed val coming through as a string not an int
{ "language": "en", "url": "https://stackoverflow.com/questions/7526326", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to 'continue' from within ForEach WorkFlow activity? At the moment I'm capturing any relevant exceptions, then using an If activity to decide whether to continue processing or not. In non workflow code I'd just continue to the next item. Is there a Workflow equivalent to continue? A: Neither continue, nor break for that matter, are natively implemented inside WF. You can easily implement it with a custom NativeActivity. Check this link for the official samples. At WF\Basic\Built-InActivities\EmulatingBreakInWhile folder you've an example on how to emulate break behaviour. Same thing can be done to continue.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to pass parameters to ui:include that inside of c:forEach tag We are trying to create a list with iterating an entity with ui:include. my .xhtml file is like; <c:forEach items="#{entityHome.list}" var="entityId"> <ui:include src="/some.xhtml"> <ui:param name="id" value="#{entityId}" /> </ui:include> </c:forEach> We have already created a .xhtml file to visualize single entity. Not we want a list of all entities. Firstly we were using a h:dataGrid but according to this we changed it to c:forEach. Now when page is rendered, fields in /some.xhtml are empty. I think we cant pass parameter to ui:include. By cant i mean for this situation. Any idea? Thanks. A: I just had the same problem, what I did to solve it was putting another ui:param above the ui:include, and then link that param to the param inside the ui:include : <c:forEach items="#{entityHome.list}" var="entityId"> <ui:param name="someId" value="#{entityId}"/> <ui:include src="/some.xhtml"> <ui:param name="id" value="#{someId}" /> </ui:include> </c:forEach> This seemed to do the trick for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Conditional picture in an access form I would like to know whether it is possible or not to display a conditional picture in a form. Example: if X>0 then picture 1 is displayed else picture 2 is displayed I have looked for it but I didn't find anything Thank you A: If X > 0 Then Me.Picture = "c:\picture1.jpg" Else Me.Picture = "c:\picture2.jpg" End If Or if the picture is not directly on the form, but in a image control: If X > 0 Then Me.NameOfImageControl.Picture = "c:\picture1.jpg" Else Me.NameOfImageControl.Picture = "c:\picture2.jpg" End If EDIT: Okay, you can do this when you have the form open in design mode: * *there is a button in the toolbar to open the code window: (the screenshot is from Access 2003, I don't know which version you're using) *you can run code on events in the form like when the form is opened or closed. Check out this tutorial (Page 10). And here is another tutorial about VBA Basics in Access.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect if user is test user Facebook test users (created for an app) are working different in some ways than normal users. Ie. they can't like fanpages, so you can't test if "create.edge" listener is setup correctly. Is there a way to detect if user authenticated to app is test user? It would be useful to implement fake version of dialogs, that test user can't use (ie. liking a fanpage). My research: * *I have checked signed_request passed to app and it looks same for test users as for normal users. *I have checked graph.facebook.com/[test user id] and it also look normal. A: You cannot check if user is a test user basing on his Graph API details. Similarly, you cannot check if user like’s a specific page. You can however check your page_id against user liked pages list. So in order to determine if given user_id is a regular or a test user, you’d have to check it against the application test user list: https://graph.facebook.com/APP_ID/accounts/test-users?access_token=APP_ID|APP_SECRET So the flow would be like this: * *Authenticate user *Get his ./likes list *Find your page_id and exit successful *Get your APP ./accounts/test-users list *Find given user_id and exit successful *Exit with failure -- require user to like your page. That’s one extra call, but you can safely cache results for performance gains, since test users cannot be converted to regular users. I’d advice to cache the "likes" check for some time as well, but YMMV. A: Is Facebook user is test you can change name and password, else return error code (#200) You do not have sufficient permissions to perform this action **My solution: ** public function isTestUser($facebook_uid){ FacebookSession::setDefaultApplication(config_item('APP_ID'), config_item('APP_SECRET')); $session = FacebookSession::newAppSession(); try { $session->validate(); } catch (FacebookRequestException $ex) { // Session not valid, Graph API returned an exception with the reason. return FALSE; } catch (\Exception $ex) { // Graph API returned info, but it may mismatch the current app or have expired. return FALSE; } $request = new FacebookRequest( $session, 'POST', '/'.facebook_uid, array( 'password' => 'password', 'name' => 'Test Username' ) ); try { $response = $request->execute(); } catch (FacebookRequestException $ex) { // (#200) You do not have sufficient permissions to perform this action // (#100) Invalid password // (#100) Invalid name return ($ex->getCode() == 100) ? TRUE : FALSE; } catch (\Exception $ex) { return FALSE; } /* object(Facebook\GraphObject)#1714 (1) { ["backingData":protected]=> array(1) { ["success"]=> bool(true) } } */ $graphObject = $response->getGraphObject(); return ($graphObject) ? TRUE : FALSE; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7526338", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MS CRM c#: Pickup string guid from dictionary and use it to populate lookup field when creating a new CRM record I'm a total newbie to C#. Trying to create a custom entity record. I have created a windows service that can connect and create the CRM custom entity record but only if I hard code the GUID's for the lookups. How can I pickup the GUID from the dictionary and turn it into a lookup like I do for the text fields? snippet is below. aar_assessmentresult aar_assessmentresult = new aar_assessmentresult(); foreach (string key in dicColumnList.Keys) { colVal = string.Empty; if (dicColumnList.TryGetValue(key, out colVal)) { //this works if (key.ToString() == "AssessmentResultName") { aar_assessmentresult.aar_name = colVal.Replace("'", "''"); } //Code breaks here if (key.ToString() == "ContactID") { Guid contactid = new Guid(); aar_assessmentresult.aar_contactid = new Lookup(); aar_assessmentresult.aar_contactid.type = "contact"; aar_assessmentresult.aar_contactid.Value = contactid; } } } crmService.Create(aar_assessmentresult); A: when you do this: Guid contactid = new Guid(); aar_assessmentresult.aar_contactid = new Lookup(); aar_assessmentresult.aar_contactid.type = "contact"; aar_assessmentresult.aar_contactid.Value = contactid; you are trying to set a contact lookup with an invalid reference since your variable contactid does is not related to an existing contact record. You must create the contact in before or refer to a valid existing contact before doing crmService.Create(aar_assessmentresult);
{ "language": "en", "url": "https://stackoverflow.com/questions/7526342", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Format "12345678" to "1234-5678" How to format a string of numbers "12345678" to "1234-5678". string str = "12345678"; //I want to format it like below res = "1234-5678"; Thanks A: You can use string.Insert: string res = "12345678".Insert(4, "-"); The parameters are the index to insert into and the string to insert. A: In case you need to format numbers, you can use String.Format() method: int test = 12345678; string res = String.Format("{0:####-####}", test); // res == "1234-5678" A: How I could understand your desirable format is: to insert a hyphen after first four symbols in the string. if so, then It is very simple: res = str.Length > 4 ? string.Concat (str.Substring (0, 4), "-", str.Substring (4)) : str; If your format is other, please descride it in details. A: You can also use .Substring like so: string str1 = str.Substring(0,4); string str2 = str.Substring(4,4); string res = str1 + "-" + str2; A: I used Visual Basic Code It is not hard to convert on C# Dim str As String = "12345678" Dim num As Long = CLng(str) Dim strOut As String = Format(num, "####-####")
{ "language": "en", "url": "https://stackoverflow.com/questions/7526346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery ui autocomplete without filter I need to show user all autocomplete choices, no matter what text he already wrote in the field? Maybe i need some other plugin? $('#addressSearch').autocomplete("search", ""); That doesn't work. A: There are two scenarios: * *You're using a local data source. This is easy to accomplish in that case: var src = ['JavaScript', 'C++', 'C#', 'Java', 'COBOL']; $("#auto").autocomplete({ source: function (request, response) { response(src); } }); *You're using a remote data source. $("#auto").autocomplete({ source: function (request, response) { // Make AJAX call, but don't filter the results on the server. $.get("/foo", function (results) { response(results); }); } }); Either way you need to pass a function to the source argument and avoid filtering the results. Here's an example with a local data source: http://jsfiddle.net/andrewwhitaker/e9t5Y/ A: You can set the minLength option to 0, then it should work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jQuery in Windows 8 JS Applications Can we use frameworks like jQuery and jQuery UI in Windows 8 JS Applications? I can't find a document where I can read something about other frameworks. Thanks. A: Yes, you can. The only thing needed is to add the required JavaScript files in your application in Visual Studio and include them from there. Using any CDN won't work as you can't load external JavaScript files in a Metro JavaScript application. A: There is some fix in jQuery library that you can include it in your Windows 8 development. Here is the link to get the jQuery library (with some fix to tailor for Wins 8). https://github.com/appendto/jquery-win8 The work is done by AppendTo and they had a joint talk with Microsoft at BUILD conference this year. More detail for this jQuery library: jQuery for Windows 8 With the recent release of Windows 8 many developers have eagerly set out to create jQuery-enhanced applications for Windows 8. Unfortunately, all of these individuals quickly learned that jQuery and Windows 8 initially suffer a bit of friction when brought together. Faced with this issue, appendTo is pleased to release a custom copy of jQuery that will play nicely in Windows 8. Just download it, include it in your project, and you'll be up and running. To ensure the project's direction was carefully planned, appendTo communicated with the jQuery team routinely to address any concerns about modifying some aspects of jQuery (or its Unit Tests) to improve compatability with Windows 8. Given that this is a preview and you may come across issues in your own projects, we would like to encourage you to freely submit issues and feedback here on GitHub. We will do our best to answer your concerns in a timely manner, and resolve issues as quickly as possible. Please note that in order to get the best experience with jQuery and Windows 8 you'll need more than a modified library, you will also need an understanding of basic security concerns in the Windows 8 environment. Many of these concerns are with how you, the developer, use $.html() (and other similar methods). Please see http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx for further details. Watch the presentation given at Build 2012 online at http://channel9.msdn.com/Events/Build/2012/3-130
{ "language": "en", "url": "https://stackoverflow.com/questions/7526360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to detect if .Net 3.5 is present on the System? I know this question has been answered in other post but it dosent solves my problem: Senario: i have developed an application .net framework 3.5 sp1 using WPF When i run the application by clicking the executable i wish to check if the required .net Version is installed or else give a message to the user..... i tried all solution available on the net.... but if the Run the application on a machine which does not have .net framework or has a framework version lower that 3.5 .. its shows the crash screen My Code that i am currently using in App.Xaml.cs //Check the registry entry for .NET Framework. RegistryKey frameworkRegistryKey = Registry.LocalMachine.OpenSubKey(DOT_NET_FRAMEWORK_KEY_PATH); if (frameworkRegistryKey != null) { //Check for the installed versions. string[] versionNames = frameworkRegistryKey.GetSubKeyNames(); double framework = Convert.ToDouble( versionNames[versionNames.Length - 1].Remove(0, 1)); int servicePack = Convert.ToInt32( frameworkRegistryKey.OpenSubKey( versionNames[versionNames.Length - 1]).GetValue( SERVICE_PACK, 0)); //Check if the version is 3.5 Service Pack 1 or later. if ((framework < 3.5) || ((framework == 3.5) && (servicePack < 1))) { returnCode = ErrorCodesEnum.ERR_DOT_NET_FRAMEWORK; } } I also doubt that if its possible as without the right libraries how will my application run Any help or suggestions will be gr8 A: No matter what you do, if minimum required .NET version is not installed on the system you can't detect it using a program targeting .NET since it won't run at all! You'll need to use a bootstrapper with your installer to detect the framework installation and install it as necessary.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best way to calculate page count while creating a PDF in Quartz? My app creates a pdf page from app data, using Quartz and UIGraphics. Basically I define a CGRect docRect to fit on that page, then increment an NSInteger yOffset each time I draw something. If yOffset gets larger than docRect.size.height I do a UIGraphicsBeginPDFPage(). This works fine, BUT: I would like to draw a page count at the bottom, like "Page X of Y". X is obviously easy to tell, but at the moment when I create a new page, I don't know how large Y might be. I see 2 possible solutions for this: * *After drawing all pages, reiterate through all pages and add the counter. Problem: As far as I can tell, after calling UIGraphicsBeginPDFPage() there is no way to return back to previous pages. Is anyone able to disconfirm that? *Calculate all yOffset increments in advance to get the total page count. Possible, but IMHO not really an elegant solution. Has anyone advice on this problem? Thanks in advance, m A: If you don't want to pre-calculate the sizes of everything to determine in advance how many pages you'll have, one option is to render in two passes, much like you mention in your question. Render the first pass to temp.pdf and leave room for the page number counter. If working through the source content is a memory or performance burden, the second pass can go to final.pdf, using temp.pdf as an input. Loop through all the pages of temp.pdf, using CGPDFDocumentGetNumberOfPages to get your page count. Draw each page from temp.pdf via CGContextDrawPDFPage, followed by drawing the page counter. When you're done, delete temp.pdf as cleanup, and you're all set. Update: Something along the lines of this untested code, summarized from some previous work: ... CGPDFDocumentRef tempDocRef = CGPDFDocumentCreateWithURL((CFURLRef)tempPdfUrl); size_t pageCount = CGPDFDocumentGetNumberOfPages(docRef); CGContextRef finalPdfContext = CGPDFContextCreateWithURL((CFURLRef)finalPdfUrl, &defaultPageRect, nil); for (int pageNum = 1; pageNum <= pageCount; pageNum++) { CGPDFPageRef tempPageRef = CGPDFDocumentGetPage(tempDocRef, pageNum+1); CGPDFContextBeginPage(finalPdfContext, nil); CGContextDrawPDFPage(finalPdfContext, tempPageRef); // do your page number rendering here, using pageNum and pageCount ... CGPDFContextEndPage(finalPdfContext); CGPDFPageRelease(tempPageRef); } CGPDFDocumentRelease(tempDocRef); CGContextRelease(finalPdfContext); ... A: Syncfusion's Essential PDF provides a solution to this problem. It provides solution for the problem in two situation * *While generating the PDF Document. *After the generation of the PDF document You can try the online sample in the link http://mvc.syncfusion.com/sfreportingmvcsamplebrowser/MVC/10.1.0.44/Pdf_MVC/Samples/4.0/Settings/HeadersFooters -Suresh A: Better late than never - If this is still something your looking for an answer to, I think you might be interested in checking out this link - http://developer.apple.com/library/ios/#documentation/2DDrawing/Conceptual/DrawingPrintingiOS/GeneratingPDF/GeneratingPDF.html#//apple_ref/doc/uid/TP40010156-CH10-SW1 - Apple provides a (void)drawPageNumber:(NSInteger)pageNum to accomplish this task.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Zend_Db_Select Select values not in specific table I've googled my question and read through a bunch of forum posts but I've yet to find the answer I'm looking for hopefully someone here can help me out. For a project I'm building I've set up the following 3 tables; users, projects and projectUsers. I've set up a form where I can add users to projects by saving the userID and the projectID in the projectUsers table nothing special so far. The form contains a select element with userIDs that can be connected to a projectID (hidden field). This form element is filled with a query set up with Zend_Db_Select it selects all the users from the users table and adds it to the select. However I want to filter that result so it excludes all of the users already added to that specific project. Short version: I have a select element with users filled with a resultset from a (Zend_db_select) database query I want that resultset to be stripped from certain userIDs. For extra reference the table scheme below: CREATE TABLE IF NOT EXISTS `projects` ( `projectID` int(11) NOT NULL AUTO_INCREMENT, `projectName` varchar(255) NOT NULL PRIMARY KEY (`projectID`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `projectUsers` ( `projectUserID` int(11) NOT NULL AUTO_INCREMENT, `projectID` int(11) NOT NULL, `userID` int(11) NOT NULL PRIMARY KEY (`projectUserID`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; CREATE TABLE IF NOT EXISTS `users` ( `userID` int(11) NOT NULL AUTO_INCREMENT, `userFirstName` varchar(255) DEFAULT NULL, `userLastName` varchar(255) DEFAULT NULL PRIMARY KEY (`userID`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; Thanks in advance! A: This will select all users that have not been added to a project and ignore users from arrayOfUserIds select()->from('users', '*') ->joinLeft('projectUsers', 'projectUsers.projectUserID = users.userID', null) ->where('projectUsers.projectID = ?', someProjectID) ->where('projectUserID is null') ->where('users.userID not in (?)', arrayOfUserIds) ->query()->fetchAll(); A: addint to Soica Micea ans $blackList = array(1,3,5,6); //user id which you want to exclude $db->select()->from('users', '*') ->joinLeft('projectUsers', 'projectUsers.projectUserID = users.userID', null) ->where('projectUsers.projectID = ?', someProjectID) ->where('projectUserID is null') ->where('users.userID not in (?)', implode(',',$blackList)) ->query()->fetchAll();
{ "language": "en", "url": "https://stackoverflow.com/questions/7526364", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JMS Timeout or TimeToLive I am fairly new to Java EE and JMS and am looking at doing an implementation using JMS. Think of the following scenario: Scenario A user hits a servlet. A message is then put into a JMS server/Queue from this servlet. A response is then sent back to the user saying "Message Queued". Option 1 The consumer/MDB receives the message from the JMS queue and processes it. This is normal operation and pretty standard. Option 2 There is no consumer(for what ever reason) or the receiver is processing messages too slow. So what I would like is for the message in the queue to timeout. Once timed out, and email should be sent etc (email is just as an example). Reading the API spec/Java EE 6 tutorial I have found in the QueuSender class void send(Message message, int deliveryMode, int priority, long timeToLive) So by settings the timeToLive the message will be evicted from the queue. The problem is that the is no "interface/call back" to know that the message was evicted. It just disappears. Or am I mistaken? Another approach I thought of was for a thread to monitor the queue and evict messages that are "expired" and pull them from the queue. But I don't think that is possible, is it? Any light shed on this matter would greatly be appreciated. A: You have to make use of some implementation specific functionality to fulfill your requirements. The JMS specification does neither define which action is taken with a timed out message, nor does it offer you any reasonable criteria selection when polling messages from a queue. Most (if not all) JMS implementations do however offer the concept of DLQs (dead letter queues). If a message cannot be delivered to a regular consumer or times out, the JMS implementation will most likely be able to move the message to a DLQ, which is basically also a regular queue with its own listener. So, if you set up two queues, Q1 and Q2 and configure Q2 as a DLQ for Q1, you would do your normal request processing in a listener on Q1 and implement an additional listener for Q2 to do the error/timeout handling. A: Synchronous interaction over JMS might be of help to you either. Basicly on the client side you: * *send a message with a correlation id and time-to-live *receive a message (usually in the same thread) using the same correlation id and specifying timeout (time-to-live == timeout so if you treat it dead, it's really dead) On the other side, server: * *on an incoming message must fetch the correlation id *specify that correlation id for a response while sending it back to the client. Of course server must be quick enough to fit the timeout/time-to-live threshold. So on the client side you are always sure what's happend to the message that was sent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I divide the figure into the fields using SilverLight Can someone help me solve the question: How can I divide the figure into the fields, so depending on which area will be mouse click it will be carried out a specific event? private void LayoutRoot_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { //if (!isDragging) { //creating of my user control element NodePicture node = new NodePicture(); node.Width = 100; node.Height = 100; //use cursor position as the center of the figure Point point = e.GetPosition(this); node.SetValue(Canvas.TopProperty, point.Y - node.Height / 2); node.SetValue(Canvas.LeftProperty, point.X - node.Width / 2); node.MouseLeftButtonDown += controlReletionshipsLine; LayoutRoot.Children.Add(node); } } private void controlReletionshipsLine(object sender, MouseButtonEventArgs e) { //creating parant element of node ParentNode parentNode = new ParentNode(); //creating connected element of the node ConnectedNode connectedNode = new ConnectedNode(); //creating node element NodePicture node = (NodePicture)sender; //getting the relative position of the element Point point = e.GetPosition(this); A: You can either divide the object mathematically, using the mouse position "relative to the object" to decide where you clicked, or you can overlay a number of polygons, each with the colour alpha-channel set to 1% (so they can be hit-tested, but are not visible). As you simply want to see which quarter of the circle you clicked in, call GetPosition on the LeftMouseButtonDown event args, passing the control itself as the parameter. This will give you back a Point object with the position relative to the top left corner of the control. Then it is just a matter of seeing which quarter it is in: private void ControlX_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // Get the relative position of the element Point point = e.GetPosition(sender as UIElement); if (point.X > control.Width/2) { if (point.Y > control.Height/2) { // You are in the bottom right quarter } else { // You are in the top right quarter } } else { if (point.Y > control.Height/2) { // You are in the bottom left quarter } else { // You are in the top left quarter } } } In the sample code you sent me (in controlReletionshipsLine) you have: // getting the relative position of the element Point point = e.GetPosition(this); It should have been: // getting the relative position of the element Point point = e.GetPosition(sender as UIElement);
{ "language": "en", "url": "https://stackoverflow.com/questions/7526370", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to save a checkbox meta box in WordPress? I'm trying to add a checkbox into my custom meta box in WordPress and I ran into a problem with saving it - whenever I check the checkbox and update the post/page, it comes back unchecked again. Here's the code I'm using: add_meta_box( 'sl-meta-box-sidebar', // id 'Sidebar On/Off', // title 'sl_meta_box_sidebar', // callback function 'page', // type of write screen 'side', // context 'low' // priority ); function sl_meta_box_sidebar() { global $meta; sl_post_meta( $post->ID ); ?> <input type="checkbox" name="sl_meta[sidebar]" value="<?php echo htmlspecialchars ($meta['sidebar']); ?>" />Check to turn the sidebar <strong>off</strong> on this page. } This creates the checkbox in the sidebar of the "Edit Page" screen, as it should, no problem there. I'm not sure what should I enter in the value of the checkbox, with text fields it obviously returns whatever was saved as meta information... I tried just using "checked" instead cause that would be my first guess (then simply check for the value when using this meta data), but it didn't save the checkbox either. Here's the function that saves all the meta data, which I assume causes this problem: function sl_save_meta_box( $post_id, $post ) { global $post, $type; $post = get_post( $post_id ); if( !isset( $_POST[ "sl_meta" ] ) ) return; if( $post->post_type == 'revision' ) return; if( !current_user_can( 'edit_post', $post_id )) return; $meta = apply_filters( 'sl_post_meta', $_POST[ "sl_meta" ] ); foreach( $meta as $key => $meta_box ) { $key = 'meta_' . $key; $curdata = $meta_box; $olddata = get_post_meta( $post_id, $key, true ); if( $olddata == "" && $curdata != "" ) add_post_meta( $post_id, $key, $curdata ); elseif( $curdata != $olddata ) update_post_meta( $post_id, $key, $curdata, $olddata ); elseif( $curdata == "" ) delete_post_meta( $post_id, $key ); } do_action( 'sl_saved_meta', $post ); } add_action( 'save_post', 'sl_save_meta_box', 1, 2 ); It works perfectly for text fields, but the checkbox just won't save. I'm not sure if the saving function is wrong, or am I missing something about the value of the checkbox. Any help appreciated! A: I had trouble with this previously and here is how I solved it. First, creating the Checkbox. <?php function sl_meta_box_sidebar(){ global $post; $custom = get_post_custom($post->ID); $sl_meta_box_sidebar = $custom["sl-meta-box-sidebar"][0]; ?> <input type="checkbox" name="sl-meta-box-sidebar" <?php if( $sl_meta_box_sidebar == true ) { ?>checked="checked"<?php } ?> /> Check the Box. <?php } ?> Next, saving. <?php add_action('save_post', 'save_details'); function save_details($post_ID = 0) { $post_ID = (int) $post_ID; $post_type = get_post_type( $post_ID ); $post_status = get_post_status( $post_ID ); if ($post_type) { update_post_meta($post_ID, "sl-meta-box-sidebar", $_POST["sl-meta-box-sidebar"]); } return $post_ID; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7526374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How to set and destroy sessions in PHP Symfony How to set and destroy a session on the controller side? Tried in the view side, works just fine. But now need it from inside the controller. A: UPDATE: Destroy a Session in Symfony 2 as follows: $request->getSession()->invalidate(1); As invalidate leaves the current session untouched if you are not providing any parameter you have to set the lifetime on 1 (one second) Symfony 3.4 documentation: http://api.symfony.com/3.4/Symfony/Component/HttpFoundation/Session/Session.html#method_invalidate A: Did you try? /** @var $session Session */ $session = $request->getSession(); $session->remove('name'); A: Did you try $this->getAttributeHolder()->remove('foo'); if it was saved in namespace foobar $user->getAttributeHolder()->remove('foobar','','foo'); A: At last I found the solution just here around. Use the "session" service explained here: Old post
{ "language": "en", "url": "https://stackoverflow.com/questions/7526378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: With ASP.Net, how do I enable browser caching for static content and disable it for dynamic content? I have found a lot of good information with regards to getting browsers to avoid caching dynamic content (e.g. .aspx pages), however I have not been successful with getting browsers to cache my static content, specifically css, javascript and image files. I have been playing with Application_BeginRequest in Global.asax without success. Having a separate server for static content is not an option for us. I would also like to avoid having to configure IIS settings unless they can be controlled from the web.config. Could disabling caching for an aspx page influence the caching of static content that appears on it? I apologise if this question has been answered previously. As a starting point for discussion, here is the code behind for my Global.asax file. public class Global_asax : System.Web.HttpApplication { private static HashSet<string> _fileExtensionsToCache; private static HashSet<string> FileExtensionsToCache { get { if (_fileExtensionsToCache == null) { _fileExtensionsToCache = new HashSet<string>(); _fileExtensionsToCache.Add(".css"); _fileExtensionsToCache.Add(".js"); _fileExtensionsToCache.Add(".gif"); _fileExtensionsToCache.Add(".jpg"); _fileExtensionsToCache.Add(".png"); } return _fileExtensionsToCache; } } public void Application_BeginRequest(object sender, EventArgs e) { var cache = HttpContext.Current.Response.Cache; if (FileExtensionsToCache.Contains(Request.CurrentExecutionFilePathExtension)) { cache.SetExpires(DateTime.UtcNow.AddDays(1)); cache.SetValidUntilExpires(true); cache.SetCacheability(HttpCacheability.Private); } else { cache.SetExpires(DateTime.UtcNow.AddDays(-1)); cache.SetValidUntilExpires(false); cache.SetRevalidation(HttpCacheRevalidation.AllCaches); cache.SetCacheability(HttpCacheability.NoCache); cache.SetNoStore(); } } } A: The magic is made by HTTP headers - see this page. A: If you are using IIS7 & and you want to cache static content add the following in the web.config as according to the documentation: <configuration> <system.webServer> <staticContent> <clientCache httpExpires="Sun, 27 Sep 2015 00:00:00 GMT" cacheControlMode="UseExpires" /> </staticContent> </system.webServer> </configuration>
{ "language": "en", "url": "https://stackoverflow.com/questions/7526381", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Problem with understanding reference types I get from WCF service ObservableCoolection MyTypes = e.Result; ObservableCollection<MyType> MyTypes // it's a property of _myTypes <telerik:RadGridView x:Name="grdSrL" ItemsSource="{Binding MyTypes}" SelectedItem="{Binding SelectedMyType, Mode=TwoWay}" public ShowroomLog SelectedMyType { get { return _selectedMyType; } set { if (_selectedSMyType != value) { _selectedMyType = value; RaisePropertyChanged(SelectedMyTypePropertyName); } } } after I get those collection from web service, selected item is set by grid, and after that I do: SelectedMyType = null; Why after that none of item from collection isn't null? if I do: var x = new Car(); var y = x; and y = null; then x would be also null; Why there is different? A: Reference types in C# are effectively object pointers. In your example x and y are object pointers, not the objects themselves. If you change a pointer you do not change the object. x would not also become null as you state. That assumption/example is incorrect. If you called .Clear() on the collection via either variable, then both pointers to that collection will show 0 entries, but you need to explain what it is you are trying to do so I can explain with a specific example. .Clear() would not however destroy any children in the list if there are referenced elsewhere (e.g. by another list).
{ "language": "en", "url": "https://stackoverflow.com/questions/7526384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Looking for free/oss multiple window text editor (Perl + other lang) for view/edit different sections of same file at same time (windows platform) I'm looking for a free/oss multiple window code text editor (Perl + other languages) for viewing/editing different sections of same file. Can you recommend one for Windows platform? Currently I use Notepad++ which is good and has a tab for each file. But it doesn't allow opening the same file more than once in different tabs to be able to view different parts of the file. I would also like to 'tear-off' a tab to make a new window (just like in Google Chrome) so I can see different parts of the same file side by side. A: In Notepad++ (5.9.3 at least) right click on the tab of a version and select Clone to Other View. Voila! Editing the same file in two different tabs. You can also drag the tab out of the window and 'drop' it on the desktop to open another instance of Notepad++. A: emacs is a good fit. its almost-clone (but really not the same) epsilon is lighter and easier to begin with. (i just remembered that, although i have a full version of epsilon, it is not free... too bad, because it's a very good editor) A: Have a look at Sublime Text. I've switched to it From Notepad++. Works on Windows OS X and Linux. I find the Minimap very useful. You can get multiple views on a file using "New View into" from the file menu.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526388", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Bitwise subtraction Given the enum: [Flags] enum foo { a = 1, b = 2, c = 4 } then foo example = a | b; If I don't know if foo contains c, previously I have been writing the following if (example & foo.c == foo.c) example = example ^ foo.c; Is there a way to do this without checking for the existance of foo.c in example? As when it comes to additions, I can just do an OR, and if the enum value already exists in example then it doesnt matter. A: AND it with the complement of foo.c: example = example & ~foo.c A: I think you want: example &= ~foo.c; In other words, perform a bitwise "AND" mask with every bit set except the one for c. EDIT: I should add an "except" to Unconstrained Melody at some point, so you could write: example = example.Except(foo.c); Let me know if this would be of interest to you, and I'll see what I can do over the weekend...
{ "language": "en", "url": "https://stackoverflow.com/questions/7526389", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: ExtJS 4: Properly set waitMsgTarget using MVC pattern I have extjs 4.0 controller: Ext.define('KS.controller.DailyReport', { extend: 'Ext.app.Controller', views: ['report.Daily'], init: function() { this.control({ 'dailyReport button[action=send]': { click: this.sendDailyReport } }); }, sendDailyReport: function(button) { var win = button.up('window'); form = win.down('form'); form.getForm().waitMsgTarget = form.getEl(); form.getForm().waitMsg = 'Sending...'; if (form.getForm().isValid()) { // make sure the form contains valid data before submitting form.submit({ success: function(form, action) { Ext.Msg.alert('Success', action.result.msg); }, failure: function(form, action) { Ext.Msg.alert('Failed', action.result.msg); } }); } else { // display error alert if the data is invalid Ext.Msg.alert('Invalid Data', 'Correct them!') } } }); and extjs view: Ext.define('KS.view.report.Daily', { extend: 'Ext.window.Window', alias: 'widget.dailyReport', title: 'Daily report', layout: 'fit', autoShow: true, initComponent: function() { this.items = [{ waitMsgTarget: true, xtype: 'form', url: 'dailyReport.php', layout: 'fit', waitMsgTarget: true, waitMsg: 'Sending...', items: [{ margin: 10, xtype: 'datefield', name: 'reportDate', fieldLabel: 'Report for:', format: 'd.m.Y.', altFormats: 'd.m.Y|d,m,Y|m/d/Y', value: '12.12.2011', disabledDays: [0] }] }]; this.buttons = [{ text: 'Send', action: 'send' }, { text: 'Cancel', scope: this, handler: this.close }]; this.callParent(arguments); } }); As you can see I tried to set waitMsgTarget and waitMsg in both places but it is not appearing when I click Send button. What is wrong? A: You are really just misusing waitMsg in the following ways: * *waitMsg is not a config option of Ext.form.Basic OR Ext.form.Panel. The waitMsg must be set within your Ext.form.action.Submit. This is why setting it in the view will never work. *In your controller you are doing the same thing and setting the waitMsg as if it were a property of Ext.form.Basic. The fix is simple. Set waitMsg in your Ext.form.action.Submit. So, just change the line(s) within form.submit() to something like: form.submit({ waitMsg: 'Sending...', success: function(form, action) { Ext.Msg.alert('Success', action.result.msg); }, //..... your other stuff here }); and remove these lines from the controller: form.getForm().waitMsgTarget = form.getEl(); form.getForm().waitMsg = 'Sending...'; and for completeness remove these 2 line from the view (you have waitMsgTarget in there twice): waitMsgTarget: true, waitMsg: 'Sending...', NOTE: To define the waitMsgTarget to something other than the form itself you must pass in the id of the target. For example, in your view (ie form definition) you would want to change waitMsgTarget: true to: waitMsgTarget: 'myWindowID', //where myWindowID is the id of the container you want to mask For reference, see: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.form.action.Submit and http://docs.sencha.com/ext-js/4-0/#!/api/Ext.form.Basic
{ "language": "en", "url": "https://stackoverflow.com/questions/7526400", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to find out the last backup location used for a transaction log file in SQL 2005 or higher We have a product which uses a database and whenever a major release is done one of the upgrade scripts used on the database calls one of our stored procedures whose job is to drop and then recreate the fulltext index thus ensure any changes (i.e. new columns that are indexed) in the new release get installed. The problem is that if our client has set up the database to be full recovery mode then this will fail at the point at which it tries to recreate the fulltext index. To ensure the upgrade instructions are as simple as possible I don't want the IT guy doing it to have to do anything other than run the set of scripts according to there filenames, (i.e. run 001 - xxx.sql, then run 002 xxx.sql etc...). So the idea I thought to try was for the SP that drops/recreates to do the backup of the transaction log if the database is set to full recovery mode for them by backing up to the same location as the last transaction log backup was done. The problem is how do you find out the last location? I've searched and found scripts that indicate the use of sys.sysdatabases and msdb..backupset but those tables don't seem to have the information I need. Any ideas? Is it even possible? A: Should be in msdb..backupmediafamily, physical_device_name column
{ "language": "en", "url": "https://stackoverflow.com/questions/7526404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the Shift + End to select to the end of line? I'm using MonoDevelop 2.6 on MacOS X Snow Leopard. Is there a way to customize the Shift + END (and Shift + Home) key combinations to select only to the end (or beginning) of the current line, not to the end of the document? I suppose there is an option somwhere in MonoDevelop for customizing the cursor position after an End or Home key (choosing between EoL or EoF), but I cannot find it in the keyboard settings. A: This is how the Home and End keys work in MacOS. To expand the selection to the line start/end on MacOS, you would use Shift-Command-Left/Right. Most Mac apps (including MD) also respect the emacs commands Shift-Control-a/e. If you want a Windows-like behaviour, look for the commands "Expand selection to line start" and "Expand selection to line end" in MonoDevelop's Key Bindings preferences and remap them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I format C# string output to contain newlines? strEmail = "Hi All," + "<br>" + "The User " + lstDataSender[0].ReturnDataset.Tables[0].Rows[0][1].ToString() + " has been created on " + DateTime.Now.ToShortDateString() + "." I am writing C# code to generate an email whenever a new user has been created. I need the body of the mail in a mail format like hi, The user "xxx" has been created on "todaysdate". Thanks, yyyy so I need to insert linebreaks and bold for some characters. How might I achieve this? A: If this is a plain text email (which it looks like it is), use \r\n for new lines. strEmail = string.Concat("Hi All,\r\n\r\nThe User", lstDataSender[0].ReturnDataset.Tables[0].Rows[0][1].ToString(), "has been created on ", DateTime.Now.ToShortDateString(), ".\r\n\r\nThanks, yyyy"); Strickly speaking this should be Environment.NewLine to support different platforms, but I doubt this is a concern. A: Set yourMessage.IsBodyHtml = true Msdn-Reference can be found here. A: In order to form, you can use like below: Response.Write("Hi,<br/><br/>The user.......");
{ "language": "en", "url": "https://stackoverflow.com/questions/7526410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to code Jquery or Javascript in global.asax file Hi all i am having a requirement i.e i will have image icons on my form where i have to show tool tips when i hover the mouse on that icon. Assume that i have my controls as follows on a form Bank Name Textbox Helpicon(when i mouse over on this i would like to display the tooltip from global.asax file) Like that i have another form with same controls there also when i mouse over on the image icon i would like to display the same help file as tooltip for the help file. I have done this with Jquery but my manager is asking to show the help text from the global.asax file.. so is it possible to show the help text when i mouse over the icon from global.asax file. Can any one provide sample code.. A: global.asax is not meat for this as it is pure server side code. I assume you can use a master page that will always include the script you have done to display the tooltip. You can just need to mark the help icon with a class and perhaps display the value that is written in the alt property (it makes sense since when javascript is disabled/not available people will still be able to view the help text) A: Use a master page and put your jquery and other javascript there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: JQUERY On Screen Keyboard When I search touch screen keyboard, I found this link. JQUERY On Screen Keyboard http://www.jquery4u.com/plugins/jquery-screen-keyboard-plugin/ I like this plugin so much. But as my client requirement is a little more complex, I need to modify this plugin. What I want to modify is keyboard position. Now current keyboard position is left:0 top:0 but I want to change Applie Ipad Keyboard style layout.(eg. keyboard position is round about left:0 top:50%) So, If you know how to do It, please share with me. A: I had the same problem when I started using the on screen keyboard. It turned out that I needed to update to the latest version of JQuery-UI and that solved my positioning problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7526421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to start rails server? I am developing rails 2.3.2 application. When I type the command "rails script/server" I got the following output instead of server starting why? rails script/server Usage: rails new APP_PATH [options] Options: -J, [--skip-javascript] # Skip JavaScript files [--dev] # Setup the application with Gemfile pointing to your Rails checkout [--edge] # Setup the application with Gemfile pointing to Rails repository -G, [--skip-git] # Skip Git ignores and keeps -m, [--template=TEMPLATE] # Path to an application template (can be a filesystem path or URL) -b, [--builder=BUILDER] # Path to a application builder (can be a filesystem path or URL) [--old-style-hash] # Force using old style hash (:foo => 'bar') on Ruby >= 1.9 [--skip-gemfile] # Don't create a Gemfile -d, [--database=DATABASE] # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc) # Default: sqlite3 -O, [--skip-active-record] # Skip Active Record files [--skip-bundle] # Don't run bundle install -T, [--skip-test-unit] # Skip Test::Unit files -S, [--skip-sprockets] # Skip Sprockets files -r, [--ruby=PATH] # Path to the Ruby binary of your choice # Default: /home/xichen/.rvm/rubies/ruby-1.8.7-p352/bin/ruby -j, [--javascript=JAVASCRIPT] # Preconfigure for selected JavaScript library # Default: jquery Runtime options: -q, [--quiet] # Supress status output -s, [--skip] # Skip files that already exist -f, [--force] # Overwrite files that already exist -p, [--pretend] # Run but do not make any changes Rails options: -h, [--help] # Show this help message and quit -v, [--version] # Show Rails version number and quit Description: The 'rails new' command creates a new Rails application with a default directory structure and configuration at the path you specify. Example: rails new ~/Code/Ruby/weblog This generates a skeletal Rails installation in ~/Code/Ruby/weblog. See the README in the newly created application to get going. When I type linux command "ls" I got the following directories and files showing: app Capfile config criptq db doc features Gemfile Gemfile.lock generate lib log nbproject public Rakefile README script spec test tmp vendor my Gemfile is: source "http://rubygems.org" gem "rails", "2.3.2" gem "mysql", "2.8.1" gem "fastercsv" gem "will_paginate", "2.3.16" gem "chronic", "0.6.4" gem "whenever", "0.4.1" gem "searchlogic", "2.4.28" group :development do gem "mongrel", "1.1.5" end group :test do gem "rspec", "1.3.2" gem "rspec-rails", "1.3.4" gem "factory_girl", "1.3.3" end A: For rails 2.3.2 you can start server by: ruby script/server A: In rails 2.3.x application you can start your server by following command: ruby script/server In rails 3.x, you need to go for: rails s A: Make sure you're in the right directory when you start the server sites>yoursite> rails s A: On rails 3, the simpliest way is rails s. In rails 2, you can use ./script/server start. You can also use another servers, like thin or unicorn, that also provide more performance. I use unicorn, you can easily start it with unicorn_rails. BTW, if you use another things, like a worker (sidekiq, resque, etc), I strongly recommend you to use foreman, so you can start all your jobs in one terminal windows with one command and get a unified log. A: Goto root directory of your rails project * *In rails 2.x run > ruby script/server *In rails 3.x use > rails s A: For rails 4.1.4 you can start server: $ bin/rails server A: In a Rails 2.3 app it is just ./script/server start A: For rails 3.2.3 and latest version of rails you can start server by: First install all gem with command: bundle install or bundle. Then Configure your database to the database.yml. Create new database: rake db:create Then start rails server. rails server orrails s A: For newest Rails versions If you have trouble with rails s, sometimes terminal fails. And you should try to use: ./bin/rails To access command. A: For the latest version of Rails (Rails 5.1.4 released September 7, 2017), you need to start Rails server like below: hello_world_rails_project$ ./bin/rails server => Booting Puma => Rails 5.1.4 application starting in development => Run `rails server -h` for more startup options Puma starting in single mode... * Version 3.10.0 (ruby 2.4.2-p198), codename: Russell's Teapot * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp://0.0.0.0:3000 More help information: hello_world_rails_project$ ./bin/rails --help The most common rails commands are: generate Generate new code (short-cut alias: "g") console Start the Rails console (short-cut alias: "c") server Start the Rails server (short-cut alias: "s") test Run tests except system tests (short-cut alias: "t") test:system Run system tests dbconsole Start a console for the database specified in config/database.yml (short-cut alias: "db") new Create a new Rails application. "rails new my_app" creates a new application called MyApp in "./my_app" A: If you are in rails2 version then to start the server you have do, script/server or ./script/server But if you are in rails3 or above version then to start the server you have do, rails server or rails s A: in rails 2.3.X,just type following command to start rails server on linux script/server and for more help read "README" file which is already created in rails project folder A: I also faced the same issue, but my fault was that I was running "rails s" outside of my application directory. After opening the cmd, just go inside your application and run the commands from their, it worked for me. A: You have to cd to your master directory and then rails s command will work without problems. But do not forget bundle-install command when you didn't do it before. A: run with nohup to run process in the background permanently if ssh shell is closed/logged out nohup ./script/server start > afile.out 2> afile.err < /dev/null & A: Rails version < 2 From project root run: ./script/server A: I believe this is what happens if "rails new [project]" has not actually executed correctly. If you are doing this on windows and "rails server" just returns the help screen, you may need to restart your command prompt window and likely repeat your setup instructions. This is more likely true if this is your first time setting up the environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526424", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: facebook iOS SDK authorization without redirect to safari I need to authorize the access to facebook within the app, because I need to store the cookies where they can be used by the app later. So I want that the autorization takes place in a webview without the need for redirecting to safari. After some research I saw some answers for this problem, which consist of changing the following line: [self authorizeWithFBAppAuth:YES safariAuth:YES]; to [self authorizeWithFBAppAuth:NO safariAuth:NO]; However, this is not working for me. It does not redirect to safari anymore, but does not open the webview either. Am I missing something? The connection with facebook works fine when redirecting to safari, so the SDK should be well installed. Thanks in advance! EDIT With the help of breakpoints in the FBDialog.m code, I can see that the method webViewDidFinishLoad:is being called, so I assume it is working as expected. However, I also add the line NSLog(@"view %@",self); to the end of the init method in the FBDialog.m, which produces the text in the console: view <FBLoginDialog: 0x4e316f0; frame = (0 0; 0 0); autoresize = W+H; layer = <CALayer: 0x4e321c0>> As you can see the width and height of the frame is 0, 0. Could this be the reason for the UIWebView never show up? A little help would be greatly appreciated. A: I found the problem. I was calling the authorize method of the facebook object before the makeKeyAndVisiblemethod of the window.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Fluid Simulation using Smooth Particle Hydrodynamics Actually, I'm developing an SPH simulator using C++ and openGL. There are several problem I've encountered right now, I make initiation fluid particles on one side of the box (I make box as boundary volume), shape them like box, and give them initial velocity equal zero. Then I start the main loop, viola, the fluids start moving, and there's a weird phenomena here. The fluids start spreading over all direction. Please look at the picture : http://i278.photobucket.com/albums/kk86/anggytrisnawan/Screenshot-UntitledWindow-2.png That picture taken after several seconds from the beginning of simulation. It's seems weird for me. Here is the parameter I used for the simulation: #define H 0.040 // Smoothing Length #define Rho0 1000 // (kg/m^3) water particle rest density #define Mass 0.012 // (kg) #define DT 0.001 // time step #define TotalParticles 5000 // total number of particle Note : currently I don't calculate surface tension force yet. SOLVED : My fault here..they overlapping each other at the beginning..so pressure force make them spread.. A: From the image you provided it seems that the simulation started with all the particles in one corner. Since the particles presumably must have some repulsive potential in order to not overlap each other, once the simulation starts this repulsion will force the particles apart. Then again, you haven't shown any code, so the above is just a qualified guess. A: What are the boundary conditions' values, i.e. at which numerical coordinates are the box limits? I assume, that your simulation runs off into a certain direction due to systematic rounding errors. If I look at the picture I get the impression I'm looking down along -Z direction and the lower left corner of the box is at (0, 0, 0). If that's the case, then your particle simulation is not conservative, i.e. tends to push the particles towards to numerical 0, like if there was a force field.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run several classes in IntelliJ IDEA with same ordering? Is there a way of telling IntelliJ IDEA Community Edition to run several classes in the same ordering one after another? Every class implements its own public static void main(String[]) method. I would like to avoid jUnit since it doesn't guarantee the same ordering of execution, though its nice it can execute each test in its own JVM. A: You can write your own maven mini-project with this plugin attached: http://mojo.codehaus.org/exec-maven-plugin/ And then you can in IntelliJ add run configuration on this maven project with your goal. I think this will be looking nice. A: Do you mean like this? // write a main which calls A.main(args); B.main(args); C.main(args); If they have to run concurrently, you can add them as tasks to a ExecutorService. You can trap exceptions so that if one dies, they all shut down.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting rid of double green lines in blog posts I have a blog on Blogger, and sometimes, I notice that double green lines are automatically added below certain words, which will display an ad if you hover over it (see picture below). Is there a way I could permanently make these lines not show up (e.g. by adding code to the Blogger template)? I just noticed them being added to some of my posts recently, and I want them to go away forever. A: This is most probably a browser plugin/gadget that is inserting these links, not Blogger. Disable, or better, uninstall the TextEnhance plugin/gadget . See: http://wafflesatnoon.com/2011/10/05/seeing-unwanted-text-enhance-ads/ A: I was having the same text-enhance issue. It was installed on Chrome under the extension Premium-play codec c. Deleting the ext got rid of the adware. A: To de-install this trojan horse, follow these steps: De-install the following program(s) (go to the 'Add/Remove' section in the Control Panel): --Pando media enhancer --I Want This! 2) Apps/extensions for Chrome *To remove extensions, type chrome://extensions into the omnibox/address bar *To remove apps, go to the New Tab page > Apps panel > right click app you want to remove --Premiumplay Codec-C (extension) --Yontoo Layers (extension?) --Rewards Gaming (app) For Internet Explorer, disable the same extension(s). I hope this helped banish this software from the internet. Best regards and good luck! A: When you get a pop-up, click on the name of the company that conducts the ads and you will go to their corporate site that has a disable link and it will effectively disable these links in any page that the company conducts business. Close and reopen browser and you will no longer see double line ads from that company anywhere on the internet. If you clear your cookies you will have to repeat this step, However, this is an easy way to stop the ads without corrupting your OS or browser. If you have to hack code and you don't know what you are doing you can damage a program or your computer beyond repair...If you know what you are doing then go forth and hack away.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can HTML5 access private data like SMSes or contacts on iPhone/iOS? I'm not familiar with phone OSes. Can html5 do this on iPhone ? Thank you. A: simple answer: NO SMSs access isn't even possible for native apps. Contact access can be done via "low level" C-APIs. A: No cant access the SMS, you can't even access SMS from the SDK or mail for that matter. Not sure about contact, you hace acces to the contact via the API, but not sure if HTML5 has any contacts methods.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I defind that object set was already created? I'm working with entity framework and mysql. We created a class public class DataBaseContext : ObjectContext, IDbContext There is a method public IEnumerable<T> Find<T>(Func<T, bool> whereClause) where T : class { return CreateObjectSet<T>().Where(whereClause); } Is there a way not to create ObjectSet every time when I call the method? Can I check that it is already exists? A: Whooooo. That is so bad method. You are passing Func<>, not Expression<Func<>>. It means that every time you execute your method EF will pull all records from database table mapped to T and execute your filtering in memory of your application - creating object set is the last thing you should be afraid of. Anyway creating object set should not be expensive operation and if you don't want to create it every time you need to implement some "local caching" inside your object context instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526438", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I want to implement a scheme interpreter for studying SICP I'm reading the book Structure and Interpretation of Computer Programs, and I'd like to code a scheme interpreter gradually. Do you knows the implementation of the scheme most easy to read (and short)? I will make a JavaScript in C. A: SICP itself has several sections detailing how to build a meta-circular interpreter, but I would suggest that you take a look at the following two books for better resources on Scheme interpreters: Programming Languages: Application and Interpretation and Essentials of Programming Languages. They're both easy to read and gradually guide you through building interpreters. A: I would recommend the blog series Scheme from scratch which incrementally builds up a scheme interpreter in C. A: Christian Queinnec's book Lisp In Small Pieces is superb. More modern that EoPL. Covers both Lisp and Scheme, and goes into detail about the gory low-level stuff that most books omit. A: I would recommend reading Kent Dybvig's dissertation "Three Implementation Models for Scheme". Not the whole dissertation, but the first part (up to chapter 3) where he discusses the Heap-Based Model is very suitable for a naive implementation of Scheme. Another great resource (if I understood it correctly and you want to implement it in C) is Nils Holm's "Scheme 9 from Empty Space". This link is to Nils's page, and there's a link at the bottom to the old, public domain, edition of the book and to the newer, easier to read, commercially available edition. Read both and loved 'em. A: I can give you an overview on how my interpreter works, maybe it can give you an idea of the general thing. Although the answer is pretty late, I hope this can help someone else, who has come to this thread and wants a general idea. * *For each line of scheme entered , a Command object is created. If the command is partial then its nest level is stored(number of remaining right brackets to complete the expression). If the command is complete an Expression Object is created and the evaluators are fired on this object. *There are 4 types of evaluator classes defined , each derived from the base class Evaluator a) Define_Evaluator :for define statements b) Funcall_Evaluator :for processing other user defined functions c) Read_Evaluator :for reading an expression and converting it to a scheme object d) Print_Evaluator :prints the object depending on the type of the object. e) Eval_Evaluator :does the actual processing of the expression. 3.-> First each expression is read using the Read Evaluator which will create a scheme object out of the expression. Nested expressions are calculated recursively until the expression is complete. ->Next, the Eval_Evaluator is fired which processes the Scheme Expression Object formed in the first step. this happens as so a) if the expression to be evaluated is a symbol. Return its value. Therefore the variable blk will return the object for that block. b) if the expression to be evaluated is a list. Print the list. c) if the expression to be evaluated is a function. Look for the definition of the function which will return the evaluation using the Funcall_Evaluator. ->Lastly the print evaluator is fired to print the outcome , this print will depend on what type the output expression is. Disclaimer: This is how my interpreter works , doesnt have to be that way. A: I've been on a similar mission but several years later, recommendations: * *Peter Michaux's scheme from scratch: http://michaux.ca/articles/scheme-from-scratch-introduction, and his github repo: https://github.com/petermichaux/bootstrap-scheme/blob/v0.21/scheme.c. Sadly his royal scheme effort seems to have stalled. There were promises of a VM, which with his clarity of explanations would have been great. *Peter Norvigs lis.py: http://norvig.com/lispy.html, although written in python, is very understandable and exploits all the advantages of using a dynamic, weakly typed language to create another. He has a follow up article that adds more advanced features. *Anthony C. Hay used lis.py as an inspiration to create an implementation in C++: http://howtowriteaprogram.blogspot.co.uk/2010/11/lisp-interpreter-in-90-lines-of-c.html *A more complete implementation is chibi scheme: http://synthcode.com/scheme/chibi/ which does include a VM, but the code base is still not too large to comprehend. I'm still searching for good blog posts on creating a lisp/scheme VM, which could be coupled with JIT (important for any competitive JS implementation :). A: Apart from Queinnec's book, which probably is the most comprehensive one in scheme to C conversion, you can read also literature from the old platform library.readscheme.org.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Fast access to a (sorted) TList My project (running on Delphi 6!) requires a list of memory allocations (TMemoryAllocation) which I store within an object that also holds the information about the size of the allocation (FSize) and if the allocation is in use or free (FUsed). I use this basically as a GarbageCollector and a way to keep my application of allocating/deallocating memory all the time (and there are plenty allocations/deallocations needed). Whenever my project needs an allocation it looks up the list to find a free allocation that fits the required size. To achieve that I use a simple for loop: for I := 0 to FAllocationList.Count - 1 do begin if MemoryAllocation.FUsed and (MemoryAllocation.FSize = Size) then ... The longer my application runs this list grows to several thousand items and it slows down considerably as I run it up very frequently (several times per second). I am trying to find a way to accelerate this solution. I thought about sorting the TList by size of allocation. If I do that I should use some intelligent way of accessing the list for the particular size I need at every call. Is there some easy way to do this? Another way I was thinking about was to have two TLists. One for the Unused and one of the Used allocations. That would mean though that I would have to Extract TList.Items from one list and add to the other all the time. And I would still need to use a for-loop to go through the (now) smaller list. Would this be the right way? Other suggestions are VERY welcome as well! A: You have several possibilities: * *Of course, use a proven Memory Manager as FastMM4 or some others dedicated to better scale for multi-threaded applications; *Reinvent the wheel. If your application is very sensitive to memory allocation, perhaps some feedback about reinventing the wheel: * *Leverage your blocks size e.g. per 16 bytes multiples, then maintain one list per block size - so you can quickly reach the good block "family", and won't have to store each individual block size in memory (if it's own in the 32 bytes list, it is a 32 bytes blocks); *If you need reallocation, try to guess the best increasing factor to reduce memory copy; *Sort your blocks per size, then use binary search, which will be much faster than a plain for i := 0 to Count-1 loop; *Maintain a block of deleted items in the list, in which to lookup when you need a new item (so you won't have to delete the item, just mark it as free - this will speed up a lot if the list is huge); *Instead of using a list (which will have some speed issues when deleting or inserting sorted items with a huge number of items) use a linked list, for both items and freed items. It's definitively not so simple, so you may want to look at some existing code before, or just rely on existing libraries. I think you don't have to code this memory allocation in your application, unless FastMM4 is not fast enough for you, which I'll doubt very much, because this is a great piece of code!
{ "language": "en", "url": "https://stackoverflow.com/questions/7526443", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: what is the fastest way to generate random ip numbers in c? I need fast way to generate ip numbers that are valid (reserved ips are valid too). For now i am using this: unsigned char *p_ip; unsigned long ul_dst; p_ip = (unsigned char*) &ul_dst; for(int i=0;i<sizeof(unsigned long);i++) *p_ip++ = rand()%255; ip.sin_addr.s_addr = ul_dst; But sometimes it generate non-valid numbers, but this code can generate about 10k of valid ips in a second. Can anyone contribute? Thank you A: calling rand() is probably the slowest part of your code, if you use the implementation of a random function found at http://en.wikipedia.org/wiki/Multiply-with-carry This is an ultra fast C function for generating random numbers. storing sizeof(unsigned long) in a registered variable i.e.: register int size = sizeof(unsigned long) should also help slightly. Since you are using 4 chars = 4 x 8 byte memory, you can instead use a 32bit integer which will only require one memory address. combining the bitshifting, new random method, registered variables, should reduce running times by quite a bit. #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <time.h> uint32_t ul_dst; init_rand(time(NULL)); uint32_t random_num = rand_cmwc(); ul_dst = (random_num >> 24 & 0xFF) << 24 | (random_num >> 16 & 0xFF) << 16 | (random_num >> 8 & 0xFF) << 8 | (random_num & 0xFF); printf("%u\n",ul_dst); return 0; Above this code I have the exact copy of the random function from wikipedia. Hopefully this will run much faster. We know the size of a 32bit int is 4*8 so no need for the sizeof anymore, and instead of %255 I replaced it with a 255 bit mask A: Currently, your code writes four chars to memory. You can optimize this by writing one int32 to memory. A: Roll your own random generator. For this purpose anything with a period of (1<<32) is valid, so you could construct a lineair congruential thing. (you would not need to construct from 4 separate characters, too) Also, your *p_ip is uninitialised. you probably want a p_ip = (unsigned char *) &ul_dst; somewhere. A: Building over @Serdalis idea of using init_rand(), maybe you can try something I had come across called Knuth Shuffle which will help you generate Random Numbers with a uniform Distribution. The code will look like this I guess now but the below example uses rand(): #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define TOTAL_VAL_COUNT 254 int byteval_array[TOTAL_VAL_COUNT] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254 }; unsigned char denominator = TOTAL_VAL_COUNT+1; unsigned char generate_byte_val(); unsigned char generate_byte_val() { unsigned char inx, random_val; if (denominator == 1) denominator = TOTAL_VAL_COUNT+1; inx = rand() % denominator; random_val = byteval_array[inx]; byteval_array[inx] = byteval_array[--denominator]; byteval_array[denominator] = random_val; return random_val; } int main(int argc, char **argv) { int i; struct in_addr ip; for (i = 1; i < 255; ++i) { ip.s_addr = (generate_byte_val() | (generate_byte_val() << 8) | (generate_byte_val() << 16) | (generate_byte_val() << 24)); printf ("IP = %s\n", inet_ntoa(ip)); } } HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7526449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to export a MySQL database (data folder) from an hard disk? I know, it is really sad trying to export a database just by copying the data folder! But I have a hard disk with an important database inside and I don't know how to export this database onto my actual system (winxp - mysql 5.0.37). So, i've copied old_harddisk/program/mysql/data/coge2010 to mypc/programs/mysql/data/coge2010 Result: * *I see cogemilla (4) on my phpMyAdmin databases summary (it's correct!!! my 4 tables!) *If I click the database, I see just 1 table (oh no!) *On the mysql error log file I find messages like this one: "...[ERROR] Cannot find table coge2010/soci from the internal data dictionary of InnoDB though the .frm file for the table exists. Maybe you have deleted and recreated InnoDB data files but have forgotten to delete the corresponding .frm files of InnoDB tables, or you have moved .frm files to another database? See http://dev.mysql.com/doc/refman/5.0/en/innodb-troubleshooting.html how you can resolve the problem." Any ideas? A: You should create a dump and import it on the new server. In Command Prompt type the following to create the dumpfile: mysqldump -h host -u user -p databaseName > dumpFile.sql To import the database : mysql -h host -u user -p databaseName < dumpFile.sql A: This post may help you. Another post which may help you. A mysql table is defined by 3 files (FRM/MYD/MYI). In your case the FRM file is missing into the database folder. If you can run the mysql server of the old hard disk it is easier to do a dump of your database. The following link shows you how to do this A: You can only copy InnoDB tables if: 1. Your database is stopped. 2. You copy all InnoDB files (ibdata* ib_logfile* /*.ibd You could use dump/restore to copy a single table. You could user 'ALTER TABLE sometable ENGINE=MyISAM' to convert it to MyISAM and then copy the MYI,MYD and FRM. Percona XtraBackup can do single table restores if you're using Percona Server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Large print/echo break http response I am having a problem with an echo/print that returns a large amount of data. The response is broken and is as follows: * *end of data *http response header printed in body *start of data I am running the following script to my browser to replicate the problem: <?php // Make a large array of strings for($i=0;$i<10000;$i++) { $arr[] = "testing this string becuase it is must longer than all the rest to see if we can replicate the problem. testing this string becuase it is must longer than all the rest to see if we can replicate the problem. testing this string becuase it is must longer than all the rest to see if we can replicate the problem."; } // Create one large string from array $var = implode("-",$arr); // Set HTTP headers to ensure we are not 'chunking' response header('Content-Length: '.strlen($var)); header('Content-type: text/html'); // Print response echo $var; ?> What is happening here? Can someone else try this? A: You might have automatic output buffering activated on your server. If the buffer overflows, it just starts pooping out the rest of the data instead. Note that something like gzip compression also implicitly buffers the output. If it's the case, an ob_end_flush() call after the headers should solve it. A: Browsers often limits the characters you're allowed to pass through a get variable. To work around this, you could base 64 encode the string, and then decode it, once you recievede the respone. I think there's javascript base 64 encode libraries available. Like this one: http://www.webtoolkit.info/javascript-base64.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7526459", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: android.database.CursorIndexOutOfBoundsException I am running the software but when i scroll with the listview, its showing ok, but after a while i get this error message: I am trying to display a cursor to a listview. My Adapter class: private class DBAdapter extends SimpleCursorAdapter { private LayoutInflater mInflater; private Cursor c; private Context context; My Constructor public DBAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); this.c = c; this.context = context; mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); } getView Method @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.match_item, null); holder.tvHome = (TextView)convertView.findViewById(R.id.ll_home); convertView.setTag(holder); } else { holder = (ViewHolder)convertView.getTag(); } holder.tvHome.setText(c.getString(3)+"("+c.getString(6)+")"); c.moveToNext(); return convertView; } } Simple View Holder public static class ViewHolder { public TextView tvHome; } } Adapter init Cursor cur = dh.getAll(); startManagingCursor(cur); String[] from = new String[] { "home" }; int[] to = new int[] { R.id.ll_home}; // Now create an array adapter and set it to display using our row DBAdapter matches = new DBAdapter(this,R.layout.match_item, cur, from, to); setListAdapter(matches); Can anyone help me to solve this problem?I've searched everywhere but i could not find any solution Best regards, Nicos A: holder.tvHome.setText(c.getString(3)+"("+c.getString(6)+")"); if(position<=c.getCount()) c.moveToNext(); return convertView; A: Since you have only single element you have put index as 0. You try this one c.getString(0). I think it will work A: you're supposed to override newView and bindView when implementing your own cursor adapter, not getView. i found this: Trying to override getView in a SimpleCursorAdapter gives NullPointerExceptio
{ "language": "en", "url": "https://stackoverflow.com/questions/7526464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: suhosin encryption bug when reloading apache2 configuration I have a Apache2 server installed running with php and suhosin. The php session are handled with Zend_Session and stored in database. Suhosin is configured to encrypt session data before saving it to the database. While apache2 is running after a /etc/init.d/apache2 start everything work fine until I ask apache2 to reload using /etc/init.d/apache2 reload It seems that suhosin is not loaded correctly, and does not handle session data encryption anymore. eg: -before reload mz0NTT8tcqaa4BIuBniVnVCMNjiwllLIds-cPt3KcMvyOHTktQmuYjgfAM3UMbVkVbsKnioUxPwjqaDIORSRlDnL5Q-W6iS8AoilOPwDUuUdtYjkbKskJpv62R9q -after reload language|a:2:{s:10:"locale";s:5:"en_EN";s:12:"language";s:2:"en";} if apache is restarted sessions data are crypted again. Here are the versions og the OS, apache2, php and suhosin I have: squeeze/sid Server version: Apache/2.2.17 (Ubuntu) Server built: Feb 22 2011 18:33:02 PHP 5.3.5-1ubuntu7.2 with Suhosin-Patch (cli) (built: May 2 2011 23:18:30) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans with Suhosin v0.9.32.1, Copyright (c) 2007-2010, by SektionEins GmbH Does anyone have faced the same issue? Any help on this would be very appreciated. Thank you A: I Finally found the solution. My apache was configured with suhosin and Xdebug. It seems that desactivating Xdebug allow suhosin to reload correctly while reloading apache.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What does the dot mean in R – personal preference, naming convention or more? I am (probably) NOT referring to the "all other variables" meaning like var1~. here. I was pointed to plyr once again and looked into mlplyand wondered why parameters are defined with leading dot like this: function (.data, .fun = NULL, ..., .expand = TRUE, .progress = "none", .parallel = FALSE) { if (is.matrix(.data) & !is.list(.data)) .data <- .matrix_to_df(.data) f <- splat(.fun) alply(.data = .data, .margins = 1, .fun = f, ..., .expand = .expand, .progress = .progress, .parallel = .parallel) } <environment: namespace:plyr> What's the use of that? Is it just personal preference, naming convention or more? Often R is so functional that I miss a trick that's long been done before. A: At the start of a name it works like the UNIX filename convention to keep objects hidden by default. ls() character(0) .a <- 1 ls() character(0) ls(all.names = TRUE) [1] ".a" It can be just a token with no special meaning, it's not doing anything more than any other allowed token. my.var <- 1 my_var <- 1 myVar <- 1 It's used for S3 method dispatch. So, if I define simple class "myClass" and create objects with that class attribute, then generic functions such as print() will automatically dispatch to my specific print method. myvar <- 1 print(myvar) class(myvar) <- c("myClass", class(myvar)) print.myClass <- function(x, ...) { print(paste("a special message for myClass objects, this one has length", length(x))) return(invisible(NULL)) } print(myvar) There is an ambiguity in the syntax for S3, since you cannot tell from a function's name whether it is an S3 method or just a dot in the name. But, it's a very simple mechanism that is very powerful. There's a lot more to each of these three aspects, and you should not take my examples as good practice, but they are the basic differences. A: A dot in function name can mean any of the following: * *nothing at all *a separator between method and class in S3 methods *to hide the function name Possible meanings 1. Nothing at all The dot in data.frame doesn't separate data from frame, other than visually. 2. Separation of methods and classes in S3 methods plot is one example of a generic S3 method. Thus plot.lm and plot.glm are the underlying function definitions that are used when calling plot(lm(...)) or plot(glm(...)) 3. To hide internal functions When writing packages, it is sometimes useful to use leading dots in function names because these functions are somewhat hidden from general view. Functions that are meant to be purely internal to a package sometimes use this. In this context, "somewhat hidden" simply means that the variable (or function) won't normally show up when you list object with ls(). To force ls to show these variables, use ls(all.names=TRUE). By using a dot as first letter of a variable, you change the scope of the variable itself. For example: x <- 3 .x <- 4 ls() [1] "x" ls(all.names=TRUE) [1] ".x" "x" x [1] 3 .x [1] 4 4. Other possible reasons In Hadley's plyr package, he uses the convention to use leading dots in function names. This as a mechanism to try and ensure that when resolving variable names, the values resolve to the user variables rather than internal function variables. Complications This mishmash of different uses can lead to very confusing situations, because these different uses can all get mixed up in the same function name. For example, to convert a data.frame to a list you use as.list(..) as.list(iris) In this case as.list is a S3 generic method, and you are passing a data.frame to it. Thus the S3 function is called as.list.data.frame: > as.list.data.frame function (x, ...) { x <- unclass(x) attr(x, "row.names") <- NULL x } <environment: namespace:base> And for something truly spectacular, load the data.table package and look at the function as.data.table.data.frame: > library(data.table) > methods(as.data.table) [1] as.data.table.data.frame* as.data.table.data.table* as.data.table.matrix* Non-visible functions are asterisked > data.table:::as.data.table.data.frame function (x, keep.rownames = FALSE) { if (keep.rownames) return(data.table(rn = rownames(x), x, keep.rownames = FALSE)) attr(x, "row.names") = .set_row_names(nrow(x)) class(x) = c("data.table", "data.frame") x } <environment: namespace:data.table> A: If a user defines a function .doSomething and is lazy to specify all the roxygen documentation for parameters, it will not generate errors for compiling the package
{ "language": "en", "url": "https://stackoverflow.com/questions/7526467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "91" }
Q: WordPress posts in phpBB topics I like to know if there is a way to create topics on specific Forums when I save posts on WordPress side. Is there any tutorial available? More specific. I like to allow my plugin users to combine a WordPress category to a phpBB forum, and when I create a new post in the WordPress, automaticly to create a topic in the phpBB side in the corresponding forum. ie: Post that are posted on Tech News category, automaticly to be posted on Technology news forum on the phpBB side. Any solution for that ? A: BBPress is supposed to do exactly this. http://bbpress.org/ If you want to develop your own Wordpress plugin, take a look at phpBB's submit_post function: http://wiki.phpbb.com/Using_phpBB3%27s_Basic_Functions#1.4.7._Inserting_Posts_and_Private_Mess http://wiki.phpbb.com/Function.submit_post and Wordpress' publish_post function, located in wp-includes/post.php http://codex.wordpress.org/Function_Reference/wp_publish_post A: You don't need to switch to bbPress, you can use WP-United. It only allows you to select one forum to cross-post to at the moment, but it would be an easy change to cross-post based on category: I'm considering adding that for v0.9.2
{ "language": "en", "url": "https://stackoverflow.com/questions/7526474", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting top and left of a CSS scaled element's normal state with jQuery? I'm scaling an element on hover with transform: scale(1.2); Now I need to get the top and left position on hover, but it gives me the top and left of the scaled position.. Makes sense, but I'd like the normal state top and left? Is there an easy way to get this? A: Depending on transform-origin and the alignment of your element, you can calculate the additional offset by multiplying the width and height by the multiplier of scaleX and scaleY. Example: var element = $("#myDiv"); var prefixes = ["-moz-", "-webkit-", "-o-", "-ms-", ""]; var transX = 1, transY = 1, originX = .5, originY = .5, match; for(var i=0; i<prefixes.length; i++){ var prefix = prefixes[i]; var transform = element.css(prefix+"transform"); if(!transform) continue; match = transform.match(/scale\((\d+),(\d+)\)/i); if(match){ transX = match[1]; transY = match[2]; } else if(match = transform.match(/scale\((\d+)\)/i)){ transX = transY = match[1]; } else if(match = transform.match(/scale[XY]\(\d+\)/i)){ transX = transform.match(/scaleX\((\d+)\)/i); transX = transX ? transX[1] : 1; transY = transform.match(/scaleY\((\d+)\)/i); transY = transY ? transY[1] : 1; } var origin = element.css(prefix+"tranform-origin").match(/(\d+)% (\d+)%/); /*Default: 50% 50%*/ if(origin){ originX = origin[1]/100; originY = origin[2]/100; } else { //Investigate yourself. What would be the value if it doesn't exist? } } if(match){ /*A match has been found, thus transX and transY are defined*/ /*Width * originX * scaleY = width * [relative affected part of element] * [scale factor] = adjusted offset*/ var minusLeft = element.width() * originX * scaleX; var minusTop = element.height() * originY * scaleY; /*Do something, for example:*/ element.css("left", "-="+minusLeft+"px"); element.css("top", "-="+minusTop+"px"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7526476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php form submit counter So I've made an extremely simple 4 page static webpage for this client with a quick contact form handled by php. Everything goes swimmingly. Then the client comes to me and requests that he is able to see a counter of how many submits have been made. So he generally wants a counter for his form, Which is simple enough because I just add a counter for every successful email sent using the form and save it within some kind of data storage. BUT... the only way I can think to do it is have a separate user page with a simple box that has the number in it, that only the client can access. I could do this... Save the counter in an xml file or a one table, one column, one row mySQL database. But is there a better easier simpler way to do this??? Can I set up a link with Google analytics or something? Rather than making a single page with a number on it. A: I suggest going with a separate page for the client to view counts. You can use .htaccess to control the access to this page. The main reason is looking forward to future client requests. Most likely, they will then ask you to show counts for specified periods of time, counts per day/week/months, etc. If you set up your page now, then you can have place to customize/extend. As for storing the counter, I would suggest storing more than just the total. Have a table where you'd store: * *date/time of form submission *remote IP address (for possible future reference) *content of the submitted form (if the client ever decides to want to see it) *maybe event content of the email (if the client ever decides to want to resend it) Then to display the totals, you'd just select count(1) from that_table with any required date/etc. grouping.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the difference between "descriptor" and "signature"? I am now using ASM (Java bytecode instrumentation library). To retrieve the signature of given method, there is a field which is named "desc". I guess this is an abbreviation of "descriptor", but why isn't it named as "signature"? Is there any difference between "descriptor" and "signature"? A: "descriptor" probably refers to the method descriptor as defined in the JVM spec § 4.3.3. It describes the parameter types and the return type of a method. It does not contain the method name. "signatur" probably refers to the signature of as defined in the Java Language Specification § 8.4.2. It contains the name of the method as well as the parameter types. It does not contain the return type. Note that those two terms are defined in two different places and at different levels. A method descriptor exists at the JVM-level, so it's pretty detached from the Java language. The signature, however is a very similar concept, but acts on the Java language level (as it's defined in the JLS). A: In the context of asm, you care about internal names, method descriptors, type descriptors and signatures. Section numbers are from the asm doc. 2.1.2 Internal names "The internal name of a class is just the fully qualified name of this class, where dots are replaced with slashes." com/snark/Boojum 2.1.3 Type descriptors [[Ljava/lang/Object; 2.1.4 Method descriptor A method descriptor is a list of type descriptors that describe the parameter types and the return type of a method, in a single string. int[] m(int i, String s) becomes (ILjava/lang/String;)[I 4.1. Generics (for signatures) "For backward compatibility reasons the information about generic types is not stored in type or method descriptors (which were defined long before the introduction of generics in Java 5), but in similar constructs called type, method and class signatures." This Java: List<List<String>[]> Becomes this signature: Ljava/util/List<[Ljava/util/List<Ljava/lang/String;>;>; A: Looking at the JVM spec section 4.3.3, for one thing the descriptor contains the return type - whereas that isn't part of a the signature of a method. A method descriptor represents the parameters that the method takes and the value that it returns but... Two methods have the same signature if they have the same name and argument types (Given this, it's also not clear that the descriptor contains the name of the method...)
{ "language": "en", "url": "https://stackoverflow.com/questions/7526483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: App showing in search but can't access I can see my app in search, but when i click it i get an page not found error, also I get a page not found error when trying to view insights. I wonder whats wrong? my app name:Small Circles url:http://mysmallcircles.appspot.com/ profile page:http://www.facebook.com/apps/application.php?id=129200773829451 THX~! A: Try setting the bookmark url in the app settings. This has been logged with Facebook already: http://bugs.developers.facebook.net/show_bug.cgi?id=20469
{ "language": "en", "url": "https://stackoverflow.com/questions/7526494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Undefined method 'on' for ActionModel I'm getting the following error: NoMethodError in Users#new Showing .../app/views/users/form/_new.haml where line #7 raised: undefined method `on' for #<ActiveModel::Errors:0x007fb599ec6610> The code in line 7 is: 7: = errors_for user, :first_name And the application_helper.rb: def errors_for(model, field) error = case errors = model.errors.on(field) ... end 'on' is a default method in ActiveRecord. Why doesn't this work? A: If you're using Rails 3, then the problem is that there's no "on" method for the Errors class anymore. I think you're supposed to use "get" now. So: error = case errors = model.errors.get(field) Or... error = case errors = model.errors[field] A: I checked my user and u.errors is an ActiveRecord::Errors, while I see you have an ActiveModel::Error, I would work on that. Then I don't understand case errors = statement in your helper, I'm curious to know how you implemented that part...
{ "language": "en", "url": "https://stackoverflow.com/questions/7526499", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: call FB.login() after FB.init() automatically i`m developing an app for Facebook. My Code: function init() { window.fbAsyncInit = function() { var appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'; FB.init({ appId: appID, status: true, cookie: true, xfbml: true}); login(); }; (function() { var e = document.createElement("script"); e.async = true; e.src = "https://connect.facebook.net/en_US/all.js?xfbml=1"; document.getElementById("fb-root").appendChild(e); }()); }; function login() { FB.login(function(response) { if (response.session) { if (response.perms) { // user is logged in and granted some permissions. // perms is a comma separated list of granted permissions } else { // user is logged in, but did not grant any permissions } } else { // user is not logged in } }, {perms:'read_stream,publish_stream,offline_access'}); }; I want to call the "init" function and after "init" should call the "login" function (open up the Facebook Login Window) automatically. But i always get "b is null" FB.provide('',{ui:function(f,b){if(!f....onent(FB.UIServer._resultToken));}}); Error in Firebug. Can anybody help me? Does anybody have the same problem? Thanks A: You needn't have the facebook init stuff in a function, it can go straight on the page, then it will load at the same time, rather than waiting for a button click to load. Then you just need the login logic on the logiin button <html> <head> </head> <body> <script type="text/javascript"> window.fbAsyncInit = function() { var appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxx'; FB.init({ appId: appID, status: true, cookie: true, xfbml: true }); // This bit adds the login functionality to the login // button when api load is complete document.getElementById("login").onclick = function() { FB.login(function(response) { if (response.session) { if (response.perms) { // user is logged in and granted some permissions. // perms is a comma separated list of granted permissions } else { // user is logged in, but did not grant any permissions } } else { // user is not logged in } }, {perms:'read_stream,publish_stream,offline_access'}); } }; (function() { var e = document.createElement("script"); e.async = true; e.src = "https://connect.facebook.net/en_US/all.js?xfbml=1"; document.getElementById("fb-root").appendChild(e); }()); </script> <a id="login" href="somewhere.html">My login button</a> </body> </html> You can put the login stuff in a method and automatically call the it after the FB.init, but most browsers will block the pop up window. You are better off waiting for the user to click a login button to make sure they see it properly, and it is generally good practise to only make things happen when the user explicitly requests them to. I think the facebook 'good practice' guide also mentions this somewhere.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to bind a DataTable to a WPF DataGrid while filtering the rows and have two-way binding I have a DataTable that represents a SQL table. The SQL table references itself in a parent/child manner, but only one level (a parent can't have a parent itself) I want to bind this DataTable to a DataGrid so i can edit the rows on the DataGrid and add new Rows and this should be propagated to the DataTable. So far it's easy. But now i want to display only the rows that have a parent. From what i understand, if i use a CollectionView to filter the data the changes on the grid won't be propagated to the DataTable. So how can i do that? A: what happens if you try to set the defaultview Rowfilter? var dv = yourDataTableInstance.DefaultView; dv.RowFilter = "parentcolumn IS NOT NULL"; ItemsSource for the DataGrid is still the datatable but it should be filtered now.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: net.rim.device.api.io.file.FileIOException: File system out of resources in blackberry Below code throws net.rim.device.api.io.file.FileIOException: File system out of resources this exception. Can anyone tell me how it happens? public Bitmap loadIconFromSDcard(int index) { FileConnection fcon = null; Bitmap icon = null; InputStream is=null; try { fcon = (FileConnection) Connector.open(Shikshapatri.filepath + "i" + index + ".jpg", Connector.READ); if (fcon.exists()) { byte[] content = new byte[(int) fcon.fileSize()]; int readOffset = 0; int readBytes = 0; int bytesToRead = content.length - readOffset; is = fcon.openInputStream(); while (bytesToRead > 0) { readBytes = is.read(content, readOffset, bytesToRead); if (readBytes < 0) { break; } readOffset += readBytes; bytesToRead -= readBytes; } EncodedImage image = EncodedImage.createEncodedImage(content, 0, content.length); image = resizeImage(image, 360, 450); icon = image.getBitmap(); } } catch (Exception e) { System.out.println("Error:" + e.toString()); } finally { // Close the connections try { if (fcon != null) fcon.close(); } catch (Exception e) { } try { if (is != null) is.close(); is = null; } catch (Exception e) { } } return icon; } Thanks in advance... A: Check this BB dev forum post - http://supportforums.blackberry.com/t5/Java-Development/File-System-Out-of-Resources/m-p/105597#M11927 Basically you should guaranteedly close all connections/streams as soon as you don't need them, because there is a limited number of connection (be it a file connection or http connection) handles in OS. If you execute several loadIconFromSDcard() calls at the same time (from different threads) consider redesign the code to call them sequentially. UPDATE: To avoid errors while reading the content just use the following: byte[] content = IOUtilities.streamToBytes(is); And since you don't need file connection and input stream any longer just close them right after reading the content (before creating EncodedImage): is.close(); is = null; // let the finally block know there is no need to try closing it fcon.close(); fcon = null; // let the finally block know there is no need to try closing it Minor points: Also in the finally block it is worth set fcon = null; explicitly after you close it, I believe this can help old JVMs (BB uses Java 1.3 - rather old one) to decide quicker that the object is ready to be garbage collected. I also believe that the order you close streams in the finally block may be important - I'd change to close is first and then fcon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Removing duplicates with Regex, using Editpad Lite 7 I have a comma-delimited list of words in a text document. I have basically just removed all the punctuation from a novel, so there is a lot of instances of the same words. I can't find out how to use regex to leave just one instance of every word. I'm using Editpad Lite 7. Could anyone give me advice on how to do this. (If possible at all). A: If your editor supports look-around assertions, you could use it to remove (i.e. replace with "") all matches of (?<=,|^)([^,]*)(?=,)(?=.*,\1(,|$)) See it in action in RegExr. The performance of this might be quite bad, depending of the length of the text. If you need to do this regularly, you could be better of writing a small script in the language of your choice. A: Assuming you have a text that is a comma-delimited list of words like: hello,world,hello,abc,world and you want to remove duplicate words so that the resulting text is: hello,world,abc I don't think you will be able to do this using regular expressions in Editpad Lite 7. Your best bet is to use a programming language to accomplish this. Here is a simple example using PHP: $text = "hello,world,hello,abc,world"; $seen = array(); foreach (explode(',', $text) as $word) { if (isset($seen[$word])) continue; $seen[$word] = true; print $word . ','; } // Outputs: hello,world,abc,
{ "language": "en", "url": "https://stackoverflow.com/questions/7526507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Force closing if i add a string to string array I have the code as below String[] myList = new String[] {"Hello","World","Foo","Bar"}; ListView lv = new ListView(this); myList[4] = "hi"; lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,myList)); setContentView(lv); The app is force closing,in logs im getting "java.lang.UnsupportedOperationException" if i remove myList[4] = "hi"; code I'm getting the listview as in myList array. But my problem is i have to add string dynamically to this array and have to display. A: Don't use array. Array has fixed length and you cannot add new items to it. Use list instead: List<String> myList = new ArrayList<String>(); myList.add("Hello"); myList.add("World"); myList.add("Foor"); myList.add("Bar"); ListView lv = new ListView(this); myList.add("hi"); A: You cannot simply add another element to the array. When you declare your array as String[] myList = new String[] {"Hello","World","Foo","Bar"}; Your array is created with four elements in it. When you are trying to set myList[4], you're essentially trying to set a fifth element - and are obviously getting ArrayIndexOutOfBoundsException. If you need to dynamically add elements, you are better off using ArrayList instead of an array. A: Since your array contains 4 items, myList[4] is actually out of bounds. The maximum element index will be myList[3]. Sure this is the issue. A: you are trying to add element at 5th position. Arrays don't grow dynamically. why dont' you try like this, String[] myList = new String[] {"Hello","World","Foo","Bar"}; ArrayList<String> mList=new ArrayList<String>(); Collections.addAll(mList,myList); ListView lv = new ListView(this); mList.add("Hi"); lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mList)); setContentView(lv);
{ "language": "en", "url": "https://stackoverflow.com/questions/7526509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting background for fragment I have a list fragment and a details fragment in a xml layout which is set as the layout of an activity. How can I set a background image for each fragment. If I am doing it in xml like android:background=@drawable/anyimage it shows an error. I searched but didn't get what I needed, so any suggestions will be appreciated. A: In my case the image file was blank and I saved it wrong. Might want to double check. Edit: Ok, actually, putting android:background in a <fragment> doesn't work, but it will if you put it in the top level element of a layout the fragment inflates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: libvlc media player in C# Hey guys and girls :) ok so i ran this project -> http://www.helyar.net/2009/libvlc-media-player-in-c-part-2/ and it worked perfectly (he was using .net 2.0) however when i try anything above 3.5 it gives -> Unable to load DLL ‘libvlc’: The specified module could not be found. (Exception from HRESULT: 0x8007007E) is there any workaround someone has done that sorts this out? MANY thanks ppl :D:D:D:D A: There are two things that must be done when using that example with the new 2.0.x VLC releases. First, you have to somehow add the libvlc DLL to the search path. I used a call to SetDllDirectory to do the trick. You declare it as: static class LibVlc { . . . [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetDllDirectory(string lpPathName); . . . } Then you can call this method with the root folder of the VLC installation. On my PC, I called it as follows: LibVlc.SetDllDirectory(@"C:\Program Files (x86)\VideoLAN\VLC"); Obviously, for a program being distributed this parameter should be configurable. Next, the VLC API's have apparently changed because none of the methods require an exception object to be passed in anymore. It looks like return values from the methods should be checked (for example, libvlc_new() returns NULL if there was an error). I haven't tried passing in the exception object by reference like he does but the calls all work fine without it (and my interfaces now match the VLC API exactly). I also specify the calling convention to use when doing interop, just to be clear to the runtime what I expect for parameter passing order and such. For example, here are my defines for libvlc_new and libvlc_release: [DllImport("libvlc", CallingConvention=CallingConvention.Cdecl)] public static extern IntPtr libvlc_new(int argc, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] string[] argv); [DllImport("libvlc", CallingConvention=CallingConvention.Cdecl)] public static extern void libvlc_release(IntPtr instance); I hope this helps! A: You must copy libvlc.dll to your bin/debug folder. It must be the one from your VLC installation folder (C:\program files\videolan\vlc)
{ "language": "en", "url": "https://stackoverflow.com/questions/7526518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Source for basic Shapes in WPF Does anybody know if there is some online source where one can download basic shapes such as the minimize/ maximize glyph, a star geometry or the Visual Studio pin glyph as WPF GEometry Path? A: In Expression Blend you can find Shapes for WPF. http://www.microsoft.com/expression/products/blend_overview.aspx Assets->Shapes A: If you have a favorite WPF app, you could also use Snoop to look at the shapes in that app and use them as a starting point. Please do not just rip other people's hard work off!
{ "language": "en", "url": "https://stackoverflow.com/questions/7526524", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ThinkingSphinx Polymorphic relation problem | rails 3.1 I could not create index with thinking_sphinx for the simple polymorphic schema below. (Note: I am able to create index from has_many models but I want to create my indexes from 'belongs_to' model (Comment).) For simplicity, I created a sample project which has the schema: create_table "articles", :force => true do |t| t.string "title" t.text "body" t.datetime "created_at" t.datetime "updated_at" end create_table "comments", :force => true do |t| t.text "content" t.integer "commentable_id" t.string "commentable_type" t.datetime "created_at" t.datetime "updated_at" end create_table "photos", :force => true do |t| t.string "title" t.datetime "created_at" t.datetime "updated_at" end My sample models and index are: class Article < ActiveRecord::Base has_many :comments, :as => :commentable end class Photo < ActiveRecord::Base has_many :comments, :as => :commentable end class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true define_index do indexes commentable_type, :as => :commentable_type has commentable_id, :type => :integer, :as => :commentable_id indexes commentable.title end end I have 1 article with 1 comment and 1 photo with 1 comment, for the test. The problem is I could not create index with ruby '1.9.2', rails '3.1.0' and thinking_sphinx '2.0.5'. Note, I tried creating index with both 0.99 and 2.0.1 beta releases of sphinx. I also tried article.title and photo.title for the problematic line. Waiting for working answers. The error: (in /Users/mustafat/Desktop/xxx-meta/testlog) Generating Configuration to /Users/mustafat/Desktop/xxx-meta/testlog/config/development.sphinx.conf Sphinx 2.0.1-beta (r2792) Copyright (c) 2001-2011, Andrew Aksyonoff Copyright (c) 2008-2011, Sphinx Technologies Inc (http://sphinxsearch.com) using config file '/Users/mustafat/Desktop/xxx-meta/testlog/config/development.sphinx.conf'... FATAL: no indexes found in config file '/Users/mustafat/Desktop/xxx-meta/testlog/config/development.sphinx.conf' Failed to start searchd daemon. Check /Users/mustafat/Desktop/xxx-meta/testlog/log/searchd.log. Failed to start searchd daemon. Check /Users/mustafat/Desktop/xxx-meta/testlog/log/searchd.log if I try with the code below: class Comment < ActiveRecord::Base belongs_to :commentable, :polymorphic => true define_index do indexes commentable_type, :as => :commentable_type has commentable_id, :type => :integer, :as => :commentable_id indexes article.title end end I am getting the error below: (in /Users/mustafat/Desktop/xxx-meta/testlog) Generating Configuration to /Users/mustafat/Desktop/xxx-meta/testlog/config/development.sphinx.conf Sphinx 2.0.1-beta (r2792) Copyright (c) 2001-2011, Andrew Aksyonoff Copyright (c) 2008-2011, Sphinx Technologies Inc (http://sphinxsearch.com) using config file '/Users/mustafat/Desktop/xxx-meta/testlog/config/development.sphinx.conf'... indexing index 'comment_core'... ERROR: index 'comment_core': sql_range_query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' `comments`.`id`, `comments`.`commentable_id` ORDER BY NULL' at line 1 (DSN=mysql://root:***@localhost:3306/xxx_testlog). total 0 docs, 0 bytes total 0.003 sec, 0 bytes/sec, 0.00 docs/sec skipping non-plain index 'comment'... total 0 reads, 0.000 sec, 0.0 kb/call avg, 0.0 msec/call avg total 0 writes, 0.000 sec, 0.0 kb/call avg, 0.0 msec/call avg Failed to start searchd daemon. Check /Users/mustafat/Desktop/xxx-meta/testlog/log/searchd.log. Failed to start searchd daemon. Check /Users/mustafat/Desktop/xxx-meta/testlog/log/searchd.log A: As answered on Twitter, this is fixed in the latest release of TS, 2.0.7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why is a download manager required to utilize full download speed available via isp from computer in california accessing ec2 instance in virginia? So far I get an average of 700 kilobytes per second for downloads via chrome hitting an ec2 instance in virginia (us-east region). If I download directly from s3 in virginia (us-east region) I get 2 megabytes per second. I've simplified this way down to simply running apache and reading a file from a mounted ebs volume. Less than one percent of the time I've seen the download hit around 1,800 kilobytes per second. I also tried nginx, no difference. I also tried running a large instance with 7GB of Ram. I tried allocating 6GB of ram to the jvm and running tomcat, streaming the files in memory from s3 to avoid the disk. I tried enabling sendfile in apache. None of this helps. When I run from apache reading from the file system, and use a download manager such as downthemall, I always get 2 megabytes per second when downloading from an ec2 instance in virginia (us-east region). It's as if my apache is configured to only allow 700 megabytes per thread. I don't see any configuration options relating to this though. What am I missing here? I also benchmarked dropbox downloads as they use ec2 as well, and I noticed I get roughly 700 kilobytes per second there too, which is way slow as well. I imagine they must host their ec2 instances in virginia / us-east region as well based in the speed. If I use a download manager to download files from dropbox I get 2 megabytes a second as well. Is this just the case with tcp, where if you are far away from the server you have to split transfers into chunks and download them in parrallel to saturate your network connection? A: I think your last sentence is right: your 700mbps is probably a limitation of a given tcp connection ... maybe a throttle imposed by EC2, or perhaps your ISP, or the browser, or a router along the way -- dunno. Download managers likely split the request over multiple connections (I think this is called "multi-source"), gluing things together in the right order after they arrive. Whether this is the case depends on the software you're using, of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C++ Constructor / Class Question: Error - left of must have class/struct/union I realise what this error means, the thing that is puzzling me is why I get it. I have emulated the error in this tiny program for the sake of this question. Here is the code: source file: #include "RandomGame.h" using namespace std; NumberGame::NumberGame(int i) { upperBound = i; numberChosen = 1 + rand() % upperBound; } NumberGame::NumberGame() { upperBound = 1000; numberChosen = 1 + rand() % upperBound; } int NumberGame::guessedNumber(int g) { if (g == numberChosen) { return 2; } else if (g < numberChosen) { return 0; } else { return 1; } } header file: #ifndef NUMBERGAME_H #define NUMBERGAME_H #include <iostream> using namespace std; class NumberGame { private: int upperBound; int numberChosen; int g; public: NumberGame(int); NumberGame(); int guessedNumber(int); }; #endif main: #include <iostream> #include <cstdlib> #include "RandomGame.h" using namespace std; int makeEven(int); int main() { //only one of these lines will remain uncommented NumberGame newNumberGame(5); // works NumberGame newNumberGame; // works NumberGame newNumberGame(); // doesn't work // I get the error here, apparently when using empty brackets, newNumberGame //is not a class anymore. wwwhhyyyyy?????? newNumberGame.guessedNumber(5); return 0; } I haven't done C++ in a while so i'm sure it's something really simple, but why doesn't the empty brackets work? btw it also doesn't work if I just have one constructor with no arguments, or one constructor with a default argument. A: This NumberGame newNumberGame(); declares a function newNumberGame() taking no arguments and returning a NumberGame. C++'s grammar is grown over several decades, rather than being designed in a single act of creation. Consequently, it has many ambiguities that needed to be resolved. This ambiguity was resolved for a b() to be a function declaration rather than an object definition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526538", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what is difference between sprite.width VS sprite.scaleX Both of sprite.width and sprite.scaleX can be used for scale a sprite. Is possible sprite.scaleX depends on screen size? A: When you change the width property, the scaleX property changes accordingly var rect:Shape = new Shape(); rect.graphics.beginFill(0xFF0000); rect.graphics.drawRect(0, 0, 100, 100); trace(rect.scaleX) // 1; rect.width = 200; trace(rect.scaleX) // 2; official documentation A: You should read the official documentation about scaleX and width. By default, scaleX=1 which means there is no rescaling of the sprite, it does not depend on anything, you may set it freely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: sqlite query results in crash in iPhone app - Memory Issue I am using a sqlite query to get nutrient values for a specific food item from USDA database. The query works fine, when tried in simulator, but results in crash on device sometimes. I am including the USDA database in the app itself. Also the table on which the query is getting executed holds more than 5 lac records. I am getting 'Level 1 Memory Warning' at the launch of application. I cannot go for webservices, as the requirement is to give offline support. Any suggestions how to handle this situation?? Edit : In the log I get Signal 0 message Program received signal: “0”. Data Formatters temporarily unavailable, will re-try after a 'continue'. (Unknown error loading shared library "/Developer/usr/lib/libXcodeDebuggerSupport.dylib") A: I guess the size of the database is causing the crash... If you are using this database as read only then you can use the compressed and encrypted form ... you can get more details from here http://www.hwaci.com/sw/sqlite/cerod.html this might help you get rid of the memory warnings.. here is another link which can help you reduce the size of the database.... How to reduce the size of an sqlite3 database for iphone? A: You are exhausting your app's memory. I am not a DB expert but you will have to use some special techniques to access your huge data base. Perhaps execute multiple queries serially in different sections of the DB. Or divide the DB into segments. Following are some references related to the crash you are seeing- Program received signal: “0”. Data Formatters temporarily unavailable Data Formatters temporarily unavailable Data Formatters temporarily unavailable, will re-try after a 'continue' There are more if you search for the error message. A: Memory Related Crashes are quite common for ios apps I've noticed that more stable apps tend to manually manage memory alot over just letting the device manage it. I think if you split it up into sections instead of reading off one file and like akshay said index the tables it will be more stable. You could try reading files from compressed zips which would be more efficient over just plain old reading.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Widgets in Rails I have a business that I outsourced all of the tech for. Its essentially a widget on an external site, with a management panel on our domain selecting whats shown on the widget. Lets say its a manual "relevant news" widget. I think I can code the rails part, but how would I do the widgets part? Can someone point me in the right direction? The widget would need to be JavaScript and copy/pastable. (More context, having to use the old system thats in PHP, and it breaks my heart having to ask the outsourcers to help me with every little thing, so I'm looking to rebuild it) EDIT: how much of this is still valid? Its posted from 07 - http://www.igvita.com/2007/06/05/creating-javascript-widgets-in-rails/ Thanks! Geoff A: you could create a json api using https://github.com/fabrik42/acts_as_api (imho, this is the easiest way to create an api) and then create your widget in pure javascript or jquery. If you need to authenticate, you'll need to send an api key with your requests, and also on your server side check the request.domain with the api key you have given that domains webmaster.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526543", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can Joins between views and table hurt performance? I am new in sql server, my manager has given me job where i have to find out performance of query in sql server 2008. That query is very complex having joins between views and table. I read in internet that joins between views and table cause performance hurt? If any expert can help me on this? Any good link where i found knowledge of this? How to calculate query performance in sql server? A: Look at the query plan - it could be anything. Missing indexes on one of the underlying view tables, missing indexes on the join table or something else. Take a look at this article by Gail Shaw about finding performance issues in SQL Server - part 1, part 2. A: A view (that isn't indexed/materialised) is just a macro: no more, no less That is, it expands into the outer query. So a join with 3 views (with 4, 5, and 6 joins respectively) becomes a single query with 15 JOINs. This is a common "I can reuse it" mistake: DRY doesn't usually apply to SQL code. Otherwise, see Oded's answer A: Oded is correct, you should definitely start with the query plan. That said, there are a couple of things that you can already see at a high level, for example: CONVERT(VARCHAR(8000), CN.Note) LIKE '%T B9997%' LIKE searches with a wildcard at the front are bad news in terms of performance, because of the way indexes work. If you think about it, it's easy to find all people in the phone book whose name starts with "Smi". If you try to find all people who have "mit" anywhere in their name, you will find that you need to read the entire phone book. SQL Server does the same thing - this is called a full table scan, and is typically quite slow. The other issue is that the left side of the condition uses a function to modify the column (specifically, converting it to a varchar). Essentially, this again means that SQL Server cannot use an index, even if there was one for the column CN.Note. My guess is that the column is a text column, and that you will not be allowed to change the filter logic to remove the wildcard at the beginning of the search. In this case, I would recommend looking into Full-Text Search / Indexing functionality. By enabling full text indexing, and using specific keywords such as CONTAINS, you should get better performance. Again (as with all performance optimisation scenarios), you should still start with the query plan to see if this really is the biggest problem with the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue with Custom URL scheme and messages app in iOS I have registered an Custom URL scheme in my application. From server i send an SMS to the phone with the message starting with the custom URL scheme. example myapp://mymessageToApplication When the SMS reaches the inbox, the messages application does not receognize the above message as a link. So, i am unable to click on the message to start by application. This happens everytime i delete the application and reinstall the application. But, when i restart my phone, the messages application recognizes the message as a link and i can click on the link to start my application. After that it all fine until i delete the current application and re-install it again through xCode on my test phone. Does anyone aced similar issue? can anyone suggest me what could be wrong? To add, i can type the message myapp://mymessageToApplication in browser to launch my application. It works always. So, the custom URL is registered fine. Only the messages application is not picking it up until i restart the phone. A: I have filed a bug in Apple and they have replied for that. They ahve agreed that it is a known issue and they are working on it. Below is the reply from them This is a follow up to Bug ID# 10166363. After further investigation it has been determined that this is a known issue, which is currently being investigated by engineering. This issue has been filed in our bug database under the original Bug ID# 10053369. The original bug number being used to track this duplicate issue can be found in the State column, in this format: Duplicate/OrigBug#. Thank you for submitting this bug report. We truly appreciate your assistance in helping us discover and isolate bugs. A: Did you try to only kill and restart the messages application instead of restarting your iPhone completely? I guess that's only because the Messages application only check which custom URL schemes are registered when it launches (and not when it is already launched but in background and is only brought to forground). Just a guess but it might be a probable explanation (and if it is, I don't think there is anything you can do except file a bug to Apple... but check it first)
{ "language": "en", "url": "https://stackoverflow.com/questions/7526547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it neceassry to extends SQLiteOpenHelper? Is it necessary to extends SQLiteOpenHelper.I just want to copy the database(read only) from aseets folder. A: if you just want to copy the database then its fine. But if you want to read,update,delete or create new record in database then there are two ways * *Extend sqlitedatabase *Use ormlite wrapper Hope this will help. A: It is not necessary to extends SQLiteOpenHelper,To create and upgrade a database in your Android application you usually subclass "SQLiteOpenHelper". In this class you need to override the methods onCreate() to create the database and onUpgrade() to upgrade the database in case of changes in the database schema. Both methods receive an "SQLiteDatabase" object. SQLiteOpenHelper provides the methods getReadableDatabase() and getWriteableDatabase() to get access to an "SQLiteDatabase" object which allows database access either in read or write mode. For the primary key of the database you should always use the identifier "_id" as some of Android functions rely on this standard. A: Yes, it not need ,if you just want copy database file and don`t operate database, it just a file I/O operate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526548", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Search in ListView c# I've wrote a method to search thru ListView for a given string and mark the ones that are found with Color. It works fine however with lots of information on screen and scrollable ListView it's sometimes hard to find what user is looking for. Normally I do create special searches by modifying method and SQL query WHERE clause but it's always a pain and requires more work/code for each ListView/Data. I would like to have some generalized search that would work for all kind of searches in ListView just like one I have now but with ability to hide (rows) what's not needed and show only necessary rows. Of course if one changes it's mind it has to bring back the old rows back. I guess the biggest problem for me is how to store all the columns and data without over complicating knowing that it can be 3 to 20+ columns and multiple rows. public static void wyszukajNazweListView(ListView varListView, string varWyszukaj) { if (varWyszukaj != "") { foreach (ListViewItem comp in varListView.Items) { comp.UseItemStyleForSubItems = false; foreach (ListViewItem.ListViewSubItem drv in comp.SubItems) { string textToAdd2 = drv.Text; if (textToAdd2.Length >= 1) { if (textToAdd2.ToLower().Contains(varWyszukaj.ToLower())) { drv.BackColor = Color.DarkOrange; } else { drv.BackColor = Color.White; } } } bool varColor = false; foreach (ListViewItem.ListViewSubItem drv in comp.SubItems) { if (drv.BackColor == Color.DarkOrange) { varColor = true; break; } } if (varListView.SmallImageList != null) { if (varColor) { comp.ImageIndex = 2; } else { comp.ImageIndex = -1; } } } } else { foreach (ListViewItem comp in varListView.Items) { comp.UseItemStyleForSubItems = false; comp.BackColor = Color.White; foreach (ListViewItem.ListViewSubItem drv in comp.SubItems) { drv.BackColor = Color.White; comp.ImageIndex = -1; } } } } A: I'd probably store it as a DataTable object. DataTable type allows setting its rows as hidden (e.g. Visible = false) and you can bind your ListView directly to it. EDIT: noticed the WinForms tag. Even simpler: no need to mock about with ViewState/Session.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526549", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Instrumenting C/C++ codes using LLVM I just read about the LLVM project and that it could be used to do static analysis on C/C++ codes using the analyzer Clang which the front end of LLVM. I wanted to know if it is possible to extract all the accesses to memory(variables, local as well as global) in the source code using LLVM. Is there any inbuilt library present in LLVM which I could use to extract this information. If not please suggest me how to write functions to do the same.(existing source code, reference, tutorial, example...) Of what i have thought, is I would first convert the source code into LLVM bc and then instrument it to do the analysis, but don't know exactly how to do it. I tried to figure out myself which IR should I use for my purpose ( Clang's Abstract Syntax Tree (AST) or LLVM's SSA Intermediate Representation (IR). ), but couldn't really figure out which one to use. Here is what I m trying to do. Given any C/C++ program (like the one given below), I am trying to insert calls to some function, before and after every instruction that reads/writes to/from memory. For example consider the below C++ program ( Account.cpp) #include <stdio.h> class Account { int balance; public: Account(int b) { balance = b; } int read() { int r; r = balance; return r; } void deposit(int n) { balance = balance + n; } void withdraw(int n) { int r = read(); balance = r - n; } }; int main () { Account* a = new Account(10); a->deposit(1); a->withdraw(2); delete a; } So after the instrumentation my program should look like: #include <stdio.h> class Account { int balance; public: Account(int b) { balance = b; } int read() { int r; foo(); r = balance; foo(); return r; } void deposit(int n) { foo(); balance = balance + n; foo(); } void withdraw(int n) { foo(); int r = read(); foo(); foo(); balance = r - n; foo(); } }; int main () { Account* a = new Account(10); a->deposit(1); a->withdraw(2); delete a; } where foo() may be any function like get the current system time or increment a counter .. so on. I understand that to insert function like above I will have to first get the IR and then run an instrumentation pass on the IR which will insert such calls into the IR, but I don't really know how to achieve it. Please suggest me with examples how to go about it. Also I understand that once I compile the program into the IR, it would be really difficult to get 1:1 mapping between my original program and the instrumented IR. So, is it possible to reflect the changes made in the IR ( because of instrumentation ) into the original program. In order to get started with LLVM pass and how to make one on my own, I looked at an example of a pass that adds run-time checks to LLVM IR loads and stores, the SAFECode's load/store instrumentation pass (http://llvm.org/viewvc/llvm-project/safecode/trunk/include/safecode/LoadStoreChecks.h?view=markup and http://llvm.org/viewvc/llvm-project/safecode/trunk/lib/InsertPoolChecks/LoadStoreChecks.cpp?view=markup). But I couldn't figure out how to run this pass. Please give me steps how to run this pass on some program say the above Account.cpp. A: Since there are no answer to your question after two days, I will offer his one which is slightly but not completely off-topic. As an alternative to LLVM, for static analysis of C programs, you may consider writing a Frama-C plug-in. The existing plug-in that computes a list of inputs for a C function needs to visit every lvalue in the function's body. This is implemented in file src/inout/inputs.ml. The implementation is short (the complexity is in other plug-ins that provide their results to this one, e.g. resolving pointers) and can be used as a skeleton for your own plug-in. A visitor for the Abstract Syntax Tree is provided by the framework. In order to do something special for lvalues, you simply define the corresponding method. The heart of the inputs plug-in is the method definition: method vlval lv = ... Here is an example of what the inputs plug-in does: int a, b, c, d, *p; main(){ p = &a; b = c + *p; } The inputs of main() are computed thus: $ frama-c -input t.c ... [inout] Inputs for function main: a; c; p; More information about writing Frama-C plug-ins in general can be found here. A: First off, you have to decide whether you want to work with clang or LLVM. They both operate on very different data structures which have advantages and disadvantages. From your sparse description of your problem, I'll recommend going for optimization passes in LLVM. Working with the IR will make it much easier to sanitize, analyze and inject code because that's what it was designed to do. The downside is that your project will be dependent on LLVM which may or may not be a problem for you. You could output the result using the C backend but that won't be usable by a human. Another important downside when working with optimization passes is that you also lose all symbols from the original source code. Even if the Value class (more on that later) has a getName method, you should never rely on it to contain anything meaningful. It's meant to help you debug your passes and nothing else. You will also have to have a basic understanding of compilers. For example, it's a bit of a requirement to know about basic blocks and static single assignment form. Fortunately they're not very difficult concepts to learn or understand (the Wikipedia articles should be adequate). Before you can start coding, you first have to do some reading so here's a few links to get you started: * *Architecture Overview: A quick architectural overview of LLVM. Will give you a good idea of what you're working with and whether LLVM is the right tool for you. *Documentation Head: Where you can find all the links below and more. Refer to this if I missed anything. *LLVM's IR reference: This is the full description of the LLVM IR which is what you'll be manipulating. The language is relatively simple so there isn't too much to learn. *Programmer's manual: A quick overview of basic stuff you'll need to know when working with LLVM. *Writting Passes: Everything you need to know to write transformation or analysis passes. *LLVM Passes: A comprehensive list of all the passes provided by LLVM that you can and should use. These can really help clean up the code and make it easier to analyze. For example, when working with loops, the lcssa, simplify-loop and indvar passes will save your life. *Value Inheritance Tree: This is the doxygen page for the Value class. The important bit here is the inheritance tree that you can follow to get the documentation for all the instructions defined in the IR reference page. Just ignore the ungodly monstrosity that they call the collaboration diagram. *Type Inheritance Tree: Same as above but for types. Once you understand all that then it's cake. To find memory accesses? Search for store and load instructions. To instrument? Just create what you need using the proper subclass of the Value class and insert it before or after the store and load instruction. Because your question is a bit too broad, I can't really help you more than this. (See correction below) By the way, I had to do something similar a few weeks ago. In about 2-3 weeks I was able to learn all I needed about LLVM, create an analysis pass to find memory accesses (and more) within a loop and instrument them with a transformation pass I created. There was no fancy algorithms involved (except the ones provided by LLVM) and everything was pretty straightforward. Moral of the story is that LLVM is easy to learn and work with. Correction: I made an error when I said that all you have to do is search for load and store instructions. The load and store instruction will only give accesses that are made to the heap using pointers. In order to get all memory accesses you also have to look at the values which can represent a memory location on the stack. Whether the value is written to the stack or stored in a register is determined during the register allocation phase which occurs in an optimization pass of the backend. Meaning that it's platform dependent and shouldn't be relied on. Now unless you provide more information about what kind of memory accesses you're looking for, in what context and how you intend to instrument them, I can't help you much more then this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Log4j logging info messages without logging warn messages I'm trying to log certain info messages onto a file but as soon as I run the application both warn and info messages are logged. Now, from what I've read from this site, you cannot log one without logging the other. Has anyone tried this before? If so, how did your properties file look like? My properties file looks like this: ***** Set root logger level to INFO and its two appenders to stdout and R. log4j.rootLogger=INFO, stdout, R # ***** stdout is set to be a ConsoleAppender. log4j.appender.stdout=org.apache.log4j.ConsoleAppender # ***** stdout uses PatternLayout. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout # ***** Pattern to output the caller's file name and line number. log4j.appender.stdout.layout.ConversionPattern=%5p [%M has started] (%F:%L) - %m%n / # ***** R is set to be a RollingFileAppender. log4j.appender.R=org.apache.log4j.DailyRollingFileAppender log4j.appender.R.DatePattern='.'yyyy-MM-dd-HH log4j.appender.R.File="folder where log will be saved" log4j.appender.R.layout.ConversionPattern=%5p [%m has started] %c{2}.[%x] (%F:%L) %d{yyyy-MM-dd HH:mm:ss} - %m%n # ***** R uses PatternLayout. log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%5p [%m has started] %c{2}.[%x] (%F:%L) %d{yyyy-MM-dd HH:mm:ss} - %m%n A: AFAIK there's no standard way to suppress higher log levels than those you are interested in. However, you might be able to use a custom appender to do that. It might look similar to this: public class MyAppender extends AppenderSkeleton { protected void append(LoggingEvent event) { if( event.getLevel() == Level.INFO ) { //append here, maybe call a nested appender } } } A: The log level WARN is higher than INFO, and the logging configuration defines the minimum threshold level to be logged by the appender. So, all messages higher than that level will also be logged. Hence, the WARN messages are expected. And I don't think you can configure it to the way you want. A: If the WARN messages that should not be printed come from a different package than the INFO messages, then you can define different log levels for these packages. The first can specify level ERROR and the second INFO it should look something like this: log4j.logger.com.test.something=ERROR log4j.logger.com.other.package=INFO cheers A: Why do you want to filter the WARN level? As peshkira said, you could use two different loggers for splitting/filtering your log output, or you could use tools like grep for filtering (offline) or you could simply remove the WARN logs from your code if your don't need them anyway. A: As far as I understand, advanced filters like LevelMatchFilter and LevelRangeFilter can do the trick for you. Thing worth keeping in mind though is that using these may require xml config instead of properties: Can't set LevelRangeFilter for log4j
{ "language": "en", "url": "https://stackoverflow.com/questions/7526552", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make invisible all running activities I want to show an alert box (like SMS alert) when a push notification is coming to device. My requirement is if the app is not visible or not running in forground, I want an alert box with transparent background. But is the app is running in forground, I just want an alert box where its background is the currently displaying activity. I can show it properly if the app is killed or running in foreground. But my problem is If the app is running in background, when the push notification comes, the alert box is visible withe background is the lastly running activity. I am displaying the alert box with in a new Activity where its background is transparent. How can I make invisible all activities in the app? Or how can I know how many activities are in stack? By knowing these I can finish all the activities.. Thank You... A: Refer these links : Closing several android activities simultaneously http://coderzheaven.com/2011/08/how-to-close-all-activities-in-your-view-stack-in-android/
{ "language": "en", "url": "https://stackoverflow.com/questions/7526553", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: isset in jQuery? Possible Duplicate: Finding whether the element exists in whole html page i would like make somethings: HTML: <span id="one">one</span> <span id="two">two</span> <span id="three">three</span> JavaScript: if (isset($("#one"))){ alert('yes'); } if (isset($("#two"))){ alert('yes'); } if (isset($("#three"))){ alert('yes'); } if (!isset($("#four"))){ alert('no'); } LIVE: http://jsfiddle.net/8KYxe/ how can I make that? A: function isset(element) { return element.length > 0; } http://jsfiddle.net/8KYxe/1/ Or, as a jQuery extension: $.fn.exists = function() { return this.length > 0; }; // later ... if ( $("#id").exists() ) { // do something } A: if (($("#one").length > 0)){ alert('yes'); } if (($("#two").length > 0)){ alert('yes'); } if (($("#three").length > 0)){ alert('yes'); } if (($("#four")).length == 0){ alert('no'); } This is what you need :) A: php.js ( http://www.phpjs.org/ ) has a isset() function: http://phpjs.org/functions/isset:454 A: You can use length: if($("#one").length) { // 0 == false; >0 == true alert('yes'); } A: function el(id) { return document.getElementById(id); } if (el('one') || el('two') || el('three')) { alert('yes'); } else if (el('four')) { alert('no'); } A: You can simply use this: if ($("#one")){ alert('yes'); } if ($("#two")){ alert('yes'); } if ($("#three")){ alert('yes'); } if ($("#four")){ alert('no'); } Sorry, my mistake, it does not work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: smartgwt filter editor problem i am using Listgrid of smartgwt api. i have set filter editor on the list grid using setShowFilterEditor(). On UI, i can filter out the text from the particular columns using filter editor which is shown on top of listgrid. till this, everything works fine. but problem starts after this. my ListGridRecords are of type ScreenInstanceGridRecord. I cleared out the filter criteria before getting the ListGridRecord from the ListGrid using method clearCriteria(), so that i can save all the records to database ie. unfiltered records. when i try to get records from the listgrid using getRecordList(), 1000 Dummy records are added on the fly on first iteration, all my populated records are ignored . and i need here is records of ScreenInstanceGridRecord type. but on second iteration, i am getting my populated records which is of ScreenInstanceGridRecord type. why this problem is occurring. i should be getting ScreenInstanceGridRecord on the first iteration itself when i try to get records from the ListGrid using getRecordList(). i am getting no idea about this weird thing. any help from your side is most welcome.. plss A: When you say you're getting 1000 Dummy records instead of your loaded records, in fact, your Records are not loaded yet at all. In this case, the ResultSet created by the ListGrid (see docs for ListGrid.fetchData()) is returning a provisional length (defaults to 1000) and returning the loading marker in lieu of Records (see ResultSet.rowIsLoaded()). Use the DataArrived event to take action once data has been loaded. See ResultSet.lengthIsKnown() for how you can, in general, tell that data is not yet loaded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526556", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Zend_Search_Lucene implementation with Symfony2 returning empty result I have an implementation of Zend_Search_Lucene within a Symfony2 application. I am using Zend 1.11. The index seems to be being created, I have several files including: _0.cfs optimization.lock.file read-lock-processing.lock.file read.lock.file segments_2 segments.gen write.lock.file here is the php code which I have inside a controller $index = \Zend_Search_Lucene::create(__DIR__.'/../../../../data/index'); $doc = new \Zend_Search_Lucene_Document(); $doc->addField(\Zend_Search_Lucene_Field::unIndexed('title', 'Symfony2') ); $doc->addField(\Zend_Search_Lucene_Field::text('contents', 'cat dog') ); $index->addDocument($doc); $index = \Zend_Search_Lucene::open(__DIR__.'/../../../../data/index'); $term = new \Zend_Search_Lucene_Index_Term("dog"); $query = new \Zend_Search_Lucene_Search_Query_Term($term); $results = $index->find($query); try { $results = $index->find($query); } catch (\Zend_Search_Lucene_Exception $ex) { $results = array(); var_dump($ex); } foreach ( $results as $result ) { echo $result->score, ' :: ', $result->title, "n"; } var_dump($results); exit; When I run the script the index files are created but only an empty array gets returned and is printed out with the last var_dump as array(0) { } Firstly does anyone know how I can check the index is being written correctly? Secondly does anyone know why my query is not returning any results? Has anyone successfully implemented Zend_Search_Lucene with Symfony2? I have tried both Lidaa Search and EWZ bundles but neither seems to work. I worked all day yesterday trying to resolve this problem with no joy, so any help would be very greatly appreciated. ok, so I've managed to write to the index file now by encoding as utf-8 like this $doc->addField(\Zend_Search_Lucene_Field::text('contents', 'dog', 'utf-8') ); However, I can still not retrieve any results. I think it might have something to do with the locale settings but I have explicitly set this like so: setlocale(LC_ALL, 'en_UK.utf-8'); ini_set('intl.default_locale', 'en-UK'); Also if I try and parse the query string as utf-8 the script hangs and timesout $queryStr = $_GET['query']; $query = \Zend_Search_Lucene_Search_QueryParser::parse($queryStr, 'utf-8'); Anyone know why this won't work on my Mac? A: Yeehaa! I reinstalled MAMP to version 2.0.3 and Boom! it works. I have a feeling this was something to do with either the default locale or encoding but not sure what. If anyone know why version 2.0 MAMP had a bug please let us know. Cheers Patrick A: You seem to be missing a commit. $doc->addField(\Zend_Search_Lucene_Field::text('contents', 'cat dog') ); $index->addDocument($doc); $index->commit(); //Try adding this line $index = \Zend_Search_Lucene::open(__DIR__.'/../../../../data/index');
{ "language": "en", "url": "https://stackoverflow.com/questions/7526561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible to store SSL certificate in android webview In the app I'm working on, I have to make an HTTPS post to a web server. I was getting certificate not trusted errors when i do it directly(without webview). But when i use android webview to load the HTTPS URL i can do public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) { handler.proceed() ; } to proceed with the connection when i get a SSL certificate not trusted error. My doubt is 1)if i use the above method will Android Webview actually store the certificate in its keystore? 2)Also will the same Webview be able to use the certificate in its keystore to accept the further connections to the same HTTPS server? 3)Can we programatically put some certificate in the webview's keystore so that it accepts all connections to an HTTPS enabled server? I am confused with lot of questions. Please help.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526563", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Can't understand this "Unreachable code detected" error I have this snippet of code that is giving me problems. The last break statements gives an error of "unreachable code detected" this has caused a logical flaw in my program. can someone identify the problem please? thanks! case 127232: case1 = splited[0]; changeRow[inServer] = "Audit Privileges and Logs:\n"; changeRow[inServer + " Exception"] = "No Exception"; writeToFile(Directory.GetCurrentDirectory() + @"\" + inServer + "127232.txt", case1); if (case1.Contains("audit level;failure") || case1.Contains("audit level;all")) { Console.WriteLine("success!"); changeRow[inServer + "Observations"] = changeRow[inServer + "Observations"] + "1) Audit options found ."; changeRow[inServer] = changeRow[inServer] + "string pattern audit level;failure or auditlevel;all found"; break; } else { //Audit Privileges should have been in enabled for sys and system accounts or the security administrator. changeRow[inServer + "Observations"] = changeRow[inServer + "Observations"] + "1) No audit options found."; changeRow[inServer] = changeRow[inServer] + "Correct audit options not configured!"; changeRow[inServer + " Exception"] = "Exception"; break; } break; A: Both the then and the else part of your if clause contain a break. So obviously the code after the if will never be executed. A: You have a break in both your if and your else clause, meaning that the break at the bottom will never be reached. It doesn't really matter in this particular case but it seems the compiler is not "smart" enough to figure that out. That's not necessarily a bad attitude for the compiler to take since this could be considered sloppy coding practice. Just get rid of both break statements within the if and else clauses or, alternatively, refactor to: case 127232: case1 = splited[0]; changeRow[inServer] = "Audit Privileges and Logs:\n"; changeRow[inServer + " Exception"] = "No Exception"; writeToFile(Directory.GetCurrentDirectory() + @"\" + inServer + "127232.txt", case1); if (case1.Contains("audit level;failure") || case1.Contains("audit level;all")) { Console.WriteLine("success!"); changeRow[inServer + "Observations"] = changeRow[inServer + "Observations"] + "1) Audit options found ."; changeRow[inServer] = changeRow[inServer] + "string pattern audit level;failure or auditlevel;all found"; break; } //Audit Privileges should have been in enabled for sys and system accounts or the security administrator. changeRow[inServer + "Observations"] = changeRow[inServer + "Observations"] + "1) No audit options found."; changeRow[inServer] = changeRow[inServer] + "Correct audit options not configured!"; changeRow[inServer + " Exception"] = "Exception"; break; What you have in your original is not really that much different to something like: if (someCondition) { doSomething(); return; } else { doSomethingElse(); } which I always think is cleaner as: if (someCondition) { doSomething(); return; } doSomethingElse(); I don't like being tabbed to death by code unless it's absolutely necessary :-) A: Because your code will go into either the if or the else and they both contain a break, which will take you outside of your switch statement, the last break statement is unnecessary. A: There are breaks in if Condition and Else condition. How can it reack break after else condition?
{ "language": "en", "url": "https://stackoverflow.com/questions/7526567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get raw page source (not generated source) from c# The goal is to get the raw source of the page, I mean do not run the scripts or let the browsers format the page at all. for example: suppose the source is <table><tr></table> after the response, I don't want get <table><tbody><tr></tr></tbody></table>, how to do this via c# code? More info: for example, type "view-source:http://feeds.gawker.com/kotaku/full" in the browser's address bar will give u a xml file, but if you just call "http://feeds.gawker.com/kotaku/full" it will render a html page, what I want is the xml file. hope this is clear. A: Here's one way, but it's not really clear what you actually want. using(var wc = new WebClient()) { var source = wc.DownloadString("http://google.com"); } A: If you mean when rendering your own page. You can get access the the raw page content using a ResponseFilter, or by overriding page render. I would question your motives for doing this though. Scripts run client-side, so it has no bearing on any c# code. A: You can use a tool such as Fiddler to see what is actually being sent over the wire. disclaimer: I think Fiddler is amazing
{ "language": "en", "url": "https://stackoverflow.com/questions/7526569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom LinearLayout width - weight placing problem I asked another questıon and after, I continued to this problem... Firstly My first Question: how to Custom Button (has two TextFields) on Android I extended a class form LinearLayout, and I add two buttons in it(width- fill_parent, weight-1). But they can't place right. If I use LinearLayout insteadof my customClass, it is working right. What Should I do?? This is my class public class SplitButtonController extends LinearLayout implements OnClickListener { // Toggle buttons private Vector<XButton2> buttons; // Listener private OnClickListener listener; public SplitButtonController(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.xbutton2, this); } public SplitButtonController(Context context) { super(context); } @Override protected void onFinishInflate() { super.onFinishInflate(); init(); } /** * Initialize the toggle buttons (set images and listeners). It's * responsibility of the user call this method after he add a ne */ public void init() { buttons = new Vector<XButton2>(); addLayoutButtons(); changeButtonsImage(); setListeners(); } private void addLayoutButtons() { int n = getChildCount(); for (int i = 0; i < n; i++) { View v = getChildAt(i); if (v instanceof XButton2) { buttons.add((XButton2) v); } } } private void changeButtonsImage() { if (buttons.size() > 1) { buttons.get(0) .setBackgroundResource( com.matriksdata.bavul.R.drawable.schedule_left_button_drawable); for (int i = 1; i < buttons.size() - 1; i++) { // buttons.get(i).setBackgroundResource(R.drawable.schedule_left_button_drawable); } buttons.get(buttons.size() - 1) .setBackgroundResource( com.matriksdata.bavul.R.drawable.schedule_right_button_drawable); } else { // TODO:set an image with rounded sides } } private void setListeners() { for (int i = 0; i < buttons.size(); i++) { buttons.get(i).setOnClickListener(this); buttons.get(i).setFocusable(true); } } @Override public void onClick(View v) { for (int i = 0; i < buttons.size(); i++) { XButton2 b = buttons.get(i); b.setChecked(v == b); } } } A: The buttons you added to your SplitButtonController are XButton2, and in your constructor, you are inflating R.layout.xbutton2. This will cause an empty "XButton2" added to your SplitButtonController layout. You don't need to inflate anything if you want to create (or extend) a simple LinearLayout. Then your SplitButtonController code should look like following: public class SplitButtonController extends LinearLayout implements OnClickListener { // Toggle buttons private Vector<XButton2> buttons; // Listener private OnClickListener listener; public SplitButtonController(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onFinishInflate() { super.onFinishInflate(); init(); } /** * Initialize the toggle buttons (set images and listeners). It's * responsibility of the user call this method after he add a ne */ public void init() { buttons = new Vector<XButton2>(); addLayoutButtons(); changeButtonsImage(); setListeners(); } private void addLayoutButtons() { int n = getChildCount(); for (int i = 0; i < n; i++) { View v = getChildAt(i); if (v instanceof XButton2) { buttons.add((XButton2) v); } } } private void changeButtonsImage() { if (buttons.size() > 1) { buttons.get(0) .setBackgroundResource( com.matriksdata.bavul.R.drawable.schedule_left_button_drawable); for (int i = 1; i < buttons.size() - 1; i++) { // buttons.get(i).setBackgroundResource(R.drawable.schedule_left_button_drawable); } buttons.get(buttons.size() - 1) .setBackgroundResource( com.matriksdata.bavul.R.drawable.schedule_right_button_drawable); } else { // TODO:set an image with rounded sides } } private void setListeners() { for (int i = 0; i < buttons.size(); i++) { buttons.get(i).setOnClickListener(this); buttons.get(i).setFocusable(true); } } @Override public void onClick(View v) { for (int i = 0; i < buttons.size(); i++) { XButton2 b = buttons.get(i); b.setChecked(v == b); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7526570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can i create circles in a image ....not using plot function? basically, i am supposed to create a image with circles and lines... not using plot function. because the final output is to pop out by imshow().or image().or imagesc()... and the created image will contiune the color processing. A: The simplest way is to draw it as usual, then use getframe to grab an image of the figure. EDIT: I don't have time for much detail, but look at the following: * *line: http://www.mathworks.co.uk/help/techdoc/ref/line.html *circle: http://www.mathworks.com/matlabcentral/fileexchange/2876 *axis properties: http://www.mathworks.co.uk/help/techdoc/ref/axes_props.html (You may want to set 'Visible', 'off', 'Position', [0 0 1 1], 'DataAspectRatio', [1 1 1]) *getframe: http://www.mathworks.co.uk/help/techdoc/ref/getframe.html The MATLAB help is really very useful. A: If you are trying to draw lines and circles directly on a raster image (matrix of pixels), then check out the Bresenham line-drawing algorithm and its variants for circles. I am sure you can find existing implementations for them on FEX Another possibility is to show the image (IMSHOW, IMAGESC, ..), use the plotting functions as usual (PLOT, LINE, ...), then grab the displayed figure as image again using GETFRAME as Nzbuu suggested. A: Use the matlab function "rectangle" and specify the 'Curvature" parameter to one. i.e. rectangle('Position',[0 0 100 100],'Curvature',[1 1]) This is obviously counter intuitive, but in Matlab, rectangle is the function you use to draw ellipses and circles. Here is the appropriate mathworks doc: http://www.mathworks.com/help/techdoc/ref/rectangle.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7526572", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Air AutoUpdate & Windows 7 pin icon I've created an Air app for use in work. To make things slightly easier, I pin the icon to taskbar (Windows 7). The app uses the auto-update framework (default), which works fine. After I update though, the pinned icon becomes a default blank page icon. If I click on this icon, Windows will tell me that it can't find the program. I need to unpin the icon and repin a new one (the icon in the start menu works fine). Anyone else have this problem and know how to fix it? I'm using AIR 2.7 (compiling with the Flex 4.1 SDK) and I'm on Windows 7 64 bit if that helps. A: A workaround would be to wrap your app inside another app as a module and only update that module. That way only the module SWF would be overwritten, leaving the original app intact. A: Resurrecting an old question. After digging around with pretty specific questions on Google, I found 2 posts, one in the Adobe forums: http://forums.adobe.com/message/3449244 and the other in the JIRA: https://bugs.adobe.com/jira/browse/SDK-24649 It looks like this bug has been open for a while and isn't getting fixed any time soon.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django-Admin.py not working I'm a complete noob at django and i cant seem to get the admin page up and running. I've set the urls.py correctly, and i've enabled the app in the settings.py module...all the database settings are correctly defined. Help please The error thrown is as shown below Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin Django Version: 1.3 Python Version: 2.7.1 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin'] Installed Middleware: ('django.middleware.common.CommonMiddleware', ' jango.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 89. response = middleware_method(request) File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py" in process_request 67. if (not _is_valid_path(request.path_info, urlconf) and File "/usr/local/lib/python2.7/dist-packages/django/middleware/common.py" in _is_valid_path 154. urlresolvers.resolve(path, urlconf) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 342. return get_resolver(urlconf).resolve(path) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve 250. for pattern in self.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _get_url_patterns 279. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in _get_urlconf_module 274. self._urlconf_module = import_module(self.urlconf_name) File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in import_module 35. __import__(name) File "/home/mjanja/workspace/DjangoProjectsLinux/ModelsDemo/../ModelsDemo/urls.py" in <module> 16. url(r'^admin/', include(admin.site.urls)), Exception Type: NameError at /admin Exception Value: name 'admin' is not defined A: you are most probably missing the following lines @ the beginning of urls.py: # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() A: seems like you may have forgotten to uncomment a few lines in the default urls.py in the project root. check the urls.py in the project root, it should at least have the following: from django.conf.urls.defaults import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), ) Also, i see a missing "d" for "django" in your settings.py above for the line: ' jango.contrib.sessions.middleware.SessionMiddleware' A: This is pretty old, but I noticed that in the list of installed middleware, one line is missing the 'd' in 'django' Installed Middleware: ('django.middleware.common.CommonMiddleware', ' jango.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware',
{ "language": "en", "url": "https://stackoverflow.com/questions/7526581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: not able to play audio from internet using AVAudioPlayer i tried to play an audio file from internet using AVAudioplayer but there is no response from UIView but if i m to play an mp3 file from bundle it works ..cud u guys help me out below is the code... -(IBAction)playPause:(id)sender { NSURL *url=[NSURL URLWithString:@"http://www.1040communications.net/sheeba/stepheni/iphone/images/today.mp3"]; NSError *error; player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error]; if (!player) NSLog(@"Error: %@", error); [player prepareToPlay]; [player play]; } A: The URL has to be a file URL, see Apple’s Technical QA1634. You can download the file to the device and then play it locally. A: your url is not returning any data.That's why it is not playing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the duration of "pointer not aliased by any other pointer" implication? Currently Visual C++ is shipped with runtime where malloc() is decorated with __declspec( restrict ). MSDN says this decoration states to the compiler that a pointer returned by malloc() cannot be aliased by any other pointer. Okay, two subsequent calls to malloc() indeed return distinct pointers. But what happens if I call void* memory1 = malloc( 10 ); free( memory1 ); void* memory2 = malloc( 10 ); //here memory1 may be equal to memory2 In this case the two pointers can point to the very same location. How does this correlate with cannot be aliased by any other pointer implication of __declspec( restrict )? A: Because once you free(memory1), accessing anything via the memory1 pointer is undefined behavior (nasal demons, and so forth), and hence the compiler can optimize assuming that memory2 is not aliased by any other pointer after the malloc() call. As for why this matters, assuming the compiler itself has no internal information about the semantics of malloc(), i.e. that it treats it just like any other function, then it cannot assume that the pointer returned is not aliased by any other pointer. The __declspec(restrict) (or equivalently, __attribute__((malloc)) in GCC) tells the compiler that the pointer is not aliased by any other pointer, which allows some optimizations not possible otherwise. A: The standard has this to say about "object lifetime" (§3.8 in N3290): The lifetime of an object of type T ends when: — if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or — the storage which the object occupies is reused or released. After you've free'd the block pointed to by memory1, that object is dead. It has ceased to exist. Dereferencing that pointer would be undefined behavior. memory2 could be assigned the same memory address, but it wouldn't "alias" anything: what was at that location has passed away.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to keep the VBScript command window open during execution When I execute a VBScript, the command window that it creates closes quickly before the user gets a chance to read the output. How can I get the window to stay open without modifying windows registry? This is the code: Set objShell = WScript.CreateObject("WScript.shell") objShell.Run "SyncToyCmd.exe -R", 1, True A: Assuming that it's the popped-up command window that you want to keep open (rather than the one running your VBScript), you can use CMD.exe's Pause command to achieve this: Set objShell = WScript.CreateObject("WScript.shell") objShell.Run "cmd.exe /C ""SyncToyCmd.exe -R & Pause"" ", 1, True A: You can send your execution command through the cmd.exe command interpreter, along with a pause command which will give the user a Press any key to continue . . . prompt to close the window. objShell.run "%comspec% /c ""SyncToyCmd.exe -R & pause""", 1, True Or to keep the window alive, use the /k flag instead of /c: objShell.run "%comspec% /k SyncToyCmd.exe -R", 1, True But beware, your VBScript will not continue (or terminate) until this cmd window is manually closed. The %comspec% environment variable refers to the correct command to open the command interpreter as per your operating system. On my XP machine, for instance, %comspec% is equal to C:\WINDOWS\system32\cmd.exe. See cmd.exe documentation here: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true More info on the use of the & versus the && command separators here. A: Make it sleep for a while, maybe tell the user it will close in 5 seconds? Set WScript = CreateObject("WScript.Shell") WScript.Sleep 5000
{ "language": "en", "url": "https://stackoverflow.com/questions/7526598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: How to define foreign key, index constraints in my migration script How should I define foreign key, index constraints in my db migration script for my Rails app in a 2.3.x environment? A: ActiveRecord doesn't support adding foreign keys in a database-agnostic way, so you'll need to do this with DB-specific code. Here's an example for MySQL: class AddForeignKeyToUsers < ActiveRecord::Migration def self.up execute 'alter table users add constraint user_role foreign key user_role_idx (role_id) references roles (id) on delete set null on update cascade' end def self.down execute 'alter table users drop foreign key user_role' end end For indexes, you can use add_index - like so: add_index(:users, :name) Edit: Updated answer to clarify that indexes and foreign keys are treated differently.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .setAttribute("disabled", false); changes editable attribute to false I want to have textboxes related to radiobuttons. Therefore each radio button should enable it's textbox and disable the others. However when I set the disabled attribute of textbox to true, it changes the editable attribute too. I tried setting editable attribute true again but it did not work. This was what I tried: JS function: function enable(id) { var eleman = document.getElementById(id); eleman.setAttribute("disabled", false); eleman.setAttribute("editable", true); } XUL elements: <radio id="pno" label="123" onclick="enable('ad')" /> <textbox id="ad" editable="true" disabled="true" flex="1" emptytext="asd" onkeypress="asd(event)" tooltiptext="" > A: the disabled attributes value is actally not considered.. usually if you have noticed the attribute is set as disabled="disabled" the "disabled" here is not necessary persay.. thus the best thing to do is to remove the attribute. element.removeAttribute("disabled"); also you could do element.disabled=false; A: just replace 'myselect' with your id to disable-> document.getElementById("mySelect").disabled = true; to enable-> document.getElementById("mySelect").disabled = false; A: An update in 2022. There is another method toggleAttribute() more specific to this use case if you don't need to consider IE11 and other legacy browsers. element.toggleAttribute("disabled"); switches between <input value="text" disabled /> and <input value="text" />, and moreover, element.toggleAttribute("disabled", true); sets <input value="text" disabled /> explicitly, no matter what state the element was; similarly, element.toggleAttribute("disabled", false); sets <input value="text" /> explicitly. A: A disabled element is, (self-explaining) disabled and thereby logically not editable, so: set the disabled attribute [...] changes the editable attribute too Is an intended and well-defined behaviour. The real problem here seems to be you're trying to set disabled to false via setAttribute() which doesn't do what you're expecting. an element is disabled if the disabled-attribute is set, independent of it's value (so, disabled="true", disabled="disabled" and disabled="false" all do the same: the element gets disabled). you should instead remove the complete attribute: element.removeAttribute("disabled"); or set that property directly: element.disabled = false; A: Just set the property directly: . eleman.disabled = false; A: Using method set and remove attribute function radioButton(o) { var text = document.querySelector("textarea"); if (o.value == "on") { text.removeAttribute("disabled", ""); text.setAttribute("enabled", ""); } else { text.removeAttribute("enabled", ""); text.setAttribute("disabled", ""); } } <input type="radio" name="radioButton" value="on" onclick = "radioButton(this)" />Enable <input type="radio" name="radioButton" value="off" onclick = "radioButton(this)" />Disabled<hr/> <textarea disabled ></textarea> A: Try doing this instead: function enable(id) { var eleman = document.getElementById(id); eleman.removeAttribute("disabled"); } To enable an element you have to remove the disabled attribute. Setting it to false still means it is disabled. http://jsfiddle.net/SRK2c/ A: There you go, <div immutable='id,class' id='abc' class='xyz'></div> <h1 immutable='onclick' onclick='alert()'>HI</h1> <p immutable='id' subtree> <!-- now childs id are immutable too --> <span id='xyz'>HELLO</span> </p> </script> const mutationHandler = entries => { entries.forEach(entry => { if (entry.type !== 'attributes') return; mutationObserver.disconnect() entry.target.setAttribute(entry.attributeName, entry.oldValue) observe() }) } const mutationObserver = new MutationObserver(mutationHandler) const observe = () => { let items = document.querySelectorAll('[immutable]'); items.forEach(item => { let subtreeEnabled = item.getAttribute('subtree') != null let immutableAttr = item.getAttribute('immutable') let captureAttrs = immutableAttr.split(','); captureAttrs.push('immutable') captureAttrs.push('subtree') mutationObserver.observe(item, { subtree: subtreeEnabled, attributes: true, attributeOldValue: true, attributeFilter: captureAttrs }) }) } observe() </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7526601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "91" }
Q: how to get a single gps fix in android? I have a program that requires a single GPS fix when a service is started. This is needed to tell an on location change when the last location is. How to get 1 single GPS fix in an android service? A: Ive found a way! all i did was defined a boolean StartUp then made this true in oncreate then if (StartUp = true){ DistanceMoved=1000000f; StartUp=false;} this will work if your location is done with distance moved.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526606", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Testing ServiceLoader in Eclipse Plugins I have four Eclipse plugin projects (create a new Java Project, right-click, configure, Convert to Plugin Project) in my workspace. The first (my.runtime) contains an interface (MyFactoryInterface) and a class (MyClient) that defines a method (List<String> getAllFactoryNames()) that loads all implementations of that interface via java.util.ServiceLoader and calls a method (String getName()) on them, collecting the results and returning them in a list. To test that class, I have a JUnit test in the second project (my.runtime.test, set up with my.runtime as Fragment-Host), checking if the name returned by a dummy implementation(MyDummy, returning "Dummy") I have in the my.runtime.test project is in the list returned by MyClient.getAllFactoryNames(). So far, it works fine. In the third project (my.extension, with my.runtime as dependency) I have a class (MyHello) that uses the names returned by MyClient.getAllFactoryNames() to return a list of greetings ("Hello "+name). Again, to test this, I have a project (my.extension.test, with my.extension as Fragment-Host) containing another Implementation (MyWorld, returning "World" as name) and a JUnit test case checking if "Hello World" is in the greetings returned by MyHello.getGreetings(). This test fails, as MyClient still only finds the MyDummy implementation, and not the MyWorld implementation. Both implementations are accompanied by matching entries in META-INF/services/my.runtime.MyFactoryInterface files. I currently use the following code to load the implementations: ServiceLoader<MyFactoryInterface> myFactoryLoader = ServiceLoader.load(MyFactoryInterface.class); for (MyFactoryInterface myFactory : myFactoryLoader) { I know that I can supply a ClassLoader as a second argument to ServiceLoader.load, but I have no idea how to get one that knows all plugin projects... any suggestions? Or is ServiceLoader not the right tool for this problem? A: If anyone stumbles over the same problem: the combination of ServiceLoader.load(MyFactoryInterface.class, Thread.currentThread().getContextClassLoader()) in MyClient and Thread.currentThread().setContextClassLoader(MyWorld.class.getClassLoader()); in the second test did the job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7526615", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: explode function and array element reading Possible Duplicate: php explode and array index I am new to PHP and would like to ask if there is a way to write a php code like $lengthofstay = ($duration <= 0 ? 'optional' : explode("_", $duration )[0]); i mean calling the explode function and at the sametime reading the first element of resulting array. A: it would be possible in 5.4 but your code is as ugly as hell. there is nothing good in writing all the code in one line. Write in in three lines and when you come across it in a week, you wouldn't stumble upon it, puzzled. if ($duration <= 0) $lengthofstay = 'optional'; } else { list($lengthofstay) = explode("_", $duration, 1); } nothing wrong with it. if you want to make it strictly one-liner - create a function. and then call it $lengthofstay = get_length_of_stay($duration); it's shorter than your cunning construct and way more readable A: You might want to use the limit-parameter from explode: explode("_", $duration, 1)
{ "language": "en", "url": "https://stackoverflow.com/questions/7526616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }