text
stringlengths
8
267k
meta
dict
Q: Error in CreateProcessW: cannot convert parameter 9 from 'STARTUPINFO' to 'LPSTARTUPINFO &' I understand that startup_info is a pointer to a STARTUPINFO structure I have a function which I pass startup_info by reference into it. So we can say that I am passing a pointer by reference void cp(....., LPSTARTUPINFO & startup_info) { CreateProcessW(....., startup_info); } Let us assume that I call function cp in this function caller() void caller() { STARTUPINFO startup_info; cp(....., startup_info); // error occurs here, I cannot convert 'STARTUPINFO' to 'LPSTARTUPINFO &' } It will give me error message: Error in CreateProcessW: cannot convert parameter 9 from 'STARTUPINFO' to 'LPSTARTUPINFO &' But since statup_info is a pointer, I should be able to pass this into function cp right? EDIT: Thank you for your advices,but the following works for me: LPSTARTUPINFO is a pointer to STARTUPINFO structure So I change to void cp(....., LPSTARTUPINFO startup_info_ptr) { CreateProcessW(....., startup_info_ptr); // pass in pointer of startup_info } void caller() { STARTUPINFO startup_info; cp(....., &startup_info); // passing the address of startup_info } A: You've got two startup_info's. In caller(), it's a STARTUPINFO (not a pointer). In cp(), it's a STARTUPINFO*& (reference to a pointer). Why? It's most likely unintentional. I'd expect: void cp(....., STARTUPINFO* pStartup_info) { CreateProcessW(....., pStartup_info); } void caller() { STARTUPINFO startup_info; cp(....., &startup_info); } In production code, I avoid p prefixes for pointers but I've used it here to disambiguate the two startup_info's which you had.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CakePhp: How to know the current local in the model? I've to develop a small website which is multi-lingual. This website is using an ERP database, so I cannot choose my database structure, ... My application has the default language in the core.php, and I'm using I18N Through URL to specify which language I've to display For every different language, I've a different table containing the description of products in the right language. So I need to set the "$useTable" of cakePhp in the constructor to the right table. But to do this, I need to know the current locale of the application. I tried several things: * *do a getInstance on the I18n class, but I've always "english" as "lang" *doing a Configure::read('Config.language'), but this only displays me the default language of the cakePhp *I tried to read the $GLOBALS['Dispatcher']->$params['language'] but if the user didn't specify any local, I don't get any *I tried to import the Component Session and read the Config.language value(which I'm writing on the app_controller), but I seems that If I'm on a french page, I click on the link to display the page in german(all texts are in german now), but the value I receive here is still in french, if I refresh the page, I finally got German, but I need to get the value now, not on the next page reload So I don't see how to retrieve this language, is there an hidden field containing this var, or anywhere I could retrieve this info? A: I didn't found any easy way to retrieve this var, and because we are called before the _beforeFilter, I've to check parameter, session, cookies and default var. So I created a method, I put it in my "Tools" component, and I import it in my model. Here is the model if you're interessted: function GetCurrentLocale(){ if(isset($GLOBALS['Dispatcher']->params['language'])) return $GLOBALS['Dispatcher']->params['language']; if($this->Session->check('Config.language')) return $this->Session->read('Config.language'); if($this->Cookie->read('lang')!==false)return $this->Cookie->read('lang'); return Configure::read('Config.language'); } And I'm calling it like this: App::import('component','Tools'); $tools = new ToolsComponent(); $locale = $tools->GetCurrentLocale(); If someone find a best way, I will be strongly interessted to see how :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7565692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regular Expression to check String is valid XHTML or not Possible Duplicate: regular expression to check if string is valid XML I am looking Regular Expression to check String is Valid XHTML or not example <h2>Legal HTML Entity References</h2><table align="center" border="0" ><tr></tr></table> A: This sounds like a bad idea: The language of valid XHTML strings is not regular. Use an HTML parsing library instead. A few examples: * *JTidy *TagSoup *HTMLParser Related question: * *When should I not use regular expressions? A: Regex is exactly the wrong tool to use. HTML is not a regular language and hence cannot be parsed by regular expressions. See Jeff's post on the subject here: http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html Since you've tagged this post Java, you should look at using one of the myriad of HTML parsing libraries available. A: Have a look here why parsing HTML using regular expressions won't work reliably: RegEx match open tags except XHTML self-contained tags XHTML is just another flavor/superset of HTML, so you're better of using a real validator, like JTidy etc. A: Try to check it with a parser. Don't do it the Cthulhu Way. Here you can find a strating point and some examples on how to do it: The Java XML Validation API
{ "language": "en", "url": "https://stackoverflow.com/questions/7565696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: replace image in local folder with URL coming from web service Possible Duplicate: android: webservice image replace with images in Local folder How can I replace an image in local folder with the URL received from web service. Please provide me a sample code or a simple example. Guide me in this issue. Thanks in advance. Regards A: URL url="http://...."; String FILENAME; InputStream input=new InputStream(url.openConnection() BufferedInputStream bis = new BufferedInputStream(input); fileDest=new File(FILENAME); if ( fileDest.exists() ){ if ( ! fileDest.delete() ) throw new Exception ( "impossible to delete "+ fileDest.getName()); } FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(bis.getBytes()); fos.close(); I guess you can start with this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JMS implementation using JNDI in spring application I am trying to implement JMS in my spring application. I have defined the JNDI name + queue name in applicationContext.xml as follows: <bean id="emailQueueConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean" lazy-init="true"> <property name="jndiName" value="java:comp/env/jms/<<Name of JNDI of connection factory>>" /> </bean> <bean id="emailQueueDestination" class="org.springframework`enter code here`.jndi.JndiObjectFactoryBean" lazy-init="true"> <property name="jndiName" value="java:comp/env/jms/<<JNDI name of queue>>" /> </bean> <bean id="emailQueueTemplate" class="org.springframework.jms.core.JmsTemplate" lazy-init="true"> <property name="connectionFactory" ref="emailQueueConnectionFactory" /> <property name="defaultDestination" ref="emailQueueDestination" /> </bean> <bean id="emailSender" class="<<Package>>.EmailSender" lazy-init="true"> <property name="jmsTemplate"> <ref bean="emailQueueTemplate" /> </property> </bean> Now my controller makes a call to the emailSender bean using the following code: ApplicationContext context = new ClassPathXmlApplicationContext("/applicationContext.xml"); EmailSender sender =(EmailSender)context.getBean("emailSender"); The exception I get is: Error 404: Request processing failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist I am loading the applicationContext.xml at serevr start-up still my code is not able to locate this file. Can anyone please help.?? A: make sure your applicationContext.xml file is in your class path then add the class path prefix, You can try some thing like this ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
{ "language": "en", "url": "https://stackoverflow.com/questions/7565700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to execute commands with Android SDK like a terminal? I want to develop a terminal app in Android. In C#, we have: System.Diagnostics.Process.Start("path of aplication") Its like running a program directly because each command is a program in Windows. I don't know how it works in Linux. A: Use ProcessBuilder to create OS processes. A: I find other solution, thank for all guys http://saurabh-nigam.blogspot.com/2010/10/running-android-native-code.html this project make the same: https://github.com/gimite/android-native-exe-demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7565701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to use uddi in .Net I have used web services in .Net before with WCF.Though, I don't really understand the benefits of UDDI. There is a lot of theory but I didn't find anything practical. Do you know any tutorials on using UDDi in .NET? A: Found an example of UDDI in .Net Another example about UDDI based enterprise SOA from codeproject MSDN articles Part 1 and Part 2 A: jUDDI has a .net port for accessing UDDI resources. http://svn.apache.org/repos/asf/juddi/trunk/juddi-client.net/
{ "language": "en", "url": "https://stackoverflow.com/questions/7565702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is there an atomic_add() function on android i need atomic addition on android, but i can't find it . In asm/atomic.h file, it just have only ATOMIC_INIT(i) macro definition . A: If you write code in C/C++ then you can use the GNU compiler builtins for atomic ops A: I am not sure if you mean that you need this in native code, but if you don't, then I'd point out AtomicInteger from Java / Android libraries provides addAndGet().
{ "language": "en", "url": "https://stackoverflow.com/questions/7565703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Display data with 'yes' or 'no' entries unique. This is my data unitCode stunum assNo subStatus SIT111 1000 1 Yes SIT111 1000 2 No SIT111 3000 1 No How do i generate only results with ONLY a 'No' eg: Only student 3000 should come up. Since that person has not handed in ANY assignments. ? A: You can use the following statement: select * from ( select unitCode, stunum, sum(case when subStatus = 'Yes' then 1 else 0 end) as CountYes, sum(case when subStatus = 'No' then 1 else 0 end) as CountNo from students group by unitCode, stunum ) as student inner join student_details on student.stunum = student_details.stunum where CountNo > 0 and CountYes = 0; A: declare @T table ( unitCode varchar(10), stunum int, assNo int, subStatus varchar(3) ) insert into @T values ('SIT111', 1000, 1, 'Yes'), ('SIT111', 1000, 2, 'No'), ('SIT111', 3000, 1, 'No') select * from @T as T where T.subStatus = 'No' and T.stunum not in (select stunum from @T where subStatus = 'Yes')
{ "language": "en", "url": "https://stackoverflow.com/questions/7565716", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VB6 Winsock Error Invalid Argument 10014 Private Sub Form_Load() Winsock1.RemotePort = 22222 Winsock1.Protocol = sckUDPProtocol End Sub Private Sub Command1_Click() Command1.Enabled = False Dim sendBuff As String sendBuff = "XXXXX" Label1: On Error GoTo Label2 Winsock1.RemoteHost = "andon-eds-1" Winsock1.SendData sendBuff Label2: Winsock1.Close Winsock1.Protocol = sckUDPProtocol Winsock1.RemotePort = 22222 Winsock1.LocalPort = 0 Label3: On Error GoTo EndOfSub Winsock1.RemoteHost = "andon-eds-1" Winsock1.SendData sendBuff EndOfSub: Command1.Enabled = True End Sub Private Sub Command2_Click() Command2.Enabled = False On Error GoTo EndOfSub Winsock1.RemoteHost = "andon-eds-1" Winsock1.SendData "XXXXX" EndOfSub: Command2.Enabled = True End Sub Private Sub Command3_Click() On Error Resume Next Command3.Enabled = False Dim sendBuff As String sendBuff = "XXXXX" PrintWinsockProperty Winsock1.RemoteHost = "andon-eds-1" Winsock1.SendData sendBuff PrintWinsockProperty Winsock1.Close Winsock1.Protocol = sckUDPProtocol Winsock1.RemotePort = 22222 Winsock1.LocalPort = 0 PrintWinsockProperty Winsock1.RemoteHost = "andon-eds-1" Winsock1.SendData sendBuff PrintWinsockProperty Command3.Enabled = True End Sub 'the host name "andon-eds-1" is not online and i want my application can continues * *when i click Command1 i found an error Invalid Argument : 10014 at >>Winsock1.SendData sendBuff << below Label3 my application cannot continues *when i click Command2 2 times it can continues without application close *when i click Command3 it can continues without application close my question are what's the difference between 1.) and 2.) ? and what's difference between On Error Resume Next and On Error GoTo for my problem ? (** i'm sorry about my english skills) thanks Private Sub Command6_Click() Dim i As Integer Command6.Enabled = False On Error GoTo BeginLoop Winsock1.RemoteHost = "Andon-eds-1" Winsock1.SendData "XXXXX" BeginLoop: Resume Next For i = 0 To 2 Winsock1.RemoteHost = "Andon-eds-" & i Winsock1.SendData "XXXXX" Debug.Print Err.Number '0 '0 '0 Next On Error GoTo TestLabel i = 100 / 0 Command6.Enabled = True Exit Sub TestLabel: End Sub A: I'm not sure what you are trying to do with the code so I can't answer your entire question but I can answer this part of your question: What's the difference between On Error Resume Next and On Error GoTo. Resume next will cause execution to go on to the next line of code if an error happens. For On Error GoTo, that will take your code to the label specified after the GoTo in the section of code that follows the On Error GoTo. A: Error 10014 (WSAEFAULT) is Bad Address The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr). Check that the machine "andon-eds-1" can be pinged ok
{ "language": "en", "url": "https://stackoverflow.com/questions/7565720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Select all string and focus when document is ready I want to select the input when document is ready. I mean input value must be like highlighted and when I click any button from keyboard input's value should be delete. How can i do this with jquery? <input type="text" class="myText" value="First Name"></input> A: Give the text box an ID and use the focus and select methods: <input id="myTextBox" type="text" class="myText" value="First Name"></input> $(document).ready(function () { $("#myTextBox").focus().select(); }); JSFiddle here A: By giving input an id $(document).ready(function(){ $("#input_id").focus(); $("#input_id").select(); }); should do it Best Regards A: try it out $(document).ready(function(){ $('input[type="text"]').focus().select(); $('input[type="text"]').click(function() { $('input[type="text"]').val('');; }); })
{ "language": "en", "url": "https://stackoverflow.com/questions/7565721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: invalidate nstimer in objective-c iphone I am having issue with invalidating a NSTimer. I initialize a NSTimer with below function. -(void) initLTTimer{ [self shutLTTimer]; [self setQuestion:questionCounter]; isQuestionAttempt=NO; tmLeftTime=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLeftTime:) userInfo:nil repeats:YES]; NSLog(@"Timer Initialized"); } further I called a function updateLeftTime in its selector. - (void)updateLeftTime:(NSTimer *)theTimer { NSLog(@"%d",timeCounter); timeCounter+=1; tfLeftTime.text=[NSString stringWithFormat:@"%d", (QUESTION_TIME_LIMIT-timeCounter)]; if (timeCounter>=QUESTION_TIME_LIMIT) { if (isQuestionAttempt==NO) { [self increaseDropShots]; } [self setQuestionBg]; timeCounter=0; [self shutLTTimer]; [self updateQuestion:nil]; } } This function [self increaseDropShots]; called in above function. here is the code of this function -(void)increaseDropShots { NSString *imgName = @"DactiveRetake"; if (IS_IPAD) { imgName = [imgName stringByAppendingString:@"_ipad"]; } wrongAttemp+=1; for (int i =1; i<=wrongAttemp; i++ ) { UIImageView *img=(UIImageView *)[self.view viewWithTag:i+50]; [img setImage:[UIImage imageNamed:imgName]]; } NSLog(@"Question dropped counter: %d",wrongAttemp); if (wrongAttemp == 3) { [self shutLTTimer]; [CommonFunctions initGlobalVars]; [Bgplayer stop]; [Bgplayer release]; OverPageViewController *opvc=[[OverPageViewController alloc] initWithNibName:[CommonFunctions getXIBFile:@"OverPageViewController"] bundle:[NSBundle mainBundle]]; [self.navigationController pushViewController:opvc animated:YES]; [opvc release]; } } In this function I am killing this timer but I am unable. -(void) shutLTTimer{ if ([tmLeftTime isValid]) { [tmLeftTime invalidate]; tmLeftTime=nil; } } This is the whole scenario of my application Please help me what is the issue. A: Answered after conversation in comments Does the code definitely get to the line, [tmLeftTime invalidate];? You can check this by using a breakpoint or an NSLog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Writing Details into a File I am trying to write into a file work/log_file.txt upon submitting a page work/login.php. But the contents (form values from login.php) are not getting written. This is the code I used if(isset($_POST['submitform'])){ $file="log_file.txt"; $open = fopen($file, "a+"); //open the file, fwrite($open, "Name: " .$_POST['user'] . "\n"); //print / write the name. fwrite($open, "Colour: ". $_POST['color'] . "\n"); //print / write the colour. fclose($open); //close the opened file } I am running the code in a test server. I just saved file as log_file.txt in local and then uploaded it to test server folder work ,and run the code. But not getting written to the file A: Does the web server process have write permissions for the file? Tip that will serve you well: turn on all errors while debugging: ini_set('display_errors',1); error_reporting(E_ALL); Any number of things could be off, but you'll never know unless you see the notices and warnings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565724", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CALL_PHONE vs CALL_PHONE_PRIVLEGED What is difference between permissions CALL_PHONE and CALL_PHONE_PRIVLEGED. After reading there definitions it appears they do more or less the same things. CALL_PHONE: Allows an application to initiate a phone call without going through the Dialer user interface for the user to confirm the call being placed. CALL_PRIVILEGED: Allows an application to call any phone number, including emergency numbers, without going through the Dialer user interface for the user to confirm the call being placed. Can someone please explain the minute difference between the two? A: any phone number, including emergency numbers "Can dial 911" (or other emergency numbers, as valid in the specific location - e.g. 112 in EU) You probably don't want just any ol' app calling the police of its own accord.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: The support of the CPAN There is a great thing in a Perl world: CPAN. http://www.cpan.org/ But I can't find any support forum or discussion board or any bugtracker for CPAN itself. Is there any? A: The backend, PAUSE, is maintained at https://github.com/andk/pause. The miscellaneous static files of CPAN are maintained at https://github.com/perlorg/cpanorg. Work on CPAN is coordinated through the cpan-workers list. When you have problems with CPAN or PAUSE, use the lists module-authors (community support) or modules (PAUSE admins). A: Every CPAN module has a bugtracker at http://rt.cpan.org/ (but it's worth checking the documentation for the module as not all authors want to use it). There's a discussion forum for CPAN modules at http://cpanforum.com/ - but it's rather underused. A: CPAN is generally accessed through a variety of means, the most common of which is the CPAN.pm module, which has a Request Tracker that can be used for bugs here: https://rt.cpan.org/Public/Dist/Display.html?Name=CPAN. A website commonly used to search CPAN, http://search.cpan.org/, is a closed-source site which does not have any community bugtracker. It does have a feedback page if you want to send comments or bug reports to its maintainer. Another common website used to search CPAN is http://metacpan.org/, which has its own github entry for bug reports. A: It appears you're after the PAUSE FAQ http://pause.perl.org/pause/query?ACTION=pause_04about#upload Please, make sure the filename you choose contains a version number. For security reasons you will never be able to upload a file with identical name again....
{ "language": "en", "url": "https://stackoverflow.com/questions/7565728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: localitics & comScore memory leaks I'm using Localitics and ComScore libs for collecting some statistic for my app. And I have a problem with memory leaks. If any body use such libs, and know how to solve this problem. Or, maybe, it's not a problem? in more details: after, when i commented // [[LocalyticsSession sharedLocalyticsSession] startSession:LOCALYTICS_KEY]; // [[CSComScore census] notifyStart:COMSCORE_ACCOUNT_ID andSecret:COMSCORE_SECRET]; in didFinishLaunchingWithOptions in my appDelegate, all leaks disappear. update * *comScore * *I'm using only base functions: in app there no code related to comScore except "notifyStart". *localitics * *I used http://www.localytics.com/documentation/iphone-integration/ for integration this lib. My appDelegate looks exactly as said in instruction. for loging i'm using - -(void)viewDidAppear:(BOOL)animated { [[LocalyticsSession sharedLocalyticsSession] tagScreen:@"Near Me."]; //here I have warning: ... may not respond to ... } here you have screen shot of my Performance tool: hope it will help. A: I am not sure exaclty what is wrong with your memory there. I use touchwizards.com for analysis, it has some great interaction analysis for iOS like heatmaps and more
{ "language": "en", "url": "https://stackoverflow.com/questions/7565730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: MYSQL using temporary when Group By I have this query: SELECT m.Number FROM table m WHERE m.IdA = _IdA AND m.IdB = _IdB AND m.IdC = _IdC GROUP BY m.Number ORDER BY m.Number; Where _IdA, _IdB & _IdC are the parameters. If I check it with EXPLAIN it says no using temporary, but if the values of those parameters doesn't return any row EXPLAIN says "using temporary" I'd like to avoid using temporary....Any ideas? A: Create a composite index (IdA, IdB, IdC, Number).
{ "language": "en", "url": "https://stackoverflow.com/questions/7565736", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: nginx+uwsgi+python2.7 come up with a bottleneck that can not pass 20000x40000 benchmarking i'm coming up with a bottleneck that my server can't pass a 20000x40000 benchmark test no matter what adjustments i made. the server have 128G Ram and with an Xeon 6 core cpu, centos5.6-64bit, in a good shape. i try combinations including: nginx + uwsgi + python2.7 nginx + apache + mod_wsgi + python2.7 apache + mod_wsgi + python2.7 none of them could make through the apache benchmarking: ab -c 20000 -n 40000 (without -k) and coincidentally, almost all tests failed around 32000 requests detail about nginx and uwsgi: nginx: worker_processes 24 use epoll worker_connections 65535 uwsgi: listen 2048 master true workers 24 uwsgi -x /etc/uwsgi_conf.xml --async 256 --file /var/www/example.py & anybody have any idea about it? thanks in advance to any possible solutions and suggestions A: Allowing such amount of concurrent connections on a single system requires a huge list of kernel tuning and probably you will never be able to manage such load in production. First of all you have to increase the number of ephemeral port, the socket backlog queue, the number of allowed file descriptor per process and so on... In addition to this (that should be already enough to stop such unrealistic test) you should increase the number of async core in uWSGI to 20k. Nothing wrong with taht (each core consume less than a page of memory), but you will end with at least 40k opened socket in your system. This is for nginx+uwsgi. With Apache you will end with 20k processes or threads, which is even worse than the 40k opened sockets.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using array with page slugs I'm using the following code to display images based on the category id: <?php if (is_category( 'web-design' )){ ?> <img src="<?php bloginfo('template_directory'); ?>/images/slider_webdesign.png" title="خدمات تصميم وتطوير المواقع" height="200px" width="960px" /> <?php }else if (is_category( 'printing' )){ ?> <img src="<?php bloginfo('template_directory'); ?>/images/slider_printing.png" title="تصميم مطبوعات" height="200px" width="960px" /> <?php }else if (is_category( 'online-marketing' )){ ?> I would like to make an array of only one condition to display an image with the category slug, is that possible? A: <?php $categories = array( 'web-design' => array( 'image' => 'slider_webdesign.png', 'title' => 'Title of image', 'height' => '200', 'width' => '960' ), 'template_directory' => array( 'image' => 'slider_printing.png', 'title' => 'Title of image', 'height' => '200', 'width' => '960' ) ); $category = false; /* following code might need rewriting since I'm not sure if this is the */ /* correct way of getting current category slug */ if (is_category()) { $slug = get_category(get_query_var('cat'))->slug; if (isset($categories[$slug])) { $category = $categories[$slug]; } } ?> <?php if ($category): ?> <img src="<?php bloginfo('template_directory'); ?>/images/<?=$category['image']?>" title="<?=$category['title']?>" height="<?=$category['height']?>" width="<?=$category['width']?>" /> <?php endif ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7565746", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 3d orthogonal projection on a plane I have a point in 3d P(x,y,z) and a plane of view Ax+By+Cz+d=0 . A point in plane is E.Now i want to project that 3d point to that plane and get 2d coordinates of the projected point relative to the point E. P(x,y,z) = 3d point which i want to project on the plane. Plane Ax + By + Cz + d = 0 , so normal n = (A,B,C) E(ex,ey,ez) = A point in plane ( eye pos of camera ) What i am doing right now is to get nearest point in plane from point P.then i subtract that point to E.I suspect that this is right ??? please help me.Thanks. A: The closest point is along the normal to the plane. So define a point Q that is offset from P along that normal. Q = P - n*t Then solve for t that puts Q in the plane: dot(Q,n) + d = 0 dot(P-n*t,n) + d = 0 dot(P,n) - t*dot(n,n) = -d t = (dot(P,n)+d)/dot(n,n) Where dot((x1,y1,z1),(x2,y2,z2)) = x1*x2 + y1*y2 + z1*z2 A: You get a point on the plane as p0 = (0, 0, -d/C). I assume the normal has unit length. The part of p in the same direction as n is dot(p-n0, n) * n + p0, so the projection is p - dot(p-p0,n)*n. If you want some coordinates on the plane, you have to provide a basis/coordinate system. Eg two linear independent vectors which span the plane. The coordinates depend on these basis vectors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to 'git pull' all the branches easily? git pull --help Incorporates changes from a remote repository into the current branch. I pull the git repository for offline view of the code and like to have the updated code for the different branches. How do I pull the code for all the branches easily without doing a pull for each branch manually? --all -- Fetch all remotes. --all didn't help. A: If the local repository is used for read only and none of the files are modified, then the below script will do the trick. for i in $(git branch | sed 's/^.//'); do git checkout $i; git pull; done There seems to be no git equivalent command for the same. A: Like Praveen Sripati's answer, but as a shell function and it brings you back to the branch you started on. Just put this in your ~/.bash_aliases file: function pull-all () { START=$(git branch | grep '\*' | set 's/^.//'); for i in $(git branch | sed 's/^.//'); do git checkout $i; git pull || break; done; git checkout $START; }; With the || break it does a satisfactory job not screwing things up if there's a conflict or the like. A: pull merges remote branches into your current local branch, so pulling all remote branches is probably not what you want. A: Inspired by @cellofellow I added this to my .profile on Mac OS X: function git-pull-all() { START=$(git symbolic-ref --short -q HEAD); for branch in $(git branch | sed 's/^.//'); do git checkout $branch; git pull ${1:-origin} $branch || break; done; git checkout $START; }; function git-push-all() { git push --all ${1:-origin}; }; The main differences are: * *I am getting the current branch with git branch | grep '\*' | set 's/^.//' instead of git branch | grep '\*' | set 's/^.//'. *You can supply a remote as a parameter e.g. git-pull-all origin. If you omit the parameter, it defaults to origin. *Also added a similar shortcut to push multiple branches back the server. A: If you only need the offline functionality, you can simple call git fetch -all to get all current information. Now you have all information at your disk and can work offline. Simple merge or checkout the branch you want to work on. Git pull is git fetch && git merge. A: You have to merge each branch individually. If you merged in multiple branches and more than one of them had merge conflicts, how could you possibly resolve then at the same time?
{ "language": "en", "url": "https://stackoverflow.com/questions/7565750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Stty getting insane on using Python subprocess I am facing a weird problem. Every time I call a particular command cmd via subprocess.Popen(cmd).wait(), the stty gets bad (does not echo my further commands on the shell, newline does not work, etc.) when the command is over. I have to run stty sane to get the stty fine again. What could be the reason for this? Update The command I am running is starting the elasticsearch process. The command launches the process in the background. A: It's possible that the command you're running is emitting some escape sequences into your terminal that are changing its mode or other settings. Programs that need the full terminal capability do that (e.g. text based editors). Capturing the standard output of the program you're executing and preventing it from going to the screen might help. Have you tried that?
{ "language": "en", "url": "https://stackoverflow.com/questions/7565753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Django logout url with GET values I have url config based on https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.views.logout Here it is: url(r'^logout(?P<next_page>.*)$', 'logout', name='auth_logout_next'), In template I use such code: <a href="{% url auth_logout_next request.path %}">{% trans "Logout" %}</a> It works nice, yet I have possible GET value in some pages - ?page=2, so request.path drops those values. How should I pass not only the existing page but also GET values if possible. A: <a href="{% url auth_logout_next request.get_full_path|urlencode %}">{% trans "Logout" %}</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7565755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Log4j logging to separate files I have an application that listens on a specific port to do its task. This application can run on multiple instances by specifying different ports in the argument. MyApp-1211.bat contains java MyApp 1211 MyApp-1311.bat contains java MyApp 1311 MyApp-1411.bat contains java MyApp 1411 This application logs to a file. The problem is all three instances log into a single file, myApp.log. Is there a way to tell log4j to use different log files? like: myApp-port1211.log myApp-port1311.log myApp-port1411.log A: Of course you can. One way would be to create multiple configuration files (log4j.xml / log4j.properties) - one per port respectively process. Upon loading the configuration file you could select the correct one based on the current port number: PropertyConfigurator.configure("log4j-" + port + ".properties"); Create the config files accordingly: log4j-1211.properties, log4j-1311.properties, ... The alternative would be to configure the file logging at runtime via Java code: String logFilename = "./myApp-port" + port + ".log"; Layout layout = new PatternLayout("%d{ISO8601} %-5p [%t] %c{1}: %m%n"); FileAppender fileAppender = new FileAppender(layout, logFilename, false); fileAppender.setThreshold(Level.DEBUG); Logger.getRootLogger().addAppender(fileAppender); A: You can refer to system properties in log4j.xml as following: <appender name="ROLL" class="org.apache.log4j.rolling.RollingFileAppender"> <!-- The active file to log to --> <param name="file" value="mylog${MY_PARAM}.log" /> </appender> Now you just have to insert your parameter into system properties either programmatically System.setProperty("MY_PARAM", args[0]) into your main() method or when you are running java: java -DMY_PARAM=1234 MyApp 1234 Obiously you can avoid dupplication if you are running you application from bat or shell script like: java -DMY_PARAM=%1 MyApp %1 Please see the following references for details: http://wiki.apache.org/logging-log4j/Log4jXmlFormat Using system environment variables in log4j xml configuration A: If you go for loading the property configuration file yourself, as suggested by other answers, don't forget to disable the log4j default initialization by adding the env. variable definition to your program's command line: -Dlog4j.defaultInitOverride=true
{ "language": "en", "url": "https://stackoverflow.com/questions/7565756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: targetting the next container child in flex i have created a couple of buttons at run time in flex. when i click on one button using event.currentTarget property i can change its properties like x,y,label etc , also i can get its index. Now i can found the next child index too but how can i change the properties of next child using its index. Currently i am using getElementIndex(Button(event.currentTarget)).x for changing its x coordinates. Need to change the coordinates of the button next to it. A: You can use getChildAt(index + 1) on the button's parent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565766", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: wix IIS version in uninstall condition fails I have a custom control as shown below. During uninstall the condition that checks for IIS_MAJOR_VERSION="#7" AND IIS_MINOR_VERSION="#5" seems to fail although during install this condition is true. I did check in the uninstall file that the property for IIS_MAJOR_VERSION="#7" AND IIS_MINOR_VERSION="#5". Does anyone know what did I do wrong? <Property Id="IIS_MAJOR_VERSION"> <RegistrySearch Id="CheckIISVersion" Root="HKLM" Key="SOFTWARE\Microsoft\InetStp" Name="MajorVersion" Type="raw" /> </Property> <Property Id="IIS_MINOR_VERSION"> <RegistrySearch Id="CheckIISMinorVersion" Root="HKLM" Key="SOFTWARE\Microsoft\InetStp" Name="MinorVersion" Type="raw" /> <Custom Action="DropDBUSerIIS75" Before="InstallFinalize">Installed AND NOT UPGRADINGPRODUCTCODE AND IIS_MAJOR_VERSION="#7" AND IIS_MINOR_VERSION="#5"</Custom> A: Even I am not sure about the code why is it going wrong, but for precaution use this code to get the value of IIS version because even if IIS is un-installed the above registry key values will persist. <Property Id="IIS_MAJOR_VERSION"> <RegistrySearch Id="CheckIISVersion" Root="HKLM" Key="SYSTEM\CurrentControlSet\services\W3SVC\Parameters" Name="MajorVersion" Type="raw" /> </Property> <Property Id="IIS_MINOR_VERSION"> <RegistrySearch Id="CheckIISMinorVersion" Root="HKLM" Key="SYSTEM\CurrentControlSet\services\W3SVC\Parameters" Name="MinorVersion" Type="raw" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7565769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Determine a cursor by condition In SQL Server for CURSOR we say: CREATE PROCEDURE SP_MY_PROC (@BANKID VARCHAR(6)='') ------------------------------- ------------------------------- DECLARE MY_CURSOR CURSOR FOR SELECT ....... Now, what I wonder, can we determine the select statement according to a cerain condition? IF BANKID<>''// SELECT * FROM EMPLOYESS WHERE BANKID=@BANKID to be the cursors query ELSE // otherwise SELECT * FROM EMPLOYEES to be the cursors query Or does it have to be static? A: Yes, you can do this with Dynamic SQL IF @BANKID<> '' SET @sql = ' DECLARE MyCursor CURSOR FOR SELECT ...' ELSE SET @sql = ' DECLARE MyCursor CURSOR FOR SELECT ...' EXEC sp_executesql @sql OPEN MyCursor A: If it is such a simple example, it's better to re-write it as a single query: DECLARE MY_CURSOR CURSOR FOR SELECT * FROM EMPLOYESS WHERE BANKID=@BANKID or @BANKID='' And, of course, we haven't addressed whether a cursor is the right solution for the larger problem or not (cursors are frequently misused by people not used to thinking of set based solutions, which is what SQL is good at). PS - avoid prefixing your stored procedures with sp_ - These names are "reserved" for SQL Server, and should be avoided to prevent future incompatibilities (and ignoring, for now, that it's also slower to access stored procs with such names, since SQL Server searches the master database before searching in the current database).
{ "language": "en", "url": "https://stackoverflow.com/questions/7565772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Construct object by calling constructor (method) explicitly Definition of class: #pragma once #include <string> #include <utility> namespace impress_errors { #define BUFSIZE 512 class Error { public: Error(int number); Error(std::string message); Error(const char *message); bool IsSystemError(); std::string GetErrorDescription(); private: std::pair <int, std::string> error; char stringerror[BUFSIZE]; // Buffer for string describing error bool syserror; }; } // namespace impres_errors I have some piece of code in file posix_lib.cpp: int pos_close(int fd) { int ret; if ((ret = close(fd)) < 0) { char err_msg[4096]; int err_code = errno; throw impress_errors::Error::Error(err_code); //Call constructor explicitly } return ret; } And in another file fs_creation.cpp: int FSCreation::GenerateFS() { int result; try { result = ImprDoMakeTree(); //This call pos_close inside. } catch (impress_errors::Error error) { logger.LogERROR(error.GetErrorDescription()); return ID_FSCREATE_MAKE_TREE_ERROR; } catch (...) { logger.LogERROR("Unexpected error in IMPRESSIONS MODULE"); return ID_FSCREATE_MAKE_TREE_ERROR; } if(result == EXIT_FAILURE) { return ID_FSCREATE_MAKE_TREE_ERROR; } return ID_SUCCESS; } On my version of compiler this one is compiled and work correct: g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5 (Ubuntu Maverick - 10.04) On another version of compiler: g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2 (Ubuntu Narwhal - 11.04) it causes error: posix_lib.cpp: In function ‘int pos_close(int)’: posix_lib.cpp:363:46: error: cannot call constructor ‘impress_errors::Error::Error’ directly posix_lib.cpp:363:46: error: for a function-style cast, remove the redundant ‘::Error’ Questions: 1. Why this work on one version of g++, and failed on another? 2. What happens when I explicitly call constructor for creating object? Is it correct? And why this is working? A: You are not calling the constructor (well, you are, but not in the way you mean it). The syntax ClassName(constructor params) means to create a temporary object of the type ClassName, using the given parameters for its constructor. So you aren't simply calling the constructor; you are creating an object. So you are creating an Error object. Your problem is that the name of Error is impress_errors::Error, not "impress_errors::Error::Error". The second ::Error would seem to be an attempt to name the constructor. Constructors don't have names; they are not functions that you can find and call at your whim (again, not in the way you mean it). A: This looks like an error in the compiler which rejects it. The code is legal, but not for the reasons you think. There is no such thing as "calling constructor (method) explicitly", because constructors don't have names (§12.1/1). On the other hand, impress_errors::Error::Error is the name of a type; class name injection (§9/2) means that the class impress_errors::Error contains a declaration of the name Error in the class, as a synonym for the name outside of the class. So impress_errors::Error, impress_errors::Error::Error, impress_errors::Error::Error::Error, etc. all name the same type (although only the first is idiomatic—the rest are all just extra noise). And when the name of a type is followed by a parenthesized expression list, as is the case here, it is an "Explicity type conversion (functional notation)". (§5.2.3—and the standard says it is an explicit type conversion even if the expression list is empty, or contains more than one expression—don't ask me what "type" is being converted in such cases.) So impress_errors::Error(err_code) (or impress_errors::Error::Error(err_code) means convert err_code into an impress_errors::Error. Which, in this case, will result in calling the constructor, since that's the only way to convert an int into an impress_errors::Error. (It's possible, however, to construct cases where the compiler will call a user defined conversion function on the object being converted.) A: It should be ok if You do what compiler is asking You. Just remove one "Error" statement;> I'm not sure why this changed in gcc, but class_name::construction_name is just redundant. Compiler knows that You want to call constructor, because its name is the same as the name of the class A: While you could explicitly call the constructor using placement new, see placement operators, you don't have an object or piece of memory in which to place the object yet. Probably easier to use something like throw new MyError(MyParams); and make the exception handler responsible for deleting it. FWIW Microsoft use this approach with MFC. A: I ran into the exact same error message. The solution is to change this line: throw impress_errors::Error::Error(err_code); //Call constructor explicitly to throw impress_errors::Error(err_code); //Call constructor explicitly In C++ you can call the base class constructor inside a derived class constructor, just never use the scope resolution operator ::
{ "language": "en", "url": "https://stackoverflow.com/questions/7565776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CFDOCUMENT creates PDF with different MD5 hashes for same input I am using CFDOCUMENT to create a PDF in CF9.0.1. However with the same input each time I generate a new PDF using CFDOCUMENT the MD5 hash seems to be different. Test code is simple: <cfdocument name=FileData1 format="PDF" localurl="yes" pagetype="A4"><h3>I am happy!</h3></cfdocument> <cfdocument name=FileData2 format="PDF" localurl="yes" pagetype="A4"><h3>I am happy!</h3></cfdocument> <cffile ACTION="write" FILE="C:\happy1.pdf" OUTPUT=#FileData1# ADDNEWLINE=NO NAMECONFLICT="Override"> <cffile ACTION="write" FILE="C:\happy2.pdf" OUTPUT=#FileData2# ADDNEWLINE=NO NAMECONFLICT="Override"> Both files produced have different MD5 file-hash although both PDF looks exactly the same. I have a user requirement where if the file is the same to ignore regeneration of PDF, so does anyone know how to force CF9 to generate the same PDF with same MD5 hash (bit similarity) if given the same input? I ran a HxD Hex File Compare and found that the file differs in three sections: * *The font name e.g. 62176/FontName/OJSSWJ+TimesNewRomanPS (the OJSSWJ is random) *The timestamp /CreationDate(D:20110927152929+08'00') *Some sort of key at the end: <]/Info 12 0 R/Size 13>> Thanks for your help in advance! A: They will never be the same. The timestamp /CreationDate(D:20110927152929+08'00') The creationDate is a timestamp of when it was created, thus unless you create it at the same second every time, it wont be the same. You might be able to modify the pdf and remove or modify this bit. Or use a different method to determine if you should create the pdf, creating it to md5 compare the results seems like a waste of processing power.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Javascript Center Possible Duplicate: How to align a <div> to the middle of the page This is a simple question with what should be a simple answer but I don't know how to do it. Well, use this code: <html> <head> <style type="text/css"> body{ min-width: 710px; } #backdrop{ min-width: 710px; max-width: 710px; } </style </head><body> <div id="backdrop"> </div> </body></html> How do you get #backdrop to center on page load and stay centered on the page when you resize? (until you resize to less than 710px wide, then the horizontal scroll bar would appear) Knowing this information would improve the layout quality of my page immensly and I could probably do it if I had a more adept knowledge of javascript and jQuery... but I don't yet. A: You don't need javascript to do this, just try: <html> <head> <style type="text/css"> body{ min-width: 710px; } #backdrop{ width:710px; margin:0 auto; } </style </head><body> <div id="backdrop"> </div> </body></html> [EDIT] This was already answered on stackoverflow: How to align a <div> to the middle (horizontally/width) of the page A: If all you need is to have the #backdrop div centered horizontally, there is no need for javascript. The whole thing can be achieved through CSS. #backdrop{ display:block; width: 710px; //just specify the width. no need for min-width or max-width if this is not meant to change. margin: 0 auto; //this will center the div in its container } A: I'm not really sure about what you want, but: #backdrop{ width:710px; margin: 0 auto; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7565787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you debug win32 com integration from Python? I'm trying to call the text to speech API from Python using win32com.client. The Python interpreter is bundled with Splunk and I'm able to invoke it manually using "splunk cmd python". Here's a sample from win32com.client import constants import win32com.client speaker = win32com.client.Dispatch("SAPI.SpVoice") speaker.Speak('this is a test') My code is invoked via the splunkd process (running as a normal windows user) and I get the following error message. (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147200925), None) I'm struggling to troubleshoot the problem, any suggestions? The bundled Python version is Python 2.6.4 (r264:75706, Feb 7 2011, 14:20:39) [MSC v.1400 64 bit (AMD64)] Cross-posted from Splunk Answers http://splunk-base.splunk.com/answers/31181/debugging-custom-search-commands == update == I've tracked the problem down to the process launching the python interpreter. For some reason the processes messes with the environment in such a way that the python interpreter behaves differently. I suspect the win32 error is actually an access violation. A: The application runs as expected when launched as a normal user. The parent process runs as system, which fails to invoke the TTS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to update a property with an new object from another thread? I have a problem setting a Property on the main thread from another thread. This is what i do at the moment: XAML: <TabControl Name="tab"/> Code Behind: TabItem tabItem = new TabItem(); Binding myBinding = new Binding("ReportView") { Source = ViewModel, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }; BindingOperations.SetBinding(tabItem, TabItem.ContentProperty, myBinding); tab.Items.Add(tabItem); Thread t = new Thread(DoWork); t.SetApartmentState(ApartmentState.STA); t.Priority = ThreadPriority.Normal; t.Start(); DoWork Method: When i create the ReportPreviewView inside the body of the Dispatcher.BeginInvoke, i don't get an exception: public void DoWork(object sender) { //I create the relavant ViewModel ReportViewModel reportViewModel = new ReportViewModel(SessionContext, Mediator, Parent.ReportRequest, false); Dispatcher.BeginInvoke((Action)(() => { //Create the relevant View ReportPreviewView reportPreviewView = new ReportPreviewView(reportViewModel) { ReportName = Parent.ReportRequest.Report.ReportName }; ViewModel.ReportView = reportPreviewView; })); } But this is not correct. It freezes up my UI thread. The creation of the ReportPreviewView takes quit a long time. So then i move the creation of the ReportPreviewView outside the Dispatcher.BeginInvoke: public void DoWork(object sender) { ReportViewModel reportViewModel = new ReportViewModel(SessionContext, Mediator, Parent.ReportRequest, false); ReportPreviewView reportPreviewView = new ReportPreviewView(reportViewModel) { ReportName = Parent.ReportRequest.Report.ReportName }; Dispatcher.BeginInvoke((Action)(() => { reportLoaderViewModel.ReportView = reportPreviewView; })); } As soon as PropertyChanged fires i get the following exception: The calling thread cannot access this object because a different thread owns it Any idea how i can get around this? A: You have to create UI elements on UI dispatcher thread. There is no escape. So when you say The creation of the ReportPreviewView takes quit a long time. Did you anaylyse why is that? Does it have drawings, animations, heavy styles, non-virtualized panels (such as canvas)? Does it have some code in its constructor that takes time to complete? If so, please reconsider your UI design. In WPF the UI always freezes for heavy views. Even if you deserialize views using XAMLReader/Writer, the creation and hosting of the view object has to take place on UI thread.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assign single value to multiple variables I want to assign 0 to all declared values in a single statement. char r, g, b = 0; The above only assigns 0 to b but not to the other variables A: You can do it two ways: char r = 0, g = 0, b = 0; or char r, g, b; r = g = b = 0; A: Tersest form is: int r,g,b=g=r=0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7565794", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: Facebook permissions for viewing photos I'm writing a Facebook application that accesses the user's friends' photos. For some reason, I can only access certain photos. I have narrowed it down to only being able to access photos with the 'Friends of Friends' privacy setting turned ON. The pictures I can't access still have the 'Friends' privacy settings turned ON, but the user the Application is acting on behalf of is friends with these people, so as per Facebook's privacy scheme, I should be able to access them. I can access the photos via the Facebook site. My application has the following permissions: user_photos, friends_photos. I'm not receiving any OAuth errors, I'm merely getting nothing back from the server (e.g. if the user has all their photos set to 'Friends only' I get a blank data{} array from a /UserID/albums API call. Anyone know what's happening? Should I be requesting more permissions from my App users? A: There's a privacy setting which can override this, check the settings on the friends' account to see what their options for 'How people bring your info to apps they use' setting is - it's on https://www.facebook.com/settings/?tab=privacy and allows users to stop apps their friends use from accessing any data about them, even if it would normally be available to that friend.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: abort AJAX post My setup is like this (simplified for clarity) : <div class="methods"> <a href="#a">Method 1</a> <a href="#b" class="fb_method">FB Method</a> <a href="#c">Method 3</a> </div> ... <!-- contents --> So each method, if clicked, will fade in the inline contents, except anchor that has "fb_method" class, since it needs to do an AJAX request first before appending to its content container in the contents. So my jQuery is like this : $('.methods a').click(function(){ // do something global to the anchors, eg : change the bg color, etc // set the target container var target = $(this).attr('href'); var xhr; //if user clicks fb_method buttons if($(this).hasClass('fb_method')){ //do ajax request - NOTE 1 xhr = $.post("/ajax/get_fb_albums.php",function(msg){ $(target).html('').append(msg).fadeIn(); }); }else{ //abort all ajax request xhr.abort(); $(target).fadeIn(); } return false; }); So what I want is when users first click fb_method button, it will request an AJAX. But if they suddenly change their mind and click other methods, I want to abort the previous AJAX request. I tracked it via Firebug and it returns an error of the xhr being undefined. if I moved the xhr in NOTE 1 before the if statement, it works but the AJAX request is still being processed. What I mean is in Firebug when I click the FB method then click other methods, it displayed something like this: // ajax request xhr - keeps on loading // ajax request xhr aborted But the request keeps on loading. A: Your xhr variable is local inside the function called when the click event happens. When you call the abort method, xhr is not the variable used for the post method. The xhr variable needs to be external to the function binded to the click event, otherwise it will be undefined when you check it for other click events. Additionally, since you probably need more than one xhr variable to store different post, you should create an array or an object to store the different post. var xhr = []; $('.methods a').click(function(){ // do something global to the anchors, eg : change the bg color, etc // set the target container var target = $(this).attr('href'); //if user clicks fb_method buttons if($(this).hasClass('fb_method')){ //do ajax request (add the post handle to the xhr array) xhr.push( $.post("/ajax/get_fb_albums.php", function(msg) { $(target).html('').append(msg).fadeIn(); }) ); }else{ //abort ALL ajax request for ( var x = 0; x < xhr.length; x++ ) { xhr[x].abort(); } $(target).fadeIn(); } return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7565798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Gridview sorting when Header text changed in RowDataBound event I have a GridView on my webpage whose DataSource is a DataTable which is populated at runtime. AllowSorting property of GridView is True. I have successfully implemented manual sorting for this GridView. But I had to translate the webpage to other languages for which I used local resource files. I changed the Header text of GridView columns in RowDataBound event. Since then I'm unable to sort the GridView. protected void GVSummaryTable_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.Cells.Count > 0) { //Translate header text if (e.Row.RowType == DataControlRowType.Header) { e.Row.Cells[0].Text = GetLocalResourceObject("GVSummaryTableName").ToString(); e.Row.Cells[1].Text = GetLocalResourceObject("GVSummaryTableLoginLevel").ToString(); e.Row.Cells[2].Text = GetLocalResourceObject("GVSummaryTableLoginID").ToString(); e.Row.Cells[4].Text = GetLocalResourceObject("GVSummaryTableDate").ToString(); } } } What should I do to enable sorting for the columns? Any help would be appreciated. Thanks! A: Changing the code to below solved the problem: if (e.Row.RowType == DataControlRowType.Header) { LinkButton LnkHeaderText = e.Row.Cells[1].Controls[0] as LinkButton; LnkHeaderText.Text = "Name"; } A: I am not sure if the problem is related to the Header text since the sorting is normally done with the Sort Expression. Please, make sure you are also giving a value to this property when doing the Sorting. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7565801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: fork() call in c I have used fork() to create 2 different processes operating on 2 different address spaces. Now, in parent process I need the value of a variable from child's address space or if the child process can modify the variable in parent's address space. Is this possible? A: No, once you've forked, each process gets its own address space and you'll have to look into either: * *some form of IPC between the processes to access each others data (such as shared memory or message queues). *some more lighweight variant of fork that allows sharing of data (including possibly threading). A: Once you have two processes, sharing data needs interprocess communication: file, pipe or shared memory. A: If you mean exchanging data between these two processes you can not. You can do it by system APIs like SharedMemory, Message Passing, Pipeline, Socket, ... A: As you have created two process using fork command Both Process will be in different address space so they will only communicate by IPC, message passing ,Piping , Shared Memory etc. otherwise one process can't access other process data as thay do have Process specific data and similarly threads also have thread specific data
{ "language": "en", "url": "https://stackoverflow.com/questions/7565806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to control Apache via Django to connect to mongoose(another HTTP server)? I have been doing lots of searching and reading to solve this. The main goal is let a Django-based web management system connecting to a device which runs a http server as well. Django will handle user request and ask device for the real data, then feedback to user. Now I have a "kinda-work-in-concept" solution: * *Browser -> Apache Server: Browser have jQuery and HTML/CSS to collect user request. *Apache Server-> Device HTTP Server: Apache + mod_python(or somesay Apache + mod_wsgi?) , so I might control the Apache to do stuff like build up a session and cookies to record login. But, this is the issue actually bugs me. How to make it work? Using what to build up socket connection between this two servers? A: You could use httplib or urllib2 (both supplied in the Python standard library) in your Django view to send HTTP requests to the device running mongoose. Alternatively you could use the Requests library which provides a less verbose API for generating HTTP requests - see also this blog post. (Also, I would strongly recommend that you use mod_wsgi rather than mod_python as mod_wsgi is being actively maintained and performs better than mod_python, which was last updated in 2007) A: If you have control over what runs on the device side, consider using XML-RPC to talk from client to server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How does AirPrint work without drivers? I would to know how AirPrint works without drivers (with compatible printer or through a AirPrint enabled pc/mac). What are the communication steps between ios device and printer?
{ "language": "en", "url": "https://stackoverflow.com/questions/7565820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: getSensorList() vs. getDefaultSensor() in Android SensorManager I'm writing a game for Android and want to be able to use the accelerometer for input. I see two ways of getting a sensor, one way is to use the first element of SensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER) and the other is SensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER). The getDefaultSensor doc says it could return a "composite" sensor, so if I want a "raw" sensor I should use getSensorList. Any idea what the difference between a composite or raw sensor is? Does this even apply to the accelerometer? Anyone have experience with devices that contain multiple or composite accelerometers? (Or some other sensor?) A: Google's documentation is way ahead of their implementation here. I browsed through the code repository (which seems to be 2.3.1-ish source) and found: public Sensor getDefaultSensor(int type) { // TODO: need to be smarter, for now, just return the 1st sensor List<Sensor> l = getSensorList(type); return l.isEmpty() ? null : l.get(0); } So there is no real difference (and I don't think they can really add one later) between the sensors returned from getDefaultSensor() and from getSensorList(). A: An update: They have updated the getDefaultSensor method in Lollipop, and there now is a difference: public Sensor getDefaultSensor(int type) { // TODO: need to be smarter, for now, just return the 1st sensor List<Sensor> l = getSensorList(type); boolean wakeUpSensor = false; // For the following sensor types, return a wake-up sensor. These types are by default // defined as wake-up sensors. For the rest of the SDK defined sensor types return a // non_wake-up version. if (type == Sensor.TYPE_PROXIMITY || type == Sensor.TYPE_SIGNIFICANT_MOTION || type == Sensor.TYPE_TILT_DETECTOR || type == Sensor.TYPE_WAKE_GESTURE || type == Sensor.TYPE_GLANCE_GESTURE || type == Sensor.TYPE_PICK_UP_GESTURE) { wakeUpSensor = true; } for (Sensor sensor : l) { if (sensor.isWakeUpSensor() == wakeUpSensor) return sensor; } return null; } So if there are multiple sensors available for the specified type, getDefaultSensor will return a non-wakeup version (unless the default type is one of those 6 above actually defined as a wakeup sensor) By the way, Sensor.TYPE_TILT_DETECTOR, Sensor.TYPE_WAKE_GESTURE, Sensor.TYPE_GLANCE_GESTURE and Sensor.TYPE_PICK_UP_GESTURE are hidden in the SDK, as they are intended to be used only for the system UI. There's more details on them in the Sensor.java source
{ "language": "en", "url": "https://stackoverflow.com/questions/7565822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: RailsInstaller on Windows 7 64bit? I tried to use the Rails Installer to get a ruby on rails environment on my Windows 7 64bit today and the .exe won't run because it's made for 32bit instead of 64bit. Update When I try to start the installer, this message pops up: Here is the translation: This version of the file is not compatible with the running version of Windows. Open the system information of the computer to check if a x86 (32bit) or x64 (64bit) version of this application is neccessary and contact the software vendor. Is there a 64bit alternative for the installer? A: 64bits Windows can run 32bits applications, that is what WOW64 layer provides (Windows on Windows) However, there are specific things you can't perform, like accessing OLE or using 64bits DLLs from 32bits applications or viceversa. If the issue you're having is connect to a MySQL installation (something you're not mentioning) you should take a look to this blog article: http://blog.mmediasys.com/2011/07/07/installing-mysql-on-windows-7-x64-and-using-ruby-with-it/ Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: From where wp ecommerce is loading plugin theme files? I updated my checkout page by updating mostly the file which was in ....wp-ecommerce/wpsc-theme/wpsc-shopping_cart_page.php It worked fine for a while, but now some of the changed states reverted to the previous state. Actually, I can even delete the file that I mentioned above, so it means wordpress is loading this file from somewhere else. Any ideas from where and what had happened? Thanks for your help. A: Although I don't have a specific answer to your question, if you use an IDE (like Dreamweaver or Eclipse) you could grab a copy of your sites code to your local PC and do a code search for something that is unique to that page. Ie, if there is a <div class="a_unique_div"> tag somewhere on that page and you know it's only visible on that page, search the code for that and it may give you a clue what file is being used for the output. Even if it's only used on 1 or 2 pages it may bring you closer to working it out. Alternatively, if you have SSH access you could try and "grep" for the code by SSHing into your server and running a command like: grep -i -R '<div class="a_unique_div">' /www/your_wp_folder/ (where /www/your_wp_folder/ is the path to your WordPress installation) Though for this you'll need SSH access, grep installed on the server, etc, so it may not be a viable option. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/7565827", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: paypal integration in asp.net 4.0 hi i'm new to the web development.I just created a online shop in which all things finally i want to add some mechanism by which i redirect my customer to paypal site and pay then redirect to my site.please help me. A: To help you with the idea. The idea is that you collect all your order informations to a page, places this informations in a form using hidden input controls, and you post them to paypal. This informations iclude the url that your customer can return if he like to cancel, return when its complete, the cost, your email, your customer email, and many other parametres that you can read them on the manual. Download the sdk here: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_download_sdks And there are also the documents here https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/library_documentation Also you can find a sample code, and other. A: the quickest and simplest way to integrate paypal <a href="https://www.paypal.com/cgi-bin/webscr ?cmd=_xclick&business=MyEmail &item_name=Widget &amount=29.00 &undefined_quantity=1 &currency_code=USD">
{ "language": "en", "url": "https://stackoverflow.com/questions/7565830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to execute query in Zend framework Thanks for previous replies I am execution "select Name from table_name where id=1"; . i saw some tutorials for getting data from the database, they mentioned $DB = new Zend_Db_Adapter_Pdo_Mysql($params); DB->setFetchMode(Zend_Db::FETCH_OBJ); and the result will getting through $result = $DB->fetchAssoc($sql); This $result is an array format, i want to get only name instead of getting all the data from the database. I am new to this topic. if i made any mistake pls do correct. A: try this: $result = $DB->fetchOne("SELECT name FROM table_name WHERE id=1"); A: This code will execute your query through doctrine getServiceLocator(). With the help of createQueryBuilder(), you can write your query directly into zend-framework2, and with setParameter, any desired condition would be set easily. $entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default'); $qb = $entityManager->createQueryBuilder(); $qb->select(array( 'TableName.columnName as columnName ' )) ->from('ProjectName\Entity\TableName', 'TableName') ->where('TableName.TableId = :Info') ->setParameter('Info', $id); $var= $qb->getQuery()->getScalarResult(); The $var variable holds the value for which, you wanted the comparison to be made with, and holds only the single values of your interest.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Blank page for jquery.SPServices that list a sharepoint List I have a SharePoint List that I wish to view it on a custom aspx file. The SharePoint List is named - "AM_Code" Inside the List, there are multiple columns but I just want those rows with the column 'Title' that is not null. The data will then be displayed on the screen. The code as follows: <%@ Page Language="C#" %> <html dir="ltr"> <head runat="server"> <META name="WebPartPageExpansion" content="full"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Testing JQuery with Sharepoint List</title> </head> <body> <form id="form1" runat="server"> </form> <script type="text/javascript" language="javascript" src="jquery-1.6.2.min.js"></script> <script type="text/javascript" language="javascript" src="jquery.SPServices-0.6.2.min.js"></script> <script language="javascript" type="text/javascript"> $(document).ready(function() { $().SPServices({ operation: "GetListItems", async: false, listName: "AM_Code", CAMLViewFields: "<Query><Where><IsNotNull><FieldRef Name="Title" /></IsNotNull></Where><OrderBy><FieldRef Name="Title" Ascending="True" /></OrderBy></Query>", completefunc: function (xData, Status) { $(xData.responseXML).find("[nodeName='z:row']").each(function() { var liHtml = "<li>" + $(this).attr("ows_Title") + "</li>"; $("#tasksUL").append(liHtml); }); } }); }); </script> <ul id="tasksUL"/> </body> </html> However nothing was being displayed. Please advise if I have miss anything. A: CAMLViewFields: "<Query><Where><IsNotNull><FieldRef Name="Title" /></IsNotNull></Where><OrderBy><FieldRef Name="Title" Ascending="True" /></OrderBy></Query>", this doesn't seem right to me A: Actually I found my own answer. The CAMLViewFields contain the following in order to work: "<Query><Where><IsNotNull><FieldRef Name='Title' /></IsNotNull></Where><OrderBy><FieldRef Name='Title' Ascending="True" /></OrderBy></Query>", Hope it help anyone who is also looking for such solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: conflicting distributed object modifiers on return type in implementation of 'release' in Singleton class I have recently upgraded to Xcode 4.2 and its started to give me so many semantic warnings with my code... one of them is "conflicting distributed object modifiers on return type in implementation of 'release'" in my singleton class.. I read somewhere about - (oneway void)release; to release this warning but once i put that in my code i start to getting compile error as "Duplicate declaration of release" not sure why and if you try to find the second declaration it shows in this line SYNTHESIZE_SINGLETON_FOR_CLASS(GlobalClass); Update: This is the post where it explained about - (oneway void)release; how to get rid of this warning "conflicting distributed object modifiers on return type in implementation of release" ? and why its happening ? A: The post you link to contains the solution to the problem in the title and explains why it happened to you. However, from reading your question it appears that your new issue is caused by mis-applying the great advice in that post's answer. I am fairly certain you added the line - (oneway void) release {} in your .m file rather than amending your existing - (void) release { line with the extra word "oneway". This would be why you get "Duplicate declaration of release". Yes, this is confusing because it's a duplicate definition that is invisibly creating the duplicate declaration. But I've just tried doing it your wrong way, and I get that "duplicate declaration" message. I get the impression, perhaps wrongly, that you didn't realise you actually had a release method, particularly when you think adding the line will "release this warning". Don't take all errors too literally, and always try to think what someone might really mean as it's often different from what they say, but do try and understand what is in your code, even in the classes you've taken off the shelf. And to address other questions raised, the reason you're overriding release is because it is a singleton which is not usually released. You probably only have a definition in your code, which will suffice. What Jonathan Grynspan has to say about specifying on both the declaration and the definition is broadly valid (and indeed the root of the issue) but it's important to recognise that in this specific case, the declaration is by Apple's foundation code which has changed. So, if it's not clear already, amend the line that XCode finds problem with to include the word oneway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: Web Service Method with Optional Parameters Possible Duplicate: Can I have an optional parameter for an ASP.NET SOAP web service I have tried looking around for this but I really cannot find the right solution for what I want to do. Sorry for the repetition since I know this has been asked before. I have a Web Service Method in which I want to have an optional parameter such as: public void MyMethod(int a, int b, int c = -3) I already know I cannot use nullable parameters, so I am just trying to use a default value. Problem is when I call this method without supplying argument c is still get an exception. Is there somewhere I have to specify it is in fact optional? Thanksю A: I've looked into optional parameters etc. before, and straight asmx web services don't support this (with default generated WSDLs). With WCF however, you can mark parameters in your datacontract as IsRequired=false - see Optional parameters in ASP.NET web service A: You can achieve optional parameters by overloads and using the MessageName property. [WebMethod(MessageName = "MyMethodDefault")] public void MyMethod(int a, int b) { MyMethod( a, b, -3); } [WebMethod(MessageName = "MyMethod")] public void MyMethod(int a, int b, int c) For this to work, you may also need to change [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] to [WebServiceBinding(ConformsTo = WsiProfiles.None)] if you haven't done so already, as WS-I Basic Profile v1.1 does not allow overloads A: Use methods overloading: [WebMethod(MessageName = "MyMethod1")] public void MyMethod(int a, int b) { return MyMethod(a, b, -3); } [WebMethod(MessageName = "MyMethod2")] public void MyMethod(int a, int b, int c) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/7565842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Running parallel selenium tests with capybara Background: I have a set of Capybara integration tests running against my Rails 3 Application. For the other parts of the test suite I'm using Rspec. I have a selenium 2.6.0 standalone server hub on my Mac OSX dev machine. java -jar selenium-server-standalone-2.6.0.jar -role hub I'm running several virtual machines each hooked up to the hub with a selenium node: java -jar selenium-server-standalone-2.6.0.jar -role webdriver -hub http://0.0.1.12:4444/grid/register port 5555 -browser browserName="internet explorer",version=8,platform=WINDOWS This works fine, In this screenshot the console shows that I have an IE7 and an IE8 browser connected to the hub: I've setup capybara to run against the selenium hub (that delegates the tests to the nodes). Capybara.app_host = "myapp.dev" Capybara.default_driver = :selenium Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app, :browser => :remote, :url => "http://localhost:4444/wd/hub", :desired_capabilities => :internet_explorer) end It works, however it will only run the test on a single internet_explorer node. It seems to be the one that is "first in line"; If i turn it off, the test will successfully run on the other node. I've been trying out the parallel_tests project, configuring capybara as suggested, but that would still only launch one integration test. How can I run my integration on all internet_explorer nodes simultaneously? Bonus question: If i wanted to run my integration tests on all connected nodes, regardless of browser capability, how would i do that? A: Here you have to fire the same tests for different browser so can try to start two process of tests i.e. Run the same command twice. As you have started the nodes the Grid will handle the execution on different nodes. In your case you are executing the test and only on suite/process is started with respect to Grid. Just for testing Purpose try firing these tests twice one after another. If you are not able to Achieve by this Use Ant or similar thing to control your execution of tests. A: For IE webdrive you can run at most 1 test on one physical node! If you want to achieve parallelism with IE webdriver than you can try by add/register more physical node to the hub. Regarding above screen shot of hub console, it also shows you only one IE icon. The message is wrong that "Supports up to 5 ...." but you can consider number of icon for respective browser displayed below it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What is the best way to achieve a honeypot style form captcha? I have heard of honeypot style captcha systems either loading the form with javascript, which might load after the page has rendered. Or checking if a hidden field is filled in, which could possibly be mitigated. Is there a full-proof way to achieve this functionality without compromising user experience? A: The basic idea is to have the form contain honeypot fields that will get the request rejected or silently dropped if they are filled out, and which are made invisible to the user through CSS or Javascript DOM manipulation. Here's a blog post that describes a fairly complex way of making it nearly impossible for bots to distinguish between regular and honeypot fields. I've used it with 100% success so far, but it only helps if they bots rely on field names. I suspect that most generic spam bots don't even try to fill out fields selectively, so you wouldn't need it, and targeted spam bots would easily defeat the scheme by identifying fields via their position in the HTML rather than the name.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error:emulator-5554 disconnected: Possible Duplicate: Why do I get a emulator-5554 disconnected message i run mine application in eclipse and the following results found in console [2011-09-27 12:47:58 - AndroidBlackjack] Android Launch! [2011-09-27 12:47:58 - AndroidBlackjack] adb is running normally. [2011-09-27 12:47:58 - AndroidBlackjack] Performing com.android.blackjack.Setup activity launch [2011-09-27 12:47:58 - AndroidBlackjack] Automatic Target Mode: Preferred AVD 'yahoo' is not available. Launching new emulator. [2011-09-27 12:47:58 - AndroidBlackjack] Launching a new emulator with Virtual Device 'yahoo' [2011-09-27 12:49:52 - AndroidBlackjack] New emulator found: emulator-5554 [2011-09-27 12:49:52 - AndroidBlackjack] Waiting for HOME ('android.process.acore') to be launched... [2011-09-27 12:51:12 - AndroidBlackjack] emulator-5554 disconnected! Cancelling 'com.android.blackjack.Setup activity launch'! please help me i do not understand this. A: Solution (Eclipse IDE) Select & Right Click on Android Project Run Configurations Go to tab Target Enable option Wipe User Data on Emulator launch parameters Run Application If you are using other IDE, you can restart your emulator using -wipe-data flag to delete all the temporary files that the emulator created in previous runs. A: the cancellation occurs because of three reasons: * *i had not clean the project emulator => project => clean *i had written the .main in small letters in manifest.xml by mistake *i had not removed windows firewall settings of window A: The problem as I discovered lays in the fact the the project has no appropriate Virtual Device defined for it in the AVD manager. So the recommended steps in eclipse are: Go to "Project"-> Properties-> Android. On the right pane see what line is checked in the Project build target. Remember the target platform number that appears in the selected line. Go to "Windows"-> AVD Manager. Check the list of existing Android Virtual Devices for a device that matches the Platform and API level that you have set for your project (see step #2 above). If there is no line that includes an AVD for your platform (as I suspect), add it using the "New" button. A "Create New Android Virtual Device" window will be opened. set a new device name. in the "Target" selection box choose the right platform for your project. Enjoy your emulator once again!
{ "language": "en", "url": "https://stackoverflow.com/questions/7565864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML - CSS - Layout I've a page here: http://www.balibar.co/?dating=does-friends-with-benefits-work With the larger first DIV on the left you can see an image with a logo and text showing and a black background. Next (with some opacity) is a white background with words (friend with benift etc)... This top parts site as i want it to.. Once the black logo/text part ends I want the text to flow to fill the entire white section below. Currently its held in the same DIV and doesn't flow across to the left. div#wrapperArticle { padding: 10px; width: 364px; } If I remove the width: 364px it does flow across but then covers the black/logo/text section that I want to keep as is - visable. Is there a way to keep the black/logo/text part visable, the text running over the rest of the image as it is with opacity and then the text to flow into and fill the area below? I've tried lots ideas but I can't get this combination to stick.. thx Adam A: Merge the left and middle column in the same <div> and then make the image float: left; with padding on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565867", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Switching from one view to another : Java I have one .java file in which I have a form for user registration and I have another page on another .java file that should appear (and previous should disappear) when user clicks on next .... could anybody provide me any guidance. Thanks a lot efforts appreciated A: Use a CardLayout A: My guess! you haven't tried setVisible() method. A: Remove old content from container and add the new content. Then call revalidate() and repaint(). A: very simple by implements Splash Screen logics, you create a JDialog (one .java) and only if everything passed from one .java then shows something from another .java
{ "language": "en", "url": "https://stackoverflow.com/questions/7565873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add Styles to document head from the view in Cakephp? I need to add styles to my style tag in my head section. How can i add to that style tag from the view. A: You'd be better off from an MVC point of view by putting these style elements in to their own stylesheet, and then inserting the sheet in the way mentioned above. However if you must use internal CSS, this should work: $this->addScript('extraCSS','<style type="text/css>".foo{color:red;}</style>'); extraCSS I believe is just an internal name given to the content that gets added to the $scripts_for_layout buffer. This will appear below any JS inclusions, which can be a problem at times. A: See all about adding css files using the HTML Helper here: http://book.cakephp.org/view/1437/css Make sure you have $scripts_for_layout in the head of your layout to have cake put scripts there automatically (see the third example). EDIT: For style tags, see here: http://book.cakephp.org/view/1440/style Otherwise, CakePHP uses simple PHP as the templating language in the view - so just write it using that. Some example code and further explanation of what you'd like to do would also be helpful.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Concatenate unwantedly applies max character width I am trying to print some mixed text and variables, all on one line. c() unwantedly forces all character fields to be the width of the largest field, i.e. 12 chars in this case. How to just get simple concatenation? > print(c('Splitting col',i,'x<', xsplitval),quote=FALSE) [1] Splitting col 9 x< 6.7 (I already checked all the SO questions, and all the R documentation, on print, options, format, and R mailing-lists, and Google, etc.) A: You probably want to use paste: i <- 9 xsplitval <- 6.7 paste('Splitting col',i,'x<', xsplitval, sep="") [1] "Splitting col9x<6.7" A: Another option is to use the sprintf function, which allows some number formatting: i <- 9 xsplitval <- 6.7 sprintf("Splitting col %i, x<%3.1f", i, xsplitval) A: I suggest the concatenate and print function, cat, for this purpose. Another option is message, which sends the output to stderr. > i <- 9 > xsplitval <- 6.7 > cat('Splitting col ',i,' x<', xsplitval, '\n', sep="") Splitting col 9 x<6.7 > message('Splitting col ',i,' x<', xsplitval, sep="") Splitting col 9 x<6.7 c is the function for combining values into a vector; it lines up the result into equally spaced columns to make looking at resulting vector easier. > c('Splitting col ',i,' x<', xsplitval) [1] "Splitting col " "9" " x<" "6.7" paste concatenates character vectors together, and sprintf is like the C function, but both return character vectors, which are output (by default) with quotes and with numbers giving the index that each line of output starts with, so you may want to wrap them in cat or message. > s1 <- paste('Splitting col ',i,' x<', xsplitval, sep=""); s1 [1] "Splitting col 9 x<6.7" > cat(s1,'\n') Splitting col 9 x<6.7 > s2 <- sprintf("Splitting col %i, x<%3.1f", i, xsplitval); s2 [1] "Splitting col 9, x<6.7" > cat(s2,'\n') Splitting col 9, x<6.7
{ "language": "en", "url": "https://stackoverflow.com/questions/7565875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript/jQuery - DateTime to Date and Time separate strings Is there any simple way to convert the following: 2011-08-31T20:01:32.000Z In to UK date format: 31-08-2011 and time to: 20:01 A: You can use jquery-dateFormat plugin. The following should do the trick: $.format.date('2011-08-31T20:01:32.000Z', "dd-MM-yyyy")); $.format.date('2011-08-31T20:01:32.000Z', "hh:mm")); A: Date: var currentTime = new Date(); var month = currentTime.getMonth() + 1; var date = currentTime.getDate(); var year = currentTime.getFullYear(); $('#date1').html(date + '-' + month + '-' + year); Time: <script type="text/javascript"> var tick; function stop() { clearTimeout(tick); } function clock() { var ut=new Date(); var h,m,s; var time=""; h=ut.getHours(); m=ut.getMinutes(); s=ut.getSeconds(); if(s<=9) s="0"+s; if(m<=9) m="0"+m; if(h<=9) h="0"+h; time+=h+":"+m+":"+s; document.getElementById('clock').innerHTML=time; tick=setTimeout("clock()",1000); } </script> <body onload="clock();" onunload="stop();"> <p><span id="clock"></span></p> </body> A: var a = '2011-08-31T20:01:32.000Z'; var b = new Date(a); See http://www.w3schools.com/jsref/jsref_obj_date.asp for methods you can use on b now. A: var rg=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\..*/g; var dateStr="2011-08-31T20:01:32.000Z".replace(rg,"$3-$2-$1"); // result is 31-08-2011 var timeStr="2011-08-31T20:01:32.000Z".replace(rg,"$4:$5"); // result is 20:01 A: You can use momentjs (http://momentjs.com/): var date = moment(dateObject).format("YYYY-MM-DD"); var time = moment(dateObject).format("HH:mm:ss"); A: Use the date object: d = new Date('2011-08-31T20:01:32.000Z'); date = d.format("dd-mm-yyyy"); time = d.format("HH:MM"); A: var date = new Date("2011-08-31T20:01:32.000Z").toLocaleDateString(); // date = 2011/08/31 date = date.split("/"); // date = ["31", "08, "2011"] date = date[2] + "-" + (date[0].length == 1 ? "0" + date[0] : date[0]) + "-" + (date[1].length == 1 ? "0" + date[1] : date[1]); // data = 2011-31-08 $("#your-txtbox").val(date);
{ "language": "en", "url": "https://stackoverflow.com/questions/7565879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: What is the mysterious ThreadSafeObjectProvider Was browsing through a project of mine and stumbled across the following code (and class) inside of a file MyWebExtentions which I have never seen before. Private s_Computer As New ThreadSafeObjectProvider(Of Global.Microsoft.VisualBasic.Devices.ServerComputer) ''' <summary> ''' Returns information about the host computer. ''' </summary> <Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")> _ Friend ReadOnly Property Computer() As Global.Microsoft.VisualBasic.Devices.ServerComputer Get Return s_Computer.GetInstance() End Get End Property So I tried looking at the object explorer and it doesnt appear, searching MSDN and nothing, tried stackoverflow also nothing. In the end I did find this article which does explain that it allows you to create a "thread safe, thread specific storage" but doesn't explain, why or how. So could someone please be kind enough to explain what is the purpose of this class, how it works and if there any appropriate usage scenarios for this class in non designer generated code? A: For when you want a particular variable to be thread static but need to create a thread static variable for each context that calls your method. You would use this. This keeps thread static variables per context where declaring something as thread static would keep it only for the thread on which it was created. That's my understanding which honestly might be completely bogus but is how i interpreted it and acts as an example of why I gave on working in WCF for a while. Seriously though, downvote this if you must but this is my best attempt to answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: DRY version of a list What would be the most efficient way to do the following: genres = [value_from_key(wb, 'Genre (1)', n), value_from_key(wb, 'Genre (2)', n), value_from_key(wb, 'Genre (3)', n), value_from_key(wb, 'Genre (4)', n),] I tried doing it with a list comprehension -- genres = [value_from_key(wb, 'Genre (%s)'%(i), n) for i in range[1,4]], but it kept raising a TypeError saying object is unsubscriptable. What would be the DRY way of doing the above? Thank you. A: Replace the square brackets [1,4] with round braces (1,4) in your call to range: genres = [value_from_key(wb, 'Genre (%s)'%(i), n) for i in range(1,4)] A: but it kept raising a TypeError saying object is unsubscriptable. Because range[1,4] means "use the tuple (1, 4) as a subscript for range". Since range is a function, you want to call it, i.e. put the arguments in parentheses (just as you do for value_from_key). I don't really see how you would conclude from an error like this that there's something wrong with the list comprehension itself. o_O What would be the DRY way of doing the above? With the list comprehension.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery accordion making some page links disabled I'm using jQuery accordion which expands and collapses fine but when it expands it hides some of the page tabs and links. When it collapses these tabs and links don't work, they just become disabled. Can somebody help me? What could be the problem? Here is the link where the problem exist http://www.alpolink.com. Five tabs in the header will work fine until you click on the vertical accordion menu, the last most right tab and right most links on the page don't work. A: Feels like you are overwriting some objects. Maybe you have a problem how you select your elements. Like $('.class').bla() will change all objects with this class. You might want to check those selectors you use. Make sure they only select the objects you really want.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Proper way to make a HTTP request in Android Which is the best way to make a HTTP connection. I mean using proxies and so on. Now I'm using this one: StringBuilder entity = new StringBuilder(); entity.append("request body"); AndroidHttpClient httpClient = AndroidHttpClient.newInstance(null); String proxyHost = android.net.Proxy.getDefaultHost(); int proxyPort = android.net.Proxy.getDefaultPort(); if (proxyHost != null && proxyPort > 0) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); ConnRouteParams.setDefaultProxy(httpClient.getParams(), proxy); } HttpPost httpPost = new HttpPost("https://w.qiwi.ru/term2/xmlutf.jsp"); httpPost.setEntity(new StringEntity(entity.toString(), "UTF-8")); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 15000); HttpConnectionParams.setSoTimeout(params, 30000); httpPost.setParams(params); HttpResponse httpResponse = httpClient.execute(httpPost); int responseCode = httpResponse.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_OK) { // parsing response } I'm not really sure if that's ok, because one of my clients tells me he has an IllegalArgumentException right after setting proxy in his APN settings. A: Use one method called executeRequest which makes the actual call to the host API_REST_HOST, this way (API_REST_HOST can be a value like "api.flickr.com" for flickr's rest api. The HTTP and the port get added) private void executeRequest(HttpGet get, ResponseHandler handler) throws IOException { HttpEntity entity = null; HttpHost host = new HttpHost(API_REST_HOST, 80, "http"); try { final HttpResponse response = mClient.execute(host, get); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); final InputStream in = entity.getContent(); handler.handleResponse(in); } } catch (ConnectTimeoutException e) { throw new ConnectTimeoutException(); } catch (ClientProtocolException e) { throw new ClientProtocolException(); } catch (IOException e) { e.printStackTrace(); throw new IOException(); } finally { if (entity != null) { try { entity.consumeContent(); } catch (IOException e) { e.printStackTrace(); } } } } Call this API from here this way: final HttpGet get = new HttpGet(uri.build().toString()); executeRequest(get, new ResponseHandler() { public void handleResponse(InputStream in) throws IOException { parseResponse(in, new ResponseParser() { public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException { parseToken(parser, token, userId); } }); } }); Where your uri is constructed like this: final Uri.Builder builder = new Uri.Builder(); builder.path(ANY_PATH_AHEAD_OF_THE_BASE_URL_IF_REQD); builder.appendQueryParameter(PARAM_KEY, PARAM_VALUE); Your mClient is declared as a class level variable this way private HttpClient mClient; and finally your parseResponse can be done in this way(say you want to parse XML data) private void parseResponse(InputStream in, ResponseParser responseParser) throws IOException { final XmlPullParser parser = Xml.newPullParser(); try { parser.setInput(new InputStreamReader(in)); int type; while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) { // Empty } if (type != XmlPullParser.START_TAG) { throw new InflateException(parser.getPositionDescription() + ": No start tag found!"); } String name = parser.getName(); if (RESPONSE_TAG_RSP.equals(name)) { final String value = parser.getAttributeValue(null, RESPONSE_ATTR_STAT); if (!RESPONSE_STATUS_OK.equals(value)) { throw new IOException("Wrong status: " + value); } } responseParser.parseResponse(parser); } catch (XmlPullParserException e) { final IOException ioe = new IOException("Could not parse the response"); ioe.initCause(e); throw ioe; } } This code takes care of all of the possible exceptions and shows how to properly parse response coming from an input stream out of a HTTP connection. As you already know please make sure you use this in a separate thread and not in the UI thread. That's it :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7565887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How could I pack a rack web-application includes infinite loop I want to pack a rack web-application in order to distribute it, In which a infinite loop resides. So it won't stop until my ctrl-c. But it seems ocra will only pack it when it ends 'naturally', and ctrl-c stopped the process. have been tring use exit or abort in callmethod of object being passed to rake. after which the whole process do not end, some trace info appears though. it is possible to invoke rake.run in a thread, and end application after given time. But I do not want to distribute a suicide version. so is there some more eligible and controllable way to normally end it ? not sure if this is a insane question, but thanks in advance. A: According to the OCRA docu, OCRA sets an environment variable OCRA_EXECUTABLE when being run. So you could check for that environment var in your code and break the loop if OCRA is running, e.g.: while true break if ENV.has_key? 'OCRA_EXECUTABLE' ... end
{ "language": "en", "url": "https://stackoverflow.com/questions/7565894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: fork and waitpid fail on linux. Without hitting the hard or soft limits I have a process that must create and close threads on demand. Each thread forks a new process using open2. Sometimes after executing the program for a long time open2 fails to fork the process sometimes and gives a "Can not allocate memory error", sometimes this happens for threads too.I know that the Linux has soft and hard limits but the number of the concurrent threads and processes for my server does not exceed those values. Is there something like a counter for number of processes and threads that eliminates thread and process creation after sometime? If it is so how servers like Postgres work for a long period of time? The project has multiple processes that communicate using TCP, but the part that causes the error that i described in a frond end to mplayer, that is written in Perl. The code is as follows: use strict; use warnings; use IO::Socket::INET; use IO::Select; use POSIX ":sys_wait_h"; use IPC::Open2; use 5.010; use Config; BEGIN { if(!$Config{useithreads}) { die "Your perl does not compiled with threading support."; } } use threads; use threads::shared; use constant { SERVER_PORT=>5000, #Remote request packet fields PACKET_REQTYPE=>0, PACKET_FILENAM=>1, PACKET_VOLMLVL=>2, PACKET_ENDPOSI=>3, PACKET_SEEKPOS=>4, #our request typs PLAY_REQUEST=>1, STOP_REQUEST=>2, INFO_REQUEST=>3, VOCH_REQUEST=>4, PAUS_REQUEST=>5, PLPA_REQUEST=>6, SEEK_REQUEST=>7, #Play states STATE_PAUS=>0, STATE_PLAY=>1, STATE_STOP=>2, }; #The following line must be added because of a bad behavior in the perl thread library that causes a SIGPIPE to be generated under heavy usage of the threads. $SIG{PIPE} = 'IGNORE'; #This variable holds the server socket object my $server_socket; #This array is used to hold objects of our all threads my @thread_objects; #create the server socket $server_socket=IO::Socket::INET->new(LocalPort=>SERVER_PORT,Listen=>20,Proto=>'tcp',Reuse=>1) or die "Creating socket error ($@)"; #Now try to accept remote connections print "Server socket created successfully now try to accept remote connections on port: ".SERVER_PORT."\n"; while(my $client_connection=$server_socket->accept()) { push @thread_objects,threads->create(\&player_thread,$client_connection); $thread_objects[$#thread_objects]->detach(); } #This subroutine is used to play something using tcp-based commands sub player_thread { my $client_socket=shift; #create a new select object my $selector=IO::Select->new($client_socket); #this variabe is used to pars our request my @remote_request; #getting th thread id of the current thread my $tid=threads->self()->tid; #This variable is used to hold the pid of mplayer child my $mp_pid=-1; #Mplayer stdin and stdout file descriptors my ($MP_STDIN,$MP_STDOUT); #This variable is used to check if we are playing something now or not my $is_playing=STATE_STOP; print "Client thread $tid created.\n"; while(1) { #check to see if we can read anything from our handler #print "Before select\n"; #my @ready=$selector->can_read(); #print "After select: @ready\n"; #now the data is ready for reading so we read it here my $data=<$client_socket>; #This means if the connection is closed by the remote end if(!defined($data)) { print "Remote connection has been closed in thread $tid mplayer id is: $mp_pid and state is: $is_playing.\n"; #if we have an mplayer child when remote connection is closed we must wait for it #so that is work is done if($mp_pid!=-1 and $is_playing ==STATE_PLAY) { waitpid $mp_pid,0; $is_playing=STATE_STOP; } elsif($is_playing==STATE_PAUS and $mp_pid!=-1) { print "thread $tid is in the paused state, we must kill mplayer.\n"; print $MP_STDIN "quit\n"; waitpid $mp_pid,0; $is_playing=STATE_STOP; } last; }#if #FIXME:: Here we must validate our argument #Now we try to execute the command chomp($data); @remote_request=split ",",$data; print "@remote_request\n"; #Trying to reap the death child and change the state of the thread my $dead_child=-1; $dead_child=&reaper($mp_pid); if($dead_child) { $is_playing=STATE_STOP; $mp_pid=-1; } given($remote_request[PACKET_REQTYPE]) { when($_==PLAY_REQUEST) { print "Play request\n"; if($is_playing==STATE_STOP) { eval{$mp_pid=open2($MP_STDOUT,$MP_STDIN,"mplayer -slave -really-quiet -softvol -volume ".$remote_request[PACKET_VOLMLVL]." -endpos ".$remote_request[PACKET_ENDPOSI]." ./".$remote_request[PACKET_FILENAM]);}; print "Some error occurred in open2 system call: $@\n" if $@; $is_playing=STATE_PLAY; print "Mplayer pid: $mp_pid.\n"; } } when($_==STOP_REQUEST) { print "Stop request\n"; if($is_playing != STATE_STOP) { print $MP_STDIN "pausing_keep stop\n"; #FIXME:: Maybe we should use WNOHANG here my $id=waitpid $mp_pid,0; print "Mplayer($id) stopped.\n"; $is_playing=STATE_STOP; $mp_pid=-1; } } when($_==PAUS_REQUEST) { print "pause request\n"; if($is_playing !=STATE_STOP) { print $MP_STDIN "pausing_keep pause\n"; $is_playing=STATE_PAUS; } } when($_==VOCH_REQUEST) { print "volume change request\n"; if($is_playing !=STATE_STOP) { print $MP_STDIN "pausing_keep volume ".$remote_request[PACKET_VOLMLVL]." 1\n"; } } when($_==INFO_REQUEST) { my $id; $id=&reaper($mp_pid); if($id > 0) { print "Mplayer($id) stopped.\n"; $is_playing=STATE_STOP; $mp_pid=-1; } given($is_playing) { when($_==STATE_STOP) { print $client_socket "Stopped\n"; } when($_==STATE_PAUS) { print $client_socket "Paused\n"; } when($_==STATE_PLAY) { print $client_socket "Playing\n"; } } } when ($_==PLPA_REQUEST) { print "play paused request\n"; if($is_playing==STATE_STOP) { eval{$mp_pid=open2($MP_STDOUT,$MP_STDIN,"mplayer -slave -really-quiet -softvol -volume ".$remote_request[PACKET_VOLMLVL]." -endpos ".$remote_request[PACKET_ENDPOSI]." ./".$remote_request[PACKET_FILENAM]);}; print "Some error occurred in open2 system call: $@\n" if $@; print $MP_STDIN "pausing_keep pause\n"; $is_playing=STATE_PAUS; } } when ($_==SEEK_REQUEST) { print "Seek request\n"; if($is_playing != STATE_STOP) { my $seek_pos=abs $remote_request[PACKET_SEEKPOS]; print $MP_STDIN "seek $seek_pos 2\n"; $is_playing=STATE_PLAY; } } default { warn "Invalid request($_)!!!"; next; } }#Given }#while $client_socket->close(); print "Thread $tid is exiting now, the child mplayer pid is: $mp_pid and state is: $is_playing.\n"; } #The following subroutine takes a pid and if that pid is grater than 0 it tries to reap it #if it is successful returns pid of the reaped process else 0 sub reaper { my $pid=shift; if($pid > 0) { my $id=waitpid($pid,WNOHANG); if($id > 0) { return $id; } } return 0; } A: "Can not allocate memory error" is what it says, either the user exceeded its memory quota (check with ulimit -m, compare to ps ux) or you're really out of memory (free). The limits for max user processes are only indirectly connected - if you fork() more processes then the user's memory quota permits, fork() will fail with ENOMEM. You also might want to see: What are some conditions that may cause fork() or system() calls to fail on Linux? A: I finally found the problem, it is because of a memory leak in the Perl's thread module that causes the memory to grow after a long time. Then open2 can not allocate memory and fails.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: direct mp3 file-transfer from a Kiosk to a smartphone I'm building a Kiosk, using a MacMini and an Elotouch display. It would load a CoreAnimation based App. that plays multimedia content following user touch-based choices. I'm in a early stage of the project. I can change the architecture/technology if needed. I need that my Kiosk could also distribute mp3 content to Smartphones close to it, wirelessly. For now I would like to support iOS and Android phones. I don't have any control on the smartphone side. The Kiosk is coin-operated (with time based session expiration) and connected to the web through a wifi network, managed by me. Can you tell me a common, safe and simple way to accomplish this? I thought to WebDav but I would like to explore alternatives, the simpler for the user-side the better. A: The best way to accomplish this is by using OBEX Push and bluetooth. There are plenty of command-line tools to list all bluetooth devices nearby, and to do a file transfer to one of them. The user would just need to activate bluetooth discovery on his cell phone, search for the phone on the kiosk, and select his phone. Another alternative is mail. WebDAV is a bad idea, because the user will have to type in the address (cumbersome!). A lot of photo kiosks are already using OBEX Push to receive photos from phones. The easiest is to provide different types of usb cables: micro-usb, mini-usb... Almost all cell phones can be attached as a USB disk nowadays. Summary: * OBEX Push * USB connect * Mail A: If you have one-time/session-based URLs, displaying a QR code on your kiosk screen would be one way to get the download URL to the device (and invalidated after successful download/session expiration); this would require a QR code reader which neither iOS nor Android have built in, though, but many users have one. Additionally, display the same URL that's encoded in the QR code using URL shortener service like bit.ly, goo.gl, etc. for the user to type in. This way there's no set up for the user, no funny business with pushing data to the user (privacy/security concerns) and every smartphone does have a web browser.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to use multiple link styles in css? Is it possible like lets say the text in the div header has a red hover, and the text in the div in the footer a white hover? Or is this just not possible and can you only set 1 style for the whole document? A: This is very much possible, just like any other element you can style them separately by being more specific. If you have this HTML: <div id="top"> <a href="#">First link</a> </div> <div id="bot"> <a href="#">Second link</a> </div> With this CSS you would style both links: a:hover { color: #000; } With this CSS you can style them separately: #top a:hover { color: #f00; } #bot a:hover { color: #fff; } A: You can set as pretty much as many as you want to if you just hook it right: /* every a:hover has color red */ a:hover { color: red; } /* #footer a:hover has color green. */ #footer a:hover { color: green; } /* Every link that has class ".ThisClass" will have yellow color */ a.ThisClass:hover { color: yellow; } A: Yes this is possible. #header a:hover { color: #f00; } #footer a:hover { color: #0f0; } http://jsfiddle.net/wrygB/2/ You may want to split this though so you can use the same hovers elsewhere. In which case you would do: .main:hover { color: #f00; } .sub:hover { color: #0f0; } And then you can apply a class of main or sub to any element to get the hover effect. A: Well you'd just select the element the a:link is within, and apply styles like that. i.e #header a:hover { color: red; } #footer a:hover { color: white; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7565907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to run java class in JAR file in maven target directory? I would like to run my Izpack installer after maven build, but I am getting following output after executing "mvn test": [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building RS IzPack installer [INFO] task-segment: [test] [INFO] ------------------------------------------------------------------------ [debug] execute contextualize [INFO] [resources:copy-resources {execution: copy-resources}] [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 109 resources [INFO] Copying 4 resources [INFO] Preparing exec:java [WARNING] Removing: java from forked lifecycle, to prevent recursive invocation. [debug] execute contextualize [INFO] [resources:copy-resources {execution: copy-resources}] [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 109 resources [INFO] Copying 4 resources [INFO] [exec:java {execution: default}] [WARNING] java.lang.ClassNotFoundException: com.izforge.izpack.installer.Installer at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:285) at java.lang.Thread.run(Thread.java:595) [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] An exception occured while executing the Java class. com.izforge.izpack.installer.Installer Looks like I have to somehow put generated jar file into classpath, any ideas? Excerpt from my pom.xml : <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <phase>test</phase> <goals> <goal>java</goal> <!-- "exec" also possible --> </goals> <configuration> <mainClass>com.izforge.izpack.installer.Installer</mainClass> <arguments> <argument>-console</argument> <!-- <argument>arg1</argument> --> </arguments> </configuration> </execution> </executions> </plugin> Apache Maven 2.2.1 (r801777; 2009-08-06 21:16:01+0200) Java version: 1.6.0_20 Java home: C:\Java\jdk16\jre Default locale: en_GB, platform encoding: Cp1252 OS name: "windows xp" version: "5.1" arch: "x86" Family: "windows" Martin A: Have you looked inside of jar ? It can be that maven didn't included needed classes into jar. A: I think You should define the classpath for the java command using -classpath. You need to construct a classpath that will contain Your main class com.izforge.izpack.installer.Installer and all it's dependencies. It can be in a jar, or a class folder or multiple jars. See Wikipedia on how to define a classpath for java call. A: You can use something like that to define a dependency for that execution: <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <phase>test</phase> <goals> <goal>java</goal> <!-- "exec" also possible --> </goals> <configuration> <mainClass>com.izforge.izpack.installer.Installer</mainClass> <arguments> <argument>-console</argument> <!-- <argument>arg1</argument> --> </arguments> </configuration> </execution> </executions> <dependencies> <dependency> <groupId>org.codehaus.izpack</groupId> <artifactId>izpack-standalone-compiler</artifactId> <version>4.3.4</version> <scope>compile</scope> </dependency> </dependencies> But there is also a Maven plugin for izpack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to determine to which extent/level an array of integers is already sorted Consider an array of any given unique integers e.g. [1,3,2,4,6,5] how would one determine the level of "sortedness", ranging from 0.0 to 1.0 ? A: One way would be to evaluate the number of items that would have to be moved to make it sorted and then divide that by the total number of items. As a first approach, I would detect the former as just the number of times a transition occurs from higher to lower value. In your list, that would be: 3 -> 2 6 -> 5 for a total of two movements. Dividing that by six elements gives you 33%. In a way, this makes sense since you can simply move the 2 to between 1 and 3, and the 5 to between 4 and 6. Now there may be edge cases where it's more efficient to move things differently but then you're likely going to have to write really complicated search algorithms to find the best solution. Personally, I'd start with the simplest option that gave you what you wanted and only bother expanding if it turns out to be inadequate. A: Ok this is just an idea, but what if you can actually sort the array, i.e. 1,2,3,4,5,6 then get it as a string 123456 now get your original array in string 132465 and compare the Levenshtein distance between the two A: I would say the number of swaps is not a very good way to determine this. Most importantly because you can sort the array using a different number of swaps. In your case, you could switch 2<-->3 and 6<-->5, but you could also do a lot more switches. How would you sort, say: 1 4 3 2 5 Would you directly switch 2 and 4, or would you switch 3 and 4, then 4 and 2, and then 3 and 2. I would say a more correct method would be the number of elements in the right place divided by the total number of elements. In your case, that would be 2/6. A: I'll propose a different approach: let's count the number of non-descending sequences k in the array, then take its reversal: 1/k. For perfectly sorted array there's only one such sequence, 1/k = 1/1 = 1. This "unsortedness" level is the lowest when the array is sorted descendingly. 0 level is approached only asymptotically when the size of the array approaches infinity. This simple approach can be computed in O(n) time. A: You could sum up the distances to their sorted position, for each item, and divide with the maximum such number. public static <T extends Comparable<T>> double sortedMeasure(final T[] items) { int n = items.length; // Find the sorted positions Integer[] sorted = new Integer[n]; for (int i = 0; i < n; i++) { sorted[i] = i; } Arrays.sort(sorted, new Comparator<Integer>() { public int compare(Integer i1, Integer i2) { T o1 = items[i1]; T o2 = items[i2]; return o1.compareTo(o2); } public boolean equals(Object other) { return this == other; } }); // Sum up the distances int sum = 0; for (int i = 0; i < n; i++) { sum += Math.abs(sorted[i] - i); } // Calculate the maximum int maximum = n*n/2; // Return the ratio return (double) sum / maximum; } Example: sortedMeasure(new Integer[] {1, 2, 3, 4, 5}) // -> 0.000 sortedMeasure(new Integer[] {1, 5, 2, 4, 3}) // -> 0.500 sortedMeasure(new Integer[] {5, 1, 4, 2, 3}) // -> 0.833 sortedMeasure(new Integer[] {5, 4, 3, 2, 1}) // -> 1.000 A: In practice, one would measure unsortedness by the amount of work it needs to get sorted. That depends on what you consider "work". If only swaps are allowed, you could count the number op swaps needed. That has a nice upper bound of (n-1). For a mergesort kind of view you are mostly interested in the number of runs, since you'll need about log (nrun) merge steps. Statistically, you would probably take "sum(abs((rank - intended_rank))" as a measure, similar to a K-S test. But at eyesight, sequences like "HABCDEFG" (7 swaps, 2 runs, submean distance) and "HGFEDCBA" (4 swaps, 8 runs, maximal distance) are always showstoppers. A: One relevant measurement of sortedness would be "number of permutations needed to be sorted". In your case that would be 2, switching the 3,2 and 6,5. Then remains how to map this to [0,1]. You could calculate the maximum number of permutations needed for the length of the array, some sort of a "maximum unsortedness", which should yield a sortedness value of 0. Then take the number of permutations for the actual array, subtract it from the max and divide by max.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Detect that a hidden form field has changed? I am using a hidden form field to store the current record that an user is editing. How can I prevent the user from changing that field? Would MVC3's anti-forgery helpers work, or do I need to roll my own checks? A: See How to detect if form field has changed without using hidden field Suggestions there are to use a hash and compare on postback to check if changes have been made. A: Edit Seems I misunterstood your question, sorry. Indeed, AntiForgeryToken won't help you prevent that. You can either store these non-editable informations in your Model (in my example the Account class) without exposing it or in your Session. You can also put some checking/event-raising in your model's properties to detect unwanted edition. Old-misunterstood-answer You can use the HtmlHelper method HtmlHelper.AntiForgeryToken 1/In your form: @using (Html.BeginForm("Edit", "User", FormMethod.Post)) { @Html.ValidationSummary(true) <fieldset> <legend>Account</legend> <div class="editor-label"> @Html.LabelFor(model => model.FirstName) </div> <div class="editor-field"> @Html.EditorFor(model => model.FirstName) @Html.ValidationMessageFor(model => model.FirstName) </div> //Your other fields <p> @Html.AntiForgeryToken() <input type="submit" value="Create" /> </p> </fieldset> } 2/ In your Post action method: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(Models.Account account) Take note that AntiForgeryToken only works with POST request and that cookies must be (obviously) enabled :). A: Rather than trying to check if the user changed anything, you should check that they are permitted to edit what ever record is indicated by the ID submitted. If they are allowed to edit the ID in question, let them do it. If not, don't. Don't even bother worrying about whether they have changed the form data, which is trivial to do. Antiforgery tokens don't really serve any purpose then, btw. A: For prevent CSRF attacks, you can use Html.AntiForgeryToken helper method in your form section
{ "language": "en", "url": "https://stackoverflow.com/questions/7565926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use more than one list item click that extends Activity implements onClicklistener I'm using 3 listviews created in java code in my program. I use extends Activity that implements onitemclicklistener. Now, how to make different item click event for each listviwe separately? Any help is appreciated and thanks in advance. A: public void onItemClick(AdapterView<?> adapter, View view, int index, long id) { switch(view.getId()) { case <listview1 Id> : //call method 1; break; case <listview2 Id> : //call method 2; break; case <listview3 Id> : //call method 3; break; } } This is a bad method.You should implement different classes for listeners.So you can modularize your code. A: Don't implement OnItemClickListener in the Activity, instead use separate classes, for instance anonimous classes. Or use a single listener, and detect the source of the event via the view parameter in the callback method. A: if you see onItemClick(AdapterView<?> parent, View view, int position, long id) It has parent AdapterView. so you can check on which adapter view it is clicked on. I personally feel not to implement onItemClickListner for this type of instances. use setOnItemClickListener(listener1) ... and so on for the 3 listViews. it's better. You can write separate listeners for each of your listView. HTH. A: You need to create a new onItemClickLIstener for each of your ListView's. You do so like this: listView1.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapter, View view, int index, long id) { } });
{ "language": "en", "url": "https://stackoverflow.com/questions/7565928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GWT-Platform: where the business logic should go? I just got the grip on GWTP and the MVP, GIN and Dispatch. With dispatch there is a Handler class which defines what the action does and returns something accordingly. So far I found myself with a case where I have 2 actions that require to execute the same method. For which I believe ActionHandling is not where the bussiness logic goes, but that it should go in a layer behind it which pass something to it somehow How should I layout my logic? I would like to use Hibernate later on btw. EDIT: as a note, applying the answers provided on practice, what needs to be done is: 1.- Create a module class that extends AbstractModule, this contains bind(Service.class).to(ServiceImpl.class); 2.- on your GuiceServletcontextListener add your serviceModule to the getInjector method return: return Guice.createInjector(new ServerModule(), new DispatchServletModule(), new ServiceModule()); 3.- On yours actionHandlers constructors have something like this @Inject TestHandler(Service service) { this.service=service } A: Business logic should be in your business objects, which are independent from your Handler classes. Try to design your business layer in a technology-agnostic way. The handlers delegate all significant processing to the business objects, so they (the handlers) should be pretty thin actually. A: You could try to inject the service layer into the handler. The service can be created as a singleton. @Inject public MyHandler(MyService service) { this.service = service; } A: Is MyService an interface? If yes, you forgot to bind it inside Guice. Personnaly I use DAOs to put my logic between ActionHandlers and my persistence framework (Hybernate, Objectify, Twig-Persist, etc.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7565930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Reduce the size of the image android How can i reduce the size of the image android programatically. Size of image can be set in grid view. Is it possible to set the size of image displayed in Edit Text that is received from grid view selected image. I have set of images in my gridview. I can reduce the size of the image in grid view display. so when i selct the image in gridview i get the image in edittext with its original size of image bigger. How can i reduce the size to small image. Please guide me in this issue. Any sample working example shall be very useful for me to understand and work accordingly. Thanks in advance. Regards A: You should try something like this, Reduce Image Size
{ "language": "en", "url": "https://stackoverflow.com/questions/7565931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: N:M Relation Syntax Error in code I have this SQL (for MySQL): create table apartmentcaretakers ( apartmentID int, caretakerID int, PRIMARY KEY (apartmentID, caretakerID), FOREIGN KEY (apartmentID) REFERENCES apartments(apartmentID), FOREIGN KEY (caretakerID) REFERENCES caretakers(caretakerID) )engine = innodb; The error that I cat: SQL syntax error near 'references apartments(apartmentID), foreign key caretakerID references caretakers' This is properly some minor mistake on my part, but could someone please point it out? EDIT: After some coding and rerunning, the error is 1064. Which I can understand why it didn't really help, as it's a broad spectrum error. A: Worked for me aswell. Make sure your referenced tables also use the INNODB engine. Use the following query to check that: SHOW TABLE STATUS WHERE Name = 'xxx' mysql> CREATE TABLE apartments ( -> apartmentID int PRIMARY KEY NOT NULL) ENGINE = innodb; Query OK, 0 rows affected (0.01 sec) mysql> CREATE TABLE caretakers ( -> caretakerID int PRIMARY KEY NOT NULL) ENGINE = innodb; Query OK, 0 rows affected (0.02 sec) mysql> CREATE TABLE apartmentcaretakers ( -> apartmentID int, -> caretakerID int, -> PRIMARY KEY (apartmentID, caretakerID), -> FOREIGN KEY ac_fk_apartments_id (apartmentID) REFERENCES apartments (apartmentID), -> FOREIGN KEY ac_fk_caretakers_id(caretakerID) REFERENCES caretakers (caretakerID) -> ) ENGINE = innodb; Query OK, 0 rows affected (0.02 sec)
{ "language": "en", "url": "https://stackoverflow.com/questions/7565937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: cout does no print in QtCreator I saw this question already on this forum but I do not know why the proposed answer does not work in my case. So I try to ask for other slution. I just got my Qt creator running under Linux. I do not understand why my: cout << "This does not appear"; Does not print in console while qdebug does qDebug() << "This appears"; This is what is contained in my .pro file: QT += core gui TARGET = aaa TEMPLATE = app SOURCES += main.cpp\ mainwindow.cpp \ IeplcModule.cpp HEADERS += mainwindow.h \ IeplcModule.h FORMS += mainwindow.ui #enable console CONFIG += console Any idea? A: When debugging with CDB (Windows debugger) and running application not in the dedicated terminal window, but within QtCreator output panel, there is an issue with std::cout/std::cerr. qDebug works because it has a trick for this case. So, the only solution in this case is enable the "run in terminal" option. For more infor please follow the link above to the Qt bug tracker. A: Try with: cout << "asdf" << endl; Possibly Qt sets up iostream in order to flush only at new line. A: Is it possible that STDOUT is redirecting? qDebug prints to STDERR by default. A: Did you #include <iostream>? I did not see any includes in the code. I assume that qdebug and cout are very similar. A: Make sure you have console config enabled in your .pro file. I.e. : CONFIG += console A: You can run this program from CMD and it will print some messages to the console: /* Create a .pro file with this content: QT += core gui widgets SOURCES += main.cpp TARGET = app ------------------------------- Build and run commands for CMD: > qmake -makefile > mingw32-make > "release/app" */ #ifdef _WIN32 #include <windows.h> #endif #include <QtCore/QFile> #include <QtCore/QString> #include <QtCore/QIODevice> #include <QtWidgets/QApplication> #include <QtWidgets/QWidget> #include <iostream> class Widget : public QWidget { public: Widget() { setWindowTitle("My Title"); QString path("assets/text.txt"); std::cout << std::endl; std::cout << "hello1" << std::endl; std::cout << path.toStdString() << std::endl; std::cout << "hello2" << std::endl; } }; int main(int argc, char *argv[]) { #ifdef _WIN32 if (AttachConsole(ATTACH_PARENT_PROCESS)) { freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); } #endif QApplication app(argc, argv); Widget w; w.show(); return app.exec(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7565941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Android MP4 playback issue from URL I am trying to play mp4 video from URL but my phone always give me error "sorry this video can not be played" instead if i download video from same URL then video plays fine at phone. http://beta-vidizmo.com/hilton.mp4 Please tell me what i am doing wrong? A: It also depends on the android version. Droid X and Samsung Captivate had a lot of trouble streaming MP4 files when it was in version 2.1, but after the Gingerbread update a lot of androids had this problem fixed. Make sure you encode the video so that the moov atom is bought to the beginning. I think you can do this with QT Faststart.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565945", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to control Primary Menu links using Secondary Menu's Drupal 6? I got a secondary menu with two items "English" & "Spanish" and Primary Menu with main site links. We are not using Langauage transliation, we got separate records in database for each langauages. So how can I make all Primary Menu links to select appropriate nodes(for each languages) when user select the secondary menu ? That's is there any way to change the primary menu links while selecting the secondary menu ? or replace primary menu items using secondary menu ? Please give me any info on this topic which can lead me to do this task ! A: That would take an awful lot of coding, you should use the transliteration module for this. If you don't you'll just end up rewriting a significant portion of that module just to get exactly the same functionality. Don't reinvent the wheel, if a solution has already been made for your problem - use it!
{ "language": "en", "url": "https://stackoverflow.com/questions/7565947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the harm of retain self in block?(Objective-C, GCD) In many guide about how to use blocks and GCD, one tip is always mentioned : do not retain self in block. The detail is when defining a block, if you reference self or a ivar of self, then self is retained by the block. So the work around is to use __block modifier to get a weakSelf or weakIvar. But what's the harm of not doing that? If the block retains self, it should release self when the block is finished(Am I right about this?). So ultimately the reference count of self is balanced. I know if self retains the block and the block retains self, it would be a retain cycle.Neither the block and self will be deallocated. But if using GCD, self don't retain the block, why not let the block retain self? A: There is no harm in retaining self unless the block stays around. If you are using GCD to execute the block and then it is removed then that is fine. It is only a problem if self has a reference to the block that it keeps around (i.e self.someBlock = ^{self.x = 2;}) because then you have a retain cycle. Personally I like the block retaining self (if used) in GCD as you have no real control over when the block executes and it cannot be canceled, so it may execute after self is deallocated if it is not retained.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: python dictionary- two keys to each value Hi I am fairly sure you can't do this but I was wondering if you could have a dictionary where each of the values can be accessed via two keys without duplicating the dictionary. The reason I want to do this is that the two keys will represent the same thing but one will be a shortened version eg. 'TYR' and 'Y' will both have the same value. A: Just place same (mutable) object in two places. If you change the object it will change in both places in the dictionary. Only donwside is that you have to add and delete both explicitly (you could create some helper method though). In [4]: d = {} In [5]: c = [1,2] In [7]: d[1] = c In [8]: d[2] = c In [9]: d Out[9]: {1: [1, 2], 2: [1, 2]} In [10]: c.append(3) In [11]: d Out[11]: {1: [1, 2, 3], 2: [1, 2, 3]} If you want to store unmutable types like string and tuple, you probably need to create object that will store in them and change it inside that object.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: MediaPlayer : How to update progress every second? I'm programming a videoplayer program and i'm searching to see the way the progress bar and time got updated every second while mediaplayer is playing. I have been looking at VideoView and MediaPlayer class , but i have no found if it use a hypothetically "OnEverySecondUpdate" Listener or whatever nice (or ugly) process to do it the good way. Any idea? P.D : I don't use a VideoView component , i'm using a SurfaceView . A: Use Handler method: postDelayed. In runnable just put postDelayed again with second interval. A: I found two relevant methods in MediaPlayer: /** * Gets the current playback position. * * @return the current position in milliseconds */ public native int getCurrentPosition(); /** * Gets the duration of the file. * * @return the duration in milliseconds */ public native int getDuration(); This is enough for u.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: FFmpeg fade effects between frames I want to create a slideshow of my images with fade in & fade out transitions between them and i am using FFmpeg fade filter. If I use command: ffmpeg -i input.mp4 "fade=in:5:8" output.mp4 To create the output video with fade effect, then it gives output video with first 5 frames black and than images are shown with fade in effect but i want fade:in:out effect between frame change. How can i do that? Please tell a solution for Centos server because i am using FFmpeg on this server only A: To create a video with fade effect, just break the video into parts and create separate videos for each image. For instance, if you have 5 images then firstly, create 50-60 copies of each image and obtain a video for that: $command= "ffmpeg -r 20 -i images/%d.jpg -y -s 320x240 -aspect 4:3 slideshow/frame.mp4"; exec($command." 2>&1", $output); This will allow you to create 5 different videos. Then, you need 10-12 different copies of those five images and again create separate videos with fade effects. ffmpeg -i input.mp4 "fade=in:5:8" output.mp4 After this you will have videos like: video for image 1 and its fade effect then for image 2 and its fade effect and so on. Now combine those videos in respective order to get the whole video. For combining the videos you need: $command = "cat pass.mpg slideshow/frame.mpg > final.mpg"; This means to join the videos using cat and then you need to convert them to mpg, join them and again reconvert them to mp4 or avi to view them properly. Also the converted mpg videos will not be proper so do not bother. When you convert them to mp4, it will be working fine. A: You can make a slideshow with crossfading between the pictures, by using the framerate filter. In the following example 0.25 is the framerate used for reading in the pictures, in this case 4 seconds for each picture. The parameter fps sets the output framerate. The parameters interp_start and interp_end can be used for changing the fading effect: interp_start=128:interp_end=128 means no fading at all. interp_start=0:interp_end=255 means continuous fading. When one picture has faded out and the next picture has fully faded in, the third picture will immediately begin to fade in. There is no pause for showing the second picture. interp_start=64:interp_end=191 means half of the time is pause for showing the pictures and the other half is fading. Unfortunately it won't be a full fading from 0 to 100%, but only from 25% to 75%. That's not exactly what you might want, but better than no fading at all. ffmpeg -framerate 0.25 -i IMG_%3d.jpg -vf "framerate=fps=30:interp_start=64:interp_end=192:scene=100" test.mp4 A: You can use gifblender to create the blended, intermediary frames from your images and then convert those to a movie with ffmpeg.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Android GL ES2 buffer issue: garbled data I am trying to save whatever is rendered on screen in a Open GL ES2 application, by not calling glClear on a renderbuffer or the framebuffer. This has been working fine on a physical Nook Color. But when running on physical Nexus One (running android 2.3.6), I a getting issues where the content of the buffer is garbled after the first render. For illustration purpose, the screens below shows how the same code looks like in Nexus One and Nook Color. The code is almost verbatim from com.example.android.apis.graphics.GLES20TriangleRenderer (level 8 example source code set). /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.apis.graphics; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLUtils; import android.opengl.Matrix; import android.os.SystemClock; import android.util.Log; import com.example.android.apis.R; class GLES20TriangleRenderer implements GLSurfaceView.Renderer { public GLES20TriangleRenderer(Context context) { mContext = context; mTriangleVertices = ByteBuffer.allocateDirect(mTriangleVerticesData.length * FLOAT_SIZE_BYTES).order(ByteOrder.nativeOrder()).asFloatBuffer(); mTriangleVertices.put(mTriangleVerticesData).position(0); } public void onDrawFrame(GL10 glUnused) { // Ignore the passed-in GL10 interface, and use the GLES20 // class's static methods instead. GLES20.glClearColor(0.0f, 0.0f, 1.0f, 1.0f); GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT); GLES20.glUseProgram(mProgram); checkGlError("glUseProgram"); GLES20.glActiveTexture(GLES20.GL_TEXTURE0); GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureID); mTriangleVertices.position(TRIANGLE_VERTICES_DATA_POS_OFFSET); GLES20.glVertexAttribPointer(maPositionHandle, 3, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices); checkGlError("glVertexAttribPointer maPosition"); mTriangleVertices.position(TRIANGLE_VERTICES_DATA_UV_OFFSET); GLES20.glEnableVertexAttribArray(maPositionHandle); checkGlError("glEnableVertexAttribArray maPositionHandle"); GLES20.glVertexAttribPointer(maTextureHandle, 2, GLES20.GL_FLOAT, false, TRIANGLE_VERTICES_DATA_STRIDE_BYTES, mTriangleVertices); checkGlError("glVertexAttribPointer maTextureHandle"); GLES20.glEnableVertexAttribArray(maTextureHandle); checkGlError("glEnableVertexAttribArray maTextureHandle"); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); Matrix.setRotateM(mMMatrix, 0, angle, 0, 0, 1.0f); Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, mMMatrix, 0); Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0); GLES20.glUniformMatrix4fv(muMVPMatrixHandle, 1, false, mMVPMatrix, 0); GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3); checkGlError("glDrawArrays"); } public void onSurfaceChanged(GL10 glUnused, int width, int height) { // Ignore the passed-in GL10 interface, and use the GLES20 // class's static methods instead. GLES20.glViewport(0, 0, width, height); float ratio = (float) width / height; Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7); } public void onSurfaceCreated(GL10 glUnused, EGLConfig config) { // Ignore the passed-in GL10 interface, and use the GLES20 // class's static methods instead. mProgram = createProgram(mVertexShader, mFragmentShader); if (mProgram == 0) { return; } maPositionHandle = GLES20.glGetAttribLocation(mProgram, "aPosition"); checkGlError("glGetAttribLocation aPosition"); if (maPositionHandle == -1) { throw new RuntimeException("Could not get attrib location for aPosition"); } maTextureHandle = GLES20.glGetAttribLocation(mProgram, "aTextureCoord"); checkGlError("glGetAttribLocation aTextureCoord"); if (maTextureHandle == -1) { throw new RuntimeException("Could not get attrib location for aTextureCoord"); } muMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix"); checkGlError("glGetUniformLocation uMVPMatrix"); if (muMVPMatrixHandle == -1) { throw new RuntimeException("Could not get attrib location for uMVPMatrix"); } /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; GLES20.glGenTextures(1, textures, 0); mTextureID = textures[0]; GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, mTextureID); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST); GLES20.glTexParameterf(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_REPEAT); GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_REPEAT); InputStream is = mContext.getResources() .openRawResource(R.raw.robot); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); Matrix.setLookAtM(mVMatrix, 0, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); } private int loadShader(int shaderType, String source) { int shader = GLES20.glCreateShader(shaderType); if (shader != 0) { GLES20.glShaderSource(shader, source); GLES20.glCompileShader(shader); int[] compiled = new int[1]; GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0); if (compiled[0] == 0) { Log.e(TAG, "Could not compile shader " + shaderType + ":"); Log.e(TAG, GLES20.glGetShaderInfoLog(shader)); GLES20.glDeleteShader(shader); shader = 0; } } return shader; } private int createProgram(String vertexSource, String fragmentSource) { int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource); if (vertexShader == 0) { return 0; } int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource); if (pixelShader == 0) { return 0; } int program = GLES20.glCreateProgram(); if (program != 0) { GLES20.glAttachShader(program, vertexShader); checkGlError("glAttachShader"); GLES20.glAttachShader(program, pixelShader); checkGlError("glAttachShader"); GLES20.glLinkProgram(program); int[] linkStatus = new int[1]; GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0); if (linkStatus[0] != GLES20.GL_TRUE) { Log.e(TAG, "Could not link program: "); Log.e(TAG, GLES20.glGetProgramInfoLog(program)); GLES20.glDeleteProgram(program); program = 0; } } return program; } private void checkGlError(String op) { int error; while ((error = GLES20.glGetError()) != GLES20.GL_NO_ERROR) { Log.e(TAG, op + ": glError " + error); throw new RuntimeException(op + ": glError " + error); } } private static final int FLOAT_SIZE_BYTES = 4; private static final int TRIANGLE_VERTICES_DATA_STRIDE_BYTES = 5 * FLOAT_SIZE_BYTES; private static final int TRIANGLE_VERTICES_DATA_POS_OFFSET = 0; private static final int TRIANGLE_VERTICES_DATA_UV_OFFSET = 3; private final float[] mTriangleVerticesData = { // X, Y, Z, U, V -1.0f, -0.5f, 0, -0.5f, 0.0f, 1.0f, -0.5f, 0, 1.5f, -0.0f, 0.0f, 1.11803399f, 0, 0.5f, 1.61803399f }; private FloatBuffer mTriangleVertices; private final String mVertexShader = "uniform mat4 uMVPMatrix;\n" + "attribute vec4 aPosition;\n" + "attribute vec2 aTextureCoord;\n" + "varying vec2 vTextureCoord;\n" + "void main() {\n" + " gl_Position = uMVPMatrix * aPosition;\n" + " vTextureCoord = aTextureCoord;\n" + "}\n"; private final String mFragmentShader = "precision mediump float;\n" + "varying vec2 vTextureCoord;\n" + "uniform sampler2D sTexture;\n" + "void main() {\n" + " gl_FragColor = texture2D(sTexture, vTextureCoord);\n" + "}\n"; private float[] mMVPMatrix = new float[16]; private float[] mProjMatrix = new float[16]; private float[] mMMatrix = new float[16]; private float[] mVMatrix = new float[16]; private int mProgram; private int mTextureID; private int muMVPMatrixHandle; private int maPositionHandle; private int maTextureHandle; private Context mContext; private static String TAG = "GLES20TriangleRenderer"; } The difference is that I removed the glClear call so it becomes like this: public void onDrawFrame(GL10 glUnused) { // Ignore the passed-in GL10 interface, and use the GLES20 // class's static methods instead. //GLES20.glClearColor(0.0f, 0.0f, 1.0f, 1.0f); GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT);// | GLES20.GL_COLOR_BUFFER_BIT); That code basically rotates the rectangle in the center. I have also tried rendering to a texture renderbuffer and then rendering the renderbuffer texture and encountered the same result (the render buffer gets garbled after the first call to GLES20.glDrawArrays with the result looking pretty much identical to the bad screenshot). I'm new to ES2. What am I doing wrong? Bad (on Nexus One): http://www.putpix.com/b/files/2849/devicebad.png Good (on Nook Color): http://www.putpix.com/b/files/2849/devicegood.png A: If you don't call clear, the result is undefined. In particular, the screen is often double-buffered so your program will be seeing multiple buffers presented at different times. There's also no obligation that the buffers are ever the same ones you've seen before.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how put an image over embeded flash in asp.net pages - z-index not help my aspx codes : <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Building.Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Test Web Page</title> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script> <script src="Scripts/bgstretcher.js" type="text/javascript"></script> <link href="css/bgstretcher.css" rel="stylesheet" type="text/css" /> <link href="css/Default.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div id="OuterDiv"> <div id="InnerDiv"> <div id="Content"> <div id="BMSFlashContainer"> <object id="BMSFlash" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="281" height="375" align="middle"> <param name="allowScriptAccess" value="sameDomain" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="Flashes/BMS.swf" /> <param name="quality" value="high" /> <param name="bgcolor" value="#000000" /> <embed name="BMSFlash" src="Flashes/BMS.swf" quality="high" bgcolor="#000000" width="281" height="375" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" /> </object> </div> </div> </div> </div> </form> </body> </html> and css codes : body { position: relative; background-color: #f1f1f1; } body, input, option, select { direction: rtl; font-family: Tahoma, 'b yekan' , 'b homa' , 'Arial' , 'Verdana' , Sans-Serif; font-size: 9pt; margin: 0px; padding: 0px; color: white; background: #a099ff url('../Images/back.jpg') no-repeat scroll left top; } a:link, a:visited { color: #0061B7; } a:hover, a:active { color: #1BB2FD; } a img { border: none; } .label { font-weight: bold; } div#OuterDiv { margin: 0px; padding: 0px; width: 100%; } div#InnerDiv { position: relative; width: 900px; height: 100%; margin: 0 auto; background: transparent url('../Images/Blue.png') repeat scroll left top; } #LiveContainer { position: fixed; top: 0px; left: 0px; z-index:1000; } #imgLive { width: 200px; } #BMSFlashContainer { position:absolute; top:0px; left:0px; border:3px solid red; } that embeded flash (BMSFlash) Is always over imgLive Image -> how can i fix this issue? A: Change: <param name="bgcolor" value="#000000" /> <embed name="BMSFlash" src="Flashes/BMS.swf" quality="high" bgcolor="#000000" width="281" height="375" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" /> To: <param name="wmode" value="transparent" /> <embed wmode="transparent" name="BMSFlash" src="Flashes/BMS.swf" quality="high" width="281" height="375" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7565965", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Two basic ANTLR questions I'm trying to use ANTLR to take a simple grammar and produce assembly output. My language of choice in ANTLR is Python. Many tutorials seem very complicated or elaborate on things that aren't relevant to me; I only really need some very simple functionality. So I have two questions: 'Returning' values from one rule to another. So let's say I have a rule like: assignment: name=IDENTIFIER ASSIGNMENT expression; I can run Python code in {}s when this rule is recognised, and I can pass args to the Python code for expression by doing something like: assignment: name=IDENTIFIER ASSIGNMENT expression[variablesList]; and then expression[variablesList]: blah blah But how do I 'return' a value to my original rule? E.g. how do I calculate the value of the expression and then send it back to my assignment rule to use in Python there? How do I write out my target language code? So I have some Python which runs when the rules are recognised, then I calculate the assembly I want that statement to produce. But how do I say "write out this string of assembly instructions to my target file"? Any good tutorials that are relevant to this kind of stuff (attribute grammars, compiling to something other than an AST, etc.) would be helpful too. If my questions don't make too much sense, please ask me to clarify; I'm having a hard time wrapping my head around ANTLR. A: Returning values from one rule to another Let's say you want to parse simple expressions and provide a map of variables at runtime that can be used in these expressions. A simple grammar including the custom Python code, returns statements from the rules, and the parameter vars to the entry point of your grammar could look like this: grammar T; options { language=Python; } @members { variables = {} } parse_with [vars] returns [value] @init{self.variables = vars} : expression EOF {value = $expression.value} ; expression returns [value] : addition {value = $addition.value} ; addition returns [value] : e1=multiplication {value = $e1.value} ( '+' e2=multiplication {value = value + $e2.value} | '-' e2=multiplication {value = value - $e2.value} )* ; multiplication returns [value] : e1=unary {value = $e1.value} ( '*' e2=unary {value = value * $e2.value} | '/' e2=unary {value = value / $e2.value} )* ; unary returns [value] : '-' atom {value = -1 * $atom.value} | atom {value = $atom.value} ; atom returns [value] : Number {value = float($Number.text)} | ID {value = self.variables[$ID.text]} | '(' expression ')' {value = $expression.value} ; Number : '0'..'9'+ ('.' '0'..'9'+)?; ID : ('a'..'z' | 'A'..'Z')+; Space : ' ' {$channel=HIDDEN}; If you now generate a parser using ANTLR v3.1.3 (no later version!): java -cp antlr-3.1.3.jar org.antlr.Tool T.g and run the script: #!/usr/bin/env python import antlr3 from antlr3 import * from TLexer import * from TParser import * input = 'a + (1.0 + 2) * 3' lexer = TLexer(antlr3.ANTLRStringStream(input)) parser = TParser(antlr3.CommonTokenStream(lexer)) print '{0} = {1}'.format(input, parser.parse_with({'a':42})) you will see the following output being printed: a + (1.0 + 2) * 3 = 51.0 Note that you can define more than a single "return" type: parse : foo {print 'a={0} b={1} c={2}'.format($foo.a, $foo.b, $foo.c)} ; foo returns [a, b, c] : A B C {a=$A.text; b=$B.text; b=$C.text} ; How to write out a target language code The easiest to go about this is to simply put print statements inside the custom code blocks and pipe the output to a file: parse_with [vars] @init{self.variables = vars} : expression EOF {print 'OUT:', $expression.value} ; and then run the script like this: ./run.py > out.txt which will create a file 'out.txt' containing: OUT: 51.0. If your grammar isn't that big, you might get away with this. However, this might become a bit messy, in which case you could set the output of your parser to template: options { output=template; language=Python; } and emit custom code through your own defined templates. See: * *StringTemplate: 5 minute Introduction *Where to get Python ANTLR package to use StringTemplate?
{ "language": "en", "url": "https://stackoverflow.com/questions/7565974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Strange Problem with MGTwitterEngine for ipad I am stuck with the strange problem of MGTwitterEngine for iPad because when I use it for iPhone it works perfectly but when I use it for iPad then in method below(delegate method) I am getting username as null but in iPhone it was giving correct(eg.soha00) Code for calling MGTwitterEngine:- -(IBAction)loginWithTwitterButtonClicked:(UIButton *)sender { _engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self]; _engine.consumerKey = @"PzkZj9g57ah2bcB58mD4Q"; _engine.consumerSecret = @"OvogWpara8xybjMUDGcLklOeZSF12xnYHLE37rel2g"; UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self]; if (controller) { [self presentModalViewController: controller animated: YES]; } } The below method is the delegate method that gets called when authorize button is clicked. - (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username { NSLog(@"Authenticated with user %@", username); } In iPhone it is showing username properly but on iPad it is returning nil. Please suggest me what might be the problem or how could I sort this issue. Please help me. Thanks in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/7565977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to interpret a crashlog with no references to a specific class Today my app crashed and generated this crashlog. The crashlog does not mention any classes in my project and to me it seems almost impossible to tackle this issue. Any ideas how to approach this problem? Thanks for your help! A: There's a tool included in Apple's Developer's tools called symbolicatecrash. With it you can symbolicate crash reports, but note that you'll need the associated .dsym file of your build Check this post to see a tutorial using it. A: This is how I ran the symbolitecrash binary. Find the binary symbolitecrash locate symbolitecrash Optional: You may add a convenience link to /usr/bin sudo ln -s /Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash /usr/bin/symbolicatecrash Copy the crash log to the Debug-iphoneos folder and go to the project cp ~/Desktop/TheCrash.crash ~/Myproject/build/Debug-iphoneos cd ~/MyProject/build/Debug-iphoneos Run the crash log symbolicater symbolicatecrash TheCrash.crash MyProject.app.dSYM > ReportWithSymbols.crash The result crashlog http://k.minus.com/jk4X2obwZMI7j.png
{ "language": "en", "url": "https://stackoverflow.com/questions/7565978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: select particular element in row of table view in titanium hi I am developing Android application using Titanium. I want to change image on click event.But I am unable to select particular image in table view.I used following code: var user_table = Ti.UI.createTableView({minRowHeight:5.length,hasChild:true}); var data = []; for (var i=0;i<5.length;i++) { var row = Ti.UI.createTableViewRow({height:'auto',className:"row"}); var username = Ti.UI.createLabel( { text:'user name', height:'auto', font:{fontSize:12, fontFamily:'Helvetica Neue', color:'#000'}, width:'auto', color:'#000', textAlign:'left', top:0, left:35, });row.add(username); var imageView = Ti.UI.createImageView( { image:'../images/user.png', left:0, top:0, height:25, width:25 });row.add(imageView); } feed_table.setData(data); feedWin.add(feed_table); I want to target image in particular row of table view so that i can replace it with another image on click event. help me for selecting that particular image A: 1) in your table view, set the event listener on the whole row. tableView.addEventListener('click',function(event){ if ( event.source.id === undefined ) { // if no id defined then you know it is not an image... } else { // you have an id, you have an image.. var rowNumber = event.index; var image = event.source; } }); 2) when you create your images, set an id on each one so you can identify it in the click event var imageView = Ti.UI.createImageView({ id :"image_"+ i, // set object id image:'../images/user.png', left:0, top:0, height:25, width:25 }); A: i would do it this way: addRow = function(_args) { var row = Ti.UI.createTableViewRow( { height:'auto', className:"row" }); var username = Ti.UI.createLabel( { text: _args.text || 'user name', height:'auto', font:{fontSize:12, fontFamily:'Helvetica Neue', color:'#000'}, width:'auto', color:'#000', textAlign:'left', top:0, left:35, }); row.add(username); var imageView = Ti.UI.createImageView( { image:_args.image||'../images/user.png', left:0, top:0, height:25, width:25 }); row.add(imageView); row.setImage = function(image) { imageView.imageURL = image; }; row.addEventListener('click',function(e) { row.setImage('new/image/path'); }; return row; } var user_table = Ti.UI.createTableView({minRowHeight:5.length,hasChild:true}); var data = []; for (var i=0;i<5.length;i++) { var newRow = addRow({ text: 'my text', image: 'my image url' }); data.push(newRow); } feed_table.setData(data); feedWin.add(feed_table); if you need to set the url you should also use feedWin.data[0].rows[indexOfRow].setImage('another/image/path'); give it a try. didn't compile that, so it's just a proposal. [update] be aware that 'auto' values may suck at android.
{ "language": "en", "url": "https://stackoverflow.com/questions/7565990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Specify content-type for documents uploaded in Magnolia We have uploaded an mp4 video file into our Magnolia DMS, which fails to play on Safari (Mac/iPad). Investigation shows that the Content-Type returned by Magnolia is "application/octet-stream" for the request. When serving the file through Tomcat directly, the correct Content-Type "video/mp4" is returned and video playback works. How can we configure the content-type to be returned in Magnolia? We know the content-type is a function of the request (e.g. if we add ".jpg" to the URL the type returned is "image/jpeg"), but couldn't use this knowledge to come up with a solution. Update: We found the MIME configuration and could change the Content-Type for "mp4" to "video/mp4". However, the Content-Type returned by Magnolia is now Content-Type: video/mp4;charset=UTF-8 while the correct, working Content-Type returned for files hosted by Tomcat is Content-Type: video/mp4 Is it possible to make Magnolia not append any charset info to the Content-Type? A: Glad you found the MIME configuration OK. Both the MIME type and the character encoding are set in ContentTypeFilter.java and MIMEMapping.java. You can specify a charset for a MIME type yourself by including it in the mime-type definition. (E.g. "video/mp4;charset=UTF-8".) If you don't include one, however, Magnolia automatically assigns the default (in this case, UTF-8). If you want to change this behavior, you'd need to tweak the source code. Out of curiosity, is the charset causing you any trouble, or are you just trying to get Magnolia to match what Tomcat does by default?
{ "language": "en", "url": "https://stackoverflow.com/questions/7565993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Piwik statitics about all websites Is it possible to use the Piwik-API with all Websites, not just for a single one? What i want to do is get a mean value of used browsers. I can do this for a single website like this: ?module=API&method=UserSettings.getBrowser&idSite=1&period=day&date=last10&format=rss If i just remove idSite=1 i get an error. A: You can specify all sites using idSite=all, you can also specify multiple sites by separating the ids with commas idSite=1,2,4,5. The resulting output is given per idSite wrapped in an extra <results> tag, so whereas before you had <result> <row> <label>Chrome 14.0</label> <nb_uniq_visitors>13</nb_uniq_visitors> ... </row> <row> <label>Chrome 13.0</label> <nb_uniq_visitors>13</nb_uniq_visitors> ... </row> ... </result> You now get <results> <result idSite="2"> <row> <label>Chrome 14.0</label> <nb_uniq_visitors>13</nb_uniq_visitors> ... </row> <row> <label>Chrome 13.0</label> <nb_uniq_visitors>13</nb_uniq_visitors> ... </row> ... </result> <result idSite="3"> <row> <label>Chrome 14.0</label> <nb_uniq_visitors>13</nb_uniq_visitors> ... </row> <row> <label>Chrome 13.0</label> <nb_uniq_visitors>13</nb_uniq_visitors> ... </row> ... </result> ... </results> This does mean that any aggregating for your mean value will have to be done once you get the data but this should be relatively trivial.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how is the linked list actually being changed i was wondering if anyone could help me with this question. i believe i understand the code and logic for the most part. i can trace code and it makes sense, but one thing i don't get is....how does the LinkedListNode previous actually change the LinkedListNode n that is passed in? it seems to me that the function loops through n, and if the element is not yet found puts it into a hashtable. but when it is found again, it uses this newly created LinkedListNode previous to skip over the duplicate and link to the following element, which is n.next. How does that actually disconnect LinkedListNode n? It seems like previous would be the LinkedListNode that has no duplicates, but since nothing gets returned in this function, n must be the one that changes. I guess I'm not seeing how n actually gets changed. Clear and thorough help would be much appreciated. Thank you = ) public static void deleteDups(LinkedListNode n){ Hashtable table = new Hashtable(); LinkedListNode previous = null; while(n != null){ if(table.containsKey(n.data)) previous.next = n.next else{ table.put(n.data, true); previous = n; } n = n.next; } } doesn't the line... LinkedListNode previous = null; create a new LinkedListNode? so this is my logic of how i'm doing it... lets say the argument, n, gets passed in as 5 -> 6 -> 5 -> 7 when the code first runs, previous is null. it goes into the else statement, and previous is now 5? and then the line n = n.next makes n 6? now the hashtable has 5, and it loops again and goes into the else. prev is now 6 and the hastable has 6. then n becomes 5. it loops again but this time it goes into the if, and prev is now 7. and n will become 7. i see that prev skipped over 5, but ...how is prev unlinking n? it seems like prev is the LinkedListNode that contains no duplicates A: how does the LinkedListNode previous actually change the LinkedListNode n that is passed in? Look at the line n = n.next; This line causes the passed node n to change - effectively moving it one node forward with each iteration. it uses this newly created LinkedListNode previous to skip over the duplicate and link to the following element No, no node is newly created here. The node previous always points to a node in the existing LinkedList of which the passed node n is one of the nodes. ( may be the starting node ). What makes you think it is newly created ? It looks like you are confused in your understanding of how nodes and references ( and so a LinkedList as a whole ) works in Java. Because all modifications occur on the Node's data , and not the reference itself , ( ugh.. thats not entirely correct ), the original LinkedList passed to the method does get modified indeed after the method returns. You will need to analyse the LinkedList structure and workings in details to understand how this works. I suggest first get clarity about what pass by value and pass by references are in Java. edit : Your analysis of the run is correct , however your confusion still remains because you are not conceptually clear on certain things. Towards the end of your analysis , you ask "..how is prev unlinking n? it seems like prev is the LinkedListNode that contains no duplicates " This is a mess - first , you need to differentiate between a LinkedListNode and a LinkedList itself. prev and n are two instances of LinkedListNode, not LinkedList itself. In your example , the LinkedList is unnamed ( we dont have a name to refer to it ). This is the original list - there is no other list. Second , in your illustration , the numbers you show are only one part of the node , called the node data. The other part, that you have missed out, is the next LinkedListNode reference that is implicit in every node. The link that you draw -> is actually the next reference in each node.When you say that prev skips 5 , what actually happens is that the next of node with data 6 is made to point to node with data 7. At start : 5|next -> 6|next -> 5|next -> 7|next->NULL After 5 is skipped : 5|next -> 6|next -> 7|next->NULL As you see , the linkedlist is changed ! It does not matter if it was changed using prev or n, the change remains in the list. A: if(table.containsKey(n.data)) previous.next = n.next Is the section which does the deletion. It assigns the reference of the prior node's next field to the node after the current node, in effect unlinking the current node.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: OWL Ontology: Represent increasing number, like first, second, third I have a question about an OWL ontology that I am making. I have a class that is actually an ID class and I would like to have instances: first, second, third etc. The first solution that I have figured is creating individuals {first, second, third etc} for this class, but then I have to write a huge number of individuals. The other solution is to create a data property that will be connected with my class that has type "integer". The second solution looks more appropriate but the thing is that I can't represent the word "first", just the number 1. Do you know how I can do that? A: You could create a class of ordinals that are uniquely identified by an integer, like so (in Turtle syntax): :hasPosition a owl:DatatypeProperty, owl:FunctionalProperty ; rdfs:range xsd:integer . :Ordinal a owl:Class ; rdfs:subClassOf [ a owl:Restriction ; owl:onProperty :hasPosition ; owl:someValuesFrom :integer ] ; owl:hasKey ( :hasPosition ) . Note the use of owl:hasKey (introduced in OWL 2) which means that the value of :hasPosition identifies a unique instance. The property is functional so that an instance cannot have two distinct positions.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Resource Loader with ready() function call and that also loads CSS? Ideally I'm looking for a Javascript resource loader that will: (1) Allow me to make "ready" calls like head.js does, e.g. head.ready(function() { $("#my").jquery_plugin(); }); // load jQuery whenever you wish bottom of the page head.js("/path/to/jquery.js"); (2) Load CSS files like yepnope (which can also handle file names with hash on the end by using the css! prefix). I don't particularly need the conditional load functionality (at this stage). (3) Ideally, only load resources once even if multiple calls are made (head.js does this automatically, yepnope does this with a filter). At the moment I'm resorting to using both head.js and yepnope, as I haven't been able to find one that supports both the first two requirements. Obviously this is not ideal, as both together (with filters and prefixes) come to 7kb minified. I think this is a bit too heavy as a bootstrap script. One option is roll my own using a combination of the two and strip out the functionality I don't need... but I'd rather stick to one that's going to be supported to reduce the pain of future updates etc. A: So we stuck with a combination head.js and yepnope until something better comes out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566006", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fluent nHibernate required files and linux I've downloaded the fluent hibernate 1.2 zip file from the website. It contains various files, amongst them NHibernate.dll FluentNHibernate.dll Castle.Core.dll Remotion.Data.Linq.dll Antlr3.Runtime.dll Iesi.Collections.dll NHibernate.ByteCode.Castle.dll Q1) Are all these files required for doing a simple application?. By simple I mean that the db contains a few tables that doesn't need complicated queries and has limited levels/amounts of reference keys and joins. Q2) Does fluent nHibernate run on mono on linux? A: * *no; see here for what's needed and what's optional. *it runs wherever you can run (and develop) .net programs (i.e it, obviouslly, needs .net runtime environment).
{ "language": "en", "url": "https://stackoverflow.com/questions/7566009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: textStyle for Tamil font? I'm already working on an Android application that displays RSS feed. My problem is that this feed has some lines in Tamil(which Android still doesn't support) I found a font online that displays the text right(without converting to Bamini) but the problem is that textStyle doesn't have any effect on it. so you know any font that can do the job or any thing i have to do to make textStyling? thanks in advance A: What you need to do is import custom fonts on to the phone before using them. A good way to do that is to include them in the package - in the APK file Hence you should be having the font in your project when you build the APK file. Let me give you an example. Assuming your tamil font's name is Harabara.ttf and you have copied it to /assets/fonts Use this method (anywhere in your activity) private void initializeFonts() { font_harabara = Typeface.createFromAsset(getAssets(), "fonts/Harabara.ttf"); } and call this API from your onCreate like this public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initializeFonts(); setContentView(getViewResourceId()); } Make sure you have declared this class level variable Typeface font_harabara = null; Finally, simply use myTextField.setTypeface(font_harabara); tada ! tamil font should now start displaying. nandri vanakkam, vaidyanathan A: There are hundreds of fonts available online. Did you check some TSCII fonts? I've written some solutions for Tamil and Android issues. Check it out too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom tooltips for Wpf Devexpress controls I have created a custom tooltip that is shown for WPF controls, but not for DevExpress WPF controls and I don't know why. To add the tooltip I do something like this: <Button.ToolTip> <cc:TooltipControl Title="Test title" Text="Some text to show in tooltip" ImageType="Information"> </cc:TooltipControl> </Button.ToolTip> My custom control inherits from the Tooltip control and has some properties that I added like Title, Text and ImageType. For the controls that don't belong to devexpress, my tooltip is shown but not for DevExpress controls. What do I need to do in order to make the DevExpress controls show my tooltip? A: It seems that the version for devexpress controls that I was using had a bug regarding the edit controls. I got a newer version and now it works, they fixed the bug.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating GPS location from background android doesn't work on most of the phones I want to get the GPS location of device every 30 min and send it to web service via a web service call. I have used repeating alarms for every 30min with a broadcast receiver in the application for this alarm. Receiver acquires the wake lock and calls the web service to update the location. This is working perfectly well on my Nexus S but not on Droid X and couple of more phones and I am not able to find a reason for this. Can this be because phone goes to sleep mode? In this particular thread http://code.google.com/p/android/issues/detail?id=10931 its written that location updates are not sent on all phones if phone is in sleep mode. Thanks, Prateek
{ "language": "en", "url": "https://stackoverflow.com/questions/7566026", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Header guard / translation unit problem I was under the impression that header guards solve the problem of redefinition. I'm getting linker errors that say there are redefinitions in the .obj files. This is the header I'm including, the problems are with the redefinition of all the global declarations. #ifndef DIRECT3D_H #define DIRECT3D_H // global declarations ID3D10Device* device; ID3D10Buffer* pBuffer; ID3D10Buffer* iBuffer; // the pointer to the index buffer ID3D10RenderTargetView* rtv; // the pointer to the render target view ID3D10DepthStencilView* dsv; // the pointer to the depth stencil view IDXGISwapChain* swapchain; // the pointer to the swap chain class ID3D10Effect* pEffect; ID3D10EffectTechnique* pTechnique; ID3D10EffectPass* pPass; ID3D10InputLayout* pVertexLayout; ID3D10EffectMatrixVariable* pTransform; // the pointer to the effect variable interface D3D10_PASS_DESC PassDesc; // function prototypes void initD3D(HWND hWnd); void render_frame(); void init_pipeline(); void cleanD3D(); void Init(); #endif say this header is called 3DClass.h. It is included in 3DClass.cpp. It is also included in another file - a main game loop. Now, I realise there can be problems with header files when there are multiple translation units, but I don't quite understand why this wouldn't be working, i'm only including the header in one file and also in the corresponding source file. shouldn't this be fine? A: Header guards solve the problem of including the same header twice or hidden recursion of includes, not double definition. If you include the same header in different translation units, header guards won't help. The solution is to never declare variables in header files. If you need to share variables, use the extern keyword in the header, and declare the actual variables in one of the translation units. A: Header guards only prevent the guarded portion of the header file from being included twice. The result is passed to the compiler, so the compiler does not know anything of the header guards. Consequently it will emit these symbols for every translation unit that includes the header (since it can not know that there was somewhere another unrelated translation unit compiled). Also the linker can not know that you didn't wanted this to happen. To solve the problem, declare the variables extern in the header, and define them in one single translation unit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android Image URL to table row I would like to dynamically add some images from this page to the rows from my table. This is my code so far: TableLayout tableView = (TableLayout) findViewById(R.id.tableView); TableRow row = new TableRow(this); ImageView im; im = new ImageView(this); im.setImageResource(R.drawable.rss); row.addView(im, new TableRow.LayoutParams(50, 50)); tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); Now... how can I make, for example, the image with the man with sunglasses, to be part of my table row? PS: I would like my application to fetch each day the images, without me changing the code. That website updates one day to another, changing the news and the images. A: Do you have an API from golfnews? My norwegian is a bit rusty to be honest. So I can't really search around on the page. Do you have any code for fetching the news? Or just one row in a tableview with an rss button? More or less. You have as I see it three options, either use their api if they have one. You probably need to talk to them. * *Use the API, should give you image in base64 or similar if they have one. *Use the RSS feed to fetch an index of the news and then parse each page and download the image in a temporary folder. *Parse the homepage of golfnews.no and download the different pictures/cache them on the device. For parsing homepages check the answers to this question: Parse HTML in Android A: For downloading images from URL private Drawable loadImageFromWebOperations(String url) { try { InputStream is = (InputStream) new URL(url).getContent(); Drawable d = Drawable.createFromStream(is, "src name"); return d; } catch (Exception e) { Log.v("EXCEPTION ", ""+e.getMessage()); return null; } } And for adding images dynamically to table you can check this Link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566035", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why 'publish' website produces bin with one dll and build script produces bin with lots of dlls I have made a script that uses the following command... "C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe" "C:\Repositories\Software\trunk\main\upload\UploadWebsite.csproj" /p:Configuration=Release This makes a website pre-compiled the bin directory has lots of dlls in it and tons of .compiled files... However when I 'right click' on the project in visual studio I am able to 'publish' the website to a folder and this creates a pre-compiled website with only one dll. This is the preferable option im just wondering what the difference between the two is....? A: The problem is that for a Website project, the publish feature of Visual Studio compiles everything into one dll, while the normal build operation compiles every page into a seperate DLL. Maybe these articles can help: Publishing Web Application with MsBuild How to publish a web site with MSBuild
{ "language": "en", "url": "https://stackoverflow.com/questions/7566037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing control as parameter to javascript function I am trying to pass a control's id to a javascript function that adds the value of it(the control which is a textbox) to a listbox but apparently I am not getting it right, can someone please correct me. Thanks. <input type="button" ID="btnAddtoLstBox" value="" title="Add this to the list" onclick="javascript:addToList(document.getElementById(btnAddtoLstBox));" class="ui-icon ui-icon-refresh ui-corner-all" style="width: 20px; height: 20px; background-position: -64px 80px" /> // scripts to add list items function addToList(varTxtBox) { // get the list box var lb = document.getElementById("uilstMemTypeTier"); // get the text to add var toAdd = varTxtBox.value; if (toAdd == "") return false; // look for the delimiter string. if found, alert and do nothing if (toAdd.indexOf(delim) != -1) { alert("The value to add to the list cannot contain the text \"" + delim + "\" as it is used as the delimiter string."); return false; } // check if the value is already in the list box for (i = 0; i < lb.length; i++) { if (toAdd == lb.options[i].value) { alert("The text you tried to add is already in the list box."); return false; } } // add it to the hidden field document.getElementById("<%=uihdnlistBasedFieldsListItems.ClientID%>").value += toAdd + delim; // create an option and add it to the end of the listbox lb.options[lb.length] = new Option(toAdd, toAdd); // clear the textfield and focus it varTxtBox.value = ""; varTxtBox.focus(); } A: Change onclick="javascript:addToList(document.getElementById(btnAddtoLstBox));" to onclick="addToList(document.getElementById('btnAddtoLstBox'));" or onclick="addToList(this);" A: If you are using control event handler you can provide this and it be control: onclick="addToList(this)" Code: http://jsfiddle.net/ARBHj/ A: You can also do it in following way- <body> <form id="form1" runat="server"> <div id="div1" style="height:100px; width:192px; background-color:red;"> </div> <br /> <div id="div2" style="height:100px; width:192px; background-color:green; display:block"> </div> <br /> <asp:Button runat="server" Text="Change color" id="btnColor" OnClientClick="javascript:return changeColor();"/> <asp:Button Text="Hide 1st" runat="server" ID="btnHide1st" OnClientClick="javascript:return hideDiv('div1');"/> <asp:Button Text="Hide 2nd" runat="server" id="btnHide2nd" OnClientClick="javascript:return hideDiv('div2');"/> </form> Hope this may have helped you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Error when compiling simple SPARC ASM math code Writing SPARC asm code to evaluate a hardcoded statement, but I'm getting an error I don't understand. I've searched all over, and while it seems to come up a lot in some bug reports out there, there's no real clues that I've found for programmers. Yes, it is homework, and yes, I'm not finished, and yes I have branch delays all over the place. I'll get to them on my own, but I need to know what the error is. This error's not telling me anything useful, and the books I have aren't any good for it either. I'm really new at this, so any help would be greatly appreciated. 1 /*Justin Reeves*/ 2 /*max{x^3-14x^2+56x-64} from [-2,8]*/ 3 /*for (x = lwr, x <= upr, x++) */ 4 define(lwr_b, -2) !lower bound 5 define(upr_b, 8) !upper bound 6 define(x_r, %l0) !x 7 define(sum_r, %l1) !sum, each pass of loop may update 8 define(max_r, %l2) !max, cmp to sum, store in max if larger 9 10 .global main 11 main: 12 save %sp, -64, %sp 13 14 ba loop_test 15 mov lwr_b, x_r /*init x_r = -2 */ 16 17 loop_test: 18 cmp x_r, upr_b 19 ble sum_loop 20 nop 21 /*then x > upr_b and the max has been found*/ 22 /*odd spot for it...but this is the end of the program*/ 23 24 25 sum_loop: ! starting backwards to give us an intial nonzero constant sum 26 mov -64, sum_r /* sum = -64 */ 27 28 mov x_r, %o0 /*56x*/ 29 mov 56, %o0 30 clr %o2 31 call .mul /*AFAIK 56x should now be in %o0*/ 32 nop 33 add sum_r, %o0, sum_r /* sum = 56x-64 */ 34 35 mov x_r, %o0 /* 14x^2 */ 36 mov x_r, %o1 37 mov -14, %o2 38 call .mul 39 nop 40 add sum_r, %o0, sum_r /* sum = -14x^2+56x-64 */ 41 42 mov x_r, %o0 43 mov x_r, %o1 44 mov x_r, %o2 45 call .mul 46 nop 47 add sum_r, %o0, sum_r /*sum = x^3-14x^2+56x-64 */ 48 49 add x_r, 1, x_r /* x++ */ 50 cmp sum_r, max_r 51 bge collect_lrg /*branches if sum > max*/ 52 nop 53 54 collect_lrg: 55 mov sum_r, max_r 56 ba loop_test 57 58 mov 1, %g1 /*exit request*/ 59 ta 0 /*trap to system*/ then when I try to define the macros and compile I get: cs32107@matrix:~$ m4 polynomialv2.m > polynomial.s cs32107@matrix:~$ gcc -g polynomial.s -o polynomial ld: fatal: relocation error: R_SPARC_32: file /var/tmp//ccVOrnx2.o: symbol : offset 0xfb5d11dd is non-aligned ld: fatal: relocation error: R_SPARC_32: file /var/tmp//ccVOrnx2.o: symbol : offset 0xfb5d120f is non-aligned ld: fatal: relocation error: R_SPARC_32: file /var/tmp//ccVOrnx2.o: symbol : offset 0xfb5d1215 is non-aligned ld: fatal: relocation error: R_SPARC_32: file /var/tmp//ccVOrnx2.o: symbol : offset 0xfb5d1219 is non-aligned ld: fatal: relocation error: R_SPARC_32: file /var/tmp//ccVOrnx2.o: symbol : offset 0xfb5d121d is non-aligned ld: fatal: relocation error: R_SPARC_32: file /var/tmp//ccVOrnx2.o: symbol : offset 0xfb5d1266 is non-aligned collect2: ld returned 1 exit status cs32107@matrix:~$ A: A bug in the assembler causes debugging code to add unaligned data access. Don't use -g but perhaps -gstabs if you need debugging information. There maybe an update for gas that fixes the problem too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7566044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove a particular div tag and reset its content using javascript Code below contains certain tags in all four. Image-1 here is the code : <div style='background-color:YellowGreen;height:20px;width:100%;margin-top:15px;font-weight: bold;'> &nbsp;&nbsp;Delegate(s) details: </div> <div style="border:1px solid black;"><br/> <div id="delegates"> <div id="0"> &nbsp;&nbsp; Name of the Delegate: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input name='contact_person[]' type='text' size="50" maxlength="50" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Designation: <select name='delegate_type_name[]' class='delegate_type'> <option value='select'>Select</option> <option value='Main'>Main</option> </select> </div><br/> </div> <div> &nbsp;&nbsp; <input type="button" name="more" value="Add More Delegates" id="add_more" /> <br /> <br /> </div> </div> In the above code on line 5 where <div id="0"> changes to value 1 in script that I mentioned in "add_more" And the javascript for "add_more" is given below jQuery('#add_more').click(function(){ var id = jQuery('#delegates > div:last').attr('id'); var temp = "<div id='"+(parseInt(id)+parseInt('1'))+"'>&nbsp;&nbsp; Name of the Delegate: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='text' size='50' maxlength='50' name='contact_person[]' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Designation:"; temp += "<select name='delegate_type_name[]' class='delegate_type additional_delegate'><option value='select'>Select</option><option value='Additional'>Additional</option><option value='Spouse'>Spouse</option></select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='button' name='rem' value='Remove' id='remove' /></div><br/>"; jQuery('#delegates').append(temp); }); In the javascript code above I have added a remove button in the temp+ variable <input type='button' name='rem' value='Remove' id='remove' /> Image-2 shows the remove button every time I click on "Add more Delegates" button. In the image-2 I click on Add More Delegates button it shows the "remove" button on the right of drop down select list. I want a jQuery function for remove button, so that when I click on remove it should remove <div id="1"> and also reset content before removing the div tag. Below image-3 is the output that I want when I click on remove button. code that I tried was this from some reference is this jQuery('#remove').click(function(){ var id = jQuery('#delegates > div:last').attr('id').remove(); }); but no luck. Thanks. A: You can't give an element id that is only a number, it must be #mydiv1, #mydiv2 or something similar, i.e. beginning with a letter not a number. A: For starters your markup is a total mess. There is no way you should be using &nbsp; for layout purposes. Read up on tableless layouts and css. The first thing you need to change is the id's of your div. An id cannot start with a numeric. I suggest naming the first div delegate0. Secondly, you are adding a remove button on every new row with the same id - all id's on a page should be unique so i suggest you change this to class="remove". As for your question, it really boils down to needing to add a jQuery handler to the remove buttons using the .livedocs method. This is as simple as: jQuery('.remove').live('click',function(){ $(this).closest('div').remove(); }); Also, you need to keep a running counter of the id of the items added, and increment this every time a new row is added. var nextDelegate = 1; jQuery('#add_more').click(function(){ ... your code here nextDelegate++; }); Also, I removed the superfluous <br/> after each div. Live example: http://jsfiddle.net/cb4xQ/
{ "language": "en", "url": "https://stackoverflow.com/questions/7566055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a Visual Studio plugin to highlight a block of text, like in Microsoft Word? I don't mean a single word, or every occurrence of a particular word... I'm talking about the ability to select a block of text, like a method, or a series of methods and highlight the background in a particular colour... Like this: http://freewindowsvistatutorials.com/programsAndApplications/microsoftWord2007/colorMarkerHighlightText.php I personally don't really like regions, they look untidy most of the time and they add to the problem almost as much as they solve it sometimes. Is there anything like this? A: VS10x Code Map, it's good but not for free
{ "language": "en", "url": "https://stackoverflow.com/questions/7566056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: PostgreSQL ERROR: there is no built-in function named " (SQL state 42883) I'm trying to add to my PostgreSQL a very simple function, to convert IP addresses from an integer to a text format. This is the code of the function: CREATE FUNCTION custom_int_to_ip(ip BIGINT) RETURNS TEXT AS $$ DECLARE octet1 BIGINT; octet2 TINYINT; octet3 TINYINT; octet4 TINYINT; restofip BIGINT; BEGIN octet1 = ip / 16777216; restofip = ip - (octet1 * 16777216); octet2 = restofip / 65536; restofip = restofip - (octet2 * 65536); octet3 = restofip / 256; octet4 = restofip - (octet3 * 256); END; RETURN(CONVERT(TEXT, octet1) + '.' + CONVERT(TEXT, octet2) + '.' + CONVERT(TEXT, octet3) + '.' + CONVERT(TEXT, octet4)); $$ LANGUAGE internal; As replay I'm obtaining the following error: ERROR: there is no built-in function named " And some lines below... SQL state: 42883 Please let me know if anyone can see my mistake here, I've been trying different syntaxes and search information for the specific SQL state but no clue about what's going on. Thanks in advance. A: There are two errors here: * *PostgreSQL uses the standard string concatenation operator || like almost all other databases *There is no convert function in PostgreSQL, you should use to_char() to convert a number to a string Btw: are you aware that there is a native IP data type available in PostgreSQL? A: Additionally to what a_horse_with_no_name already pointed out: * *Use language plpgsql instead of language internal *MySQL and others have tinyint. In PostgreSQL use smallint or int2 (synonym) instead. See the manual about data types. Better yet, make all variables bigint in this particular case and save an extra conversion. *Use the assignment operator := instead of =. = is undocumented and may stop working without notice in a future version. See here: The forgotten assignment operator "=" and the commonplace ":=" *Move END; to the end. *Output is guaranteed to be the same for the same input, so make the function IMMUTABLE to speed it up in certain situations. To sum it all up: CREATE OR REPLACE FUNCTION custom_int_to_ip(ip bigint) RETURNS inet AS $$ DECLARE octet1 bigint; octet2 bigint; octet3 bigint; octet4 bigint; restofip bigint; BEGIN octet1 := ip / 16777216; restofip := ip - (octet1 * 16777216); octet2 := restofip / 65536; restofip := restofip - (octet2 * 65536); octet3 := restofip / 256; octet4 := restofip - (octet3 * 256); RETURN (octet1::text || '.' || octet2::text || '.' || octet3::text || '.' || octet4::text); END; $$ LANGUAGE plpgsql IMMUTABLE; Call: SELECT custom_int_to_ip(1231231231); Output: 73.99.24.255
{ "language": "en", "url": "https://stackoverflow.com/questions/7566057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }