text
stringlengths
8
267k
meta
dict
Q: java - is that possible to develop GPS software on PC i want to make an application for tablet PC / notebook i want to make software to acquire a location(longitude and latitude)for PC. is that possible for me to develop GPS for PC with java programming language??? if yes, what software i need to download to develop that application???? A: First you need to have at least a GPS device to receive the GPS information! Usually, devices are connected through USB, serial port, or Bluetooth. Interface with the device (read the manufacturer's reference book on that). Once you start getting the information, all you have to do is to parse the data and adopt to your program accordingly! A: Yes, it's possible. First of all, you'll need a GPS receiver (either built into the computer, or connected to it). Typically, GPS units use a simple text protocol to talk to the host over the serial port. There are plenty of libraries out there that can help you if you don't want to parse the protocol yourself; just google "gps java". Lastly, bear in mind that typically GPS units don't work indoors since they require an unobstructed view of the sky.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557644", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Try two download links without user interaction in Javascript or HTML5 My problem is as follows: I serve a webpage to clients that contains two different download links to the same file. I want the client(!) to test both without manually clicking both links (I still present them both as a fail safe). Can this be done with javascript or html5? A: Set location = "some URL" twice. A: What you can do is making an HTTP HEAD request and look at the status code. The status code tells you whether the resource is available, while a HEAD request does not fetch the resource contents itself. This can be done with AJAX, depending on your framework. E.g. with jQuery: $.ajax({ type: "HEAD", url: "download_url", complete: function(xhr) { if(xhr.status === 200) { /* is available */ } else { /* not available */ } } }); A: Try this: <img src="providerSrc" onerror="this.src=fallbackSrc" onabort="this.src=fallbackSrc" /> Customized to your needs of course...
{ "language": "en", "url": "https://stackoverflow.com/questions/7557647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Random questions to display a download link The basic idea is to have several questions, but only 1 showing randomly on page load. Then whatever answer to that question, will display a download. The questions load randomly, but when I put in the answer the download doesn't display. I thought I had all my code correct, but maybe there is a better way to do this. If you could help me out, I'd greatly appreciate it. P.S. I already know this isn't a super secure way to hide something, but it doesn't need to be very secure. <form id="1"> Enter the 5th word on page 28 to access the download: <input id="pwd1" name="pwd1" type="text" /> </form> <form id="2"> Enter the 6th word on page 29 to access the download: <input id="pwd2" name="pwd2" type="text" /> </form> <form id="3"> Enter the 4th word on page 30 to access the download: <input id="pwd3" name="pwd3" type="text" /> </form> <form id="4"> Enter the 3rd word on page 32 to access the download: <input id="pwd4" name="pwd4" type="text" /> </form> <form id="5"> Enter the 5th word on page 33 to access the download: <input id="pwd5" name="pwd5" type="text" /> </form> <form id="6"> Enter the 3rd word on page 34 to access the download: <input id="pwd6" name="pwd6" type="text" /> </form> <form id="7"> Enter the 5th word on page 35 to access the download: <input id="pwd7" name="pwd7" type="text" /> </form> <form id="8"> Enter the 4th word on page 36 to access the download: <input id="pwd8" name="pwd8" type="text" /> </form> <form id="9"> Enter the 6th word on page 37 to access the download: <input id="pwd9" name="pwd9" type="text" /> </form> <div id="hc" style="display: none;"> <center><a href="sudoku.zip"><img id="download" src="download.png"></a></center> </div> <script language="javascript"> var rand = Math.floor(Math.random()*9); $('form').hide().eq(rand).show(); $('form').keyup(function(){ if($('#pwd1').val() == 'more'){ $('#hc').show('slow'); } if($('#pwd2').val() == 'Rectangle'){ $('#hc').show('slow'); } if($('#pwd3').val() == 'case'){ $('#hc').show('slow'); } if($('#pwd4').val() == 'similarities'){ $('#hc').show('slow'); } if($('#pwd5').val() == 'similar'){ $('#hc').show('slow'); } if($('#pwd6').val() == 'this'){ $('#hc').show('slow'); } if($('#pwd7').val() == 'done'){ $('#hc').show('slow'); } if($('#pwd8').val() == 'outside'){ $('#hc').show('slow'); } if($('#pwd9').val() == 'completed'){ $('#hc').show('slow'); } else{$('#hc').hide();} }); </script> A: your code will only work if #pwd9 is the one shown. change your if's to else if's. or switch and NO, it no secure at all. the link is there all the time A: This would be alot cleaner: var rand = Math.floor(Math.random() * 9), words = ['more', 'Rectangle', 'case', 'similarities', 'similar', 'this', 'done', 'outside', 'completed']; $('form').hide().eq(rand).show(); $('form input').keyup(function() { if (this.value === words[rand]) $('#hc').show('slow'); }); Here is a jsFiddle of it working. Edit I had the index on words wrong, fixed now. A: I think that you are missing something in the syntax - all your if statements (bar the first), should be elseif's. This really isn't very secure, and to be honest, probably more work than doing it 'properly' (i.e. display the question dynamically and only have a single form, and probably do something (almost anything) to make this more secure). A: I'm not sure this can work at all. This is how it should be done: * *A server-side language, like php, selects random question and prints out a form on screen. *Your form needs a submit button, which, when pressed, will send the data to the server. *Server-side language will then process the data and decide whether to show link or not. This is how it's normally done + it's more secure, answers and link cannot be read so easily. A: Your problem is that you're only using if's. Use else if for each if to make the final else relative to all if's rather than just the last.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JavaMail: Socket read timeout I'm using JavaMail and I want it to work through proxy for every threads (I have multithreading application). I'm using SMTPTransport.connect(Socket socket) for this. Here is socket initialization: socket = new Socket(); socket.setSoTimeout(10000); socket.connect(new InetSocketAddress(smtpHost, smtpPort)); Here is SMTPTransport call: SMTPTransport transport = null; try { transport = (SMTPTransport) mail.getTransport("smtp"); transport.connect(socket); System.out.println("ok"); And so on. But I this error happens: DEBUG: JavaMail version 1.4.4 DEBUG: successfully loaded resource: /META-INF/javamail.default.providers DEBUG: Tables of loaded providers DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc]} DEBUG: Providers Listed By Protocol: {imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]} DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc] DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: useEhlo true, useAuth true DEBUG SMTP: starting protocol to host "smtp.googlemail.com", port 465 DEBUG SMTP: exception reading response: java.net.SocketTimeoutException: Read timed out Exception reading response javax.mail.MessagingException: Exception reading response; nested exception is: java.net.SocketTimeoutException: Read timed out at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2153) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1956) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:636) at javax.mail.Service.connect(Service.java:317) at javax.mail.Service.connect(Service.java:176) at javax.mail.Service.connect(Service.java:125) at com.sun.mail.smtp.SMTPTransport.connect(SMTPTransport.java:274) at lsmtpc.CheckAccount.run(CheckAccount.java:203) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) Caused by: java.net.SocketTimeoutException: Read timed out at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:150) at java.net.SocketInputStream.read(SocketInputStream.java:121) at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:110) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read(BufferedInputStream.java:254) at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:89) at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2131) ... 13 more So as I see JavaMail can't read from socket. So what am I doing wrong? If I try to use transport.connect() method without using Socket in constructor all works perfectly and smtpHost/smtpPort are accessible from the telnet and I have no any firewalls/antiviruses. A: From the documentation for com.sun.mail.smtp.SMTPTransport: In general, applications should not need to use the classes in this package directly. Instead, they should use the APIs defined by javax.mail package (and subpackages). Applications should never construct instances of SMTPTransport directly. Instead, they should use the Session method getTransport to acquire an appropriate Transport object. WARNING: The APIs unique to this package should be considered EXPERIMENTAL. They may be changed in the future in ways that are incompatible with applications using the current APIs. JavaMail tutorial: http://java.sun.com/developer/onlineTraining/JavaMail/contents.html Could be you are not passing authentication information. Could be you are connecting to a secured host using a plain socket. You might want to read the tutorial linked for the best way to use JavaMail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557655", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simulate Atom based pc environment I need to run & test an application on Atom cpu based tablet PC. I tried remote debugging ability of VS2010 but it only handles exceptions. My multi-threaded application's behaviors are totally different on that tablet PC. Is there any way to simulate Atom cpu -low speed, single core, etc- on my desktop environment? A: Yes, you can use power saving settings to limit the CPU speed, and CPU affinity to prevent your process from using all cores. I don't know of an easy way to artificially limit use of CPU caches. Configuring power saving settings would be more appropriate for SuperUser. For affinity, you can p/invoke SetProcessAffinityMask However, the Atom has a very different internal architecture, so merely dialing down clock speed will not be a very accurate simulation. A: You can limit number of CPUs available by changing boot.ini http://support.microsoft.com/kb/170756 or Win 7 - http://windows.microsoft.com/en-US/windows7/Using-System-Configuration (start -> system configuration -> boot ->advanced).
{ "language": "en", "url": "https://stackoverflow.com/questions/7557670", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Server aborts on trying to login using Openid using Omniauth, Rails 3 I am using omniauth for my Rails 3 / Ruby 1.9 app and it is working well for Twitter and Facebook. However, I am trying to add Google OpenId and I am facing an issue. I have the following code in initializers/omniauth.rbfor Google OpenId: Rails.application.config.middleware.use OmniAuth::Builder do require 'openid/store/filesystem' provider :openid, OpenID::Store::Filesystem.new('./tmp'), :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id' When I go to http://localhost:3000/auth/google, I get the following error in terminal and the server quits. I am not sure if using a server certificate will solve the issue. The same error occurs for any openid service, so this issue is not restricted to Google. Thanks. WARNING: making https request to https://www.google.com/accounts/o8/ud without verifying server certificate; no CA path was specified. /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:60: [BUG] cfp consistency error - call0 ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.1.0] -- control frame ---------- c:0062 p:---- s:0352 b:0352 l:000200 d:000200 CFUNC :next c:0061 p:---- s:0350 b:0350 l:000343 d:000349 IFUNC c:0060 p:---- s:0348 b:0348 l:000347 d:000347 CFUNC :bytes c:0059 p:---- s:0346 b:0346 l:000345 d:000345 CFUNC :each c:0058 p:---- s:0344 b:0344 l:000343 d:000343 CFUNC :zip c:0057 p:0105 s:0340 b:0340 l:000339 d:000339 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:60 c:0056 p:0069 s:0333 b:0333 l:000332 d:000332 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:40 c:0055 p:0124 s:0324 b:0324 l:000323 d:000323 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:45 c:0054 p:0320 s:0316 b:0316 l:000315 d:000315 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:331 c:0053 p:0059 s:0305 b:0305 l:000304 d:000304 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:196 c:0052 p:0035 s:0296 b:0296 l:000295 d:000295 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:130 c:0051 p:0074 s:0289 b:0289 l:000288 d:000288 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:118 c:0050 p:0019 s:0285 b:0285 l:000284 d:000284 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer.rb:243 c:0049 p:0103 s:0277 b:0277 l:000276 d:000276 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer.rb:228 c:0048 p:0152 s:0270 b:0270 l:000269 d:000269 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-openid-1.3.1/lib/rack/openid.rb:123 c:0047 p:0138 s:0256 b:0256 l:000255 d:000255 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-openid-1.3.1/lib/rack/openid.rb:102 c:0046 p:0048 s:0247 b:0247 l:000246 d:000246 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-openid-0.3.0/lib/omniauth/strategies/open_id.rb:70 c:0045 p:0020 s:0242 b:0242 l:000241 d:000241 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-openid-0.3.0/lib/omniauth/strategies/open_id.rb:65 c:0044 p:0177 s:0239 b:0239 l:000238 d:000238 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:58 c:0043 p:0177 s:0235 b:0235 l:000234 d:000234 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:41 c:0042 p:0019 s:0231 b:0231 l:000230 d:000230 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:30 c:0041 p:0241 s:0227 b:0227 l:000226 d:000226 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:44 c:0040 p:0019 s:0223 b:0223 l:000222 d:000222 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:30 c:0039 p:0241 s:0219 b:0219 l:000218 d:000218 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:44 c:0038 p:0019 s:0215 b:0215 l:000214 d:000214 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:30 c:0037 p:0044 s:0211 b:0211 l:000210 d:000210 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/builder.rb:30 c:0036 p:0015 s:0207 b:0207 l:000206 d:000206 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/best_standards_support.rb:1 c:0035 p:0093 s:0200 b:0200 l:000199 d:000199 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/head.rb:14 c:0034 p:0155 s:0193 b:0193 l:000192 d:000192 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/methodoverride.rb:24 c:0033 p:0046 s:0187 b:0187 l:000186 d:000186 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/params_parser.rb:21 c:0032 p:0054 s:0182 b:0182 l:000181 d:000181 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/flash.rb:182 c:0031 p:0027 s:0175 b:0175 l:000174 d:000174 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/session/abstract_store.rb:1 c:0030 p:0015 s:0164 b:0164 l:000163 d:000163 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/cookies.rb:302 c:0029 p:0014 s:0156 b:0156 l:000250 d:000155 BLOCK /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/query_cache.rb:32 c:0028 p:0019 s:0154 b:0154 l:000153 d:000153 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/connection_adapters/abstract/query_cac c:0027 p:0051 s:0150 b:0150 l:000149 d:000149 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/query_cache.rb:12 c:0026 p:0019 s:0146 b:0146 l:000250 d:000250 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/query_cache.rb:31 c:0025 p:0015 s:0142 b:0142 l:000141 d:000141 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/connection_adapters/abstract/connectio c:0024 p:0029 s:0138 b:0138 l:001720 d:000137 BLOCK /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/callbacks.rb:46 c:0023 p:0155 s:0136 b:0136 l:000135 d:000135 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activesupport-3.0.10/lib/active_support/callbacks.rb:416 c:0022 p:0011 s:0126 b:0126 l:001720 d:001720 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/callbacks.rb:44 c:0021 p:0015 s:0122 b:0122 l:000121 d:000121 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/sendfile.rb:106 c:0020 p:0049 s:0112 b:0112 l:000111 d:000111 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/remote_ip.rb:48 c:0019 p:0017 s:0108 b:0108 l:000107 d:000107 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/show_exceptions.rb:47 c:0018 p:0027 s:0100 b:0100 l:000099 d:000099 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.10/lib/rails/rack/logger.rb:13 c:0017 p:0032 s:0096 b:0096 l:000095 d:000095 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/runtime.rb:17 c:0016 p:0052 s:0087 b:0087 l:000086 d:000086 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activesupport-3.0.10/lib/active_support/cache/strategy/local_cache.rb:72 c:0015 p:0014 s:0083 b:0083 l:000077 d:000082 BLOCK /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/lock.rb:11 c:0014 p:0019 s:0081 b:0081 l:000080 d:000080 METHOD <internal:prelude>:10 c:0013 p:0054 s:0078 b:0078 l:000077 d:000077 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/lock.rb:11 c:0012 p:0193 s:0073 b:0073 l:000072 d:000072 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/static.rb:30 c:0011 p:0032 s:0066 b:0066 l:000065 d:000065 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.10/lib/rails/application.rb:168 c:0010 p:0021 s:0062 b:0062 l:000061 d:000061 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.10/lib/rails/application.rb:77 c:0009 p:---- s:0057 b:0057 l:000056 d:000056 FINISH c:0008 p:0015 s:0055 b:0055 l:000054 d:000054 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.10/lib/rails/rack/log_tailer.rb:14 c:0007 p:0015 s:0050 b:0050 l:000049 d:000049 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/content_length.rb:13 c:0006 p:0338 s:0042 b:0042 l:000041 d:000041 METHOD /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/handler/webrick.rb:52 c:0005 p:0257 s:0030 b:0030 l:000029 d:000029 METHOD /Users/ankit/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:111 c:0004 p:0393 s:0020 b:0020 l:000019 d:000019 METHOD /Users/ankit/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:70 c:0003 p:0126 s:0009 b:0009 l:001338 d:000008 BLOCK /Users/ankit/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/server.rb:183 c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH c:0001 p:---- s:0002 b:0002 l:000001 d:000001 TOP --------------------------- -- Ruby level backtrace information ---------------------------------------- /Users/ankit/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread' /Users/ankit/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run' /Users/ankit/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/handler/webrick.rb:52:in `service' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/content_length.rb:13:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.10/lib/rails/rack/log_tailer.rb:14:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.10/lib/rails/application.rb:77:in `method_missing' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.10/lib/rails/application.rb:168:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/static.rb:30:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/lock.rb:11:in `call' <internal:prelude>:10:in `synchronize' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/lock.rb:11:in `block in call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activesupport-3.0.10/lib/active_support/cache/strategy/local_cache.rb:72:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/runtime.rb:17:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.10/lib/rails/rack/logger.rb:13:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/show_exceptions.rb:47:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/remote_ip.rb:48:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/sendfile.rb:106:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/callbacks.rb:44:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activesupport-3.0.10/lib/active_support/callbacks.rb:416:in `_run_call_callbacks' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/callbacks.rb:46:in `block in call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/query_cache.rb:31:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/query_cache.rb:12:in `cache' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/activerecord-3.0.10/lib/active_record/query_cache.rb:32:in `block in call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/cookies.rb:302:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/flash.rb:182:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/params_parser.rb:21:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-1.2.4/lib/rack/methodoverride.rb:24:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/head.rb:14:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/actionpack-3.0.10/lib/action_dispatch/middleware/best_standards_support.rb:17:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/builder.rb:30:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:30:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:44:in `call!' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:30:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:44:in `call!' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:30:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:41:in `call!' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-core-0.3.0/lib/omniauth/strategy.rb:58:in `request_call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-openid-0.3.0/lib/omniauth/strategies/open_id.rb:65:in `request_phase' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/oa-openid-0.3.0/lib/omniauth/strategies/open_id.rb:70:in `start' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-openid-1.3.1/lib/rack/openid.rb:102:in `call' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/rack-openid-1.3.1/lib/rack/openid.rb:123:in `begin_authentication' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer.rb:228:in `begin' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer.rb:243:in `begin_without_discovery' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:118:in `get_association' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:130:in `negotiate_association' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:196:in `request_association' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:331:in `extract_association' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/consumer/associationmanager.rb:45:in `extract_secret' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:40:in `xor_secret' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:60:in `strxor' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:60:in `zip' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:60:in `each' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:60:in `bytes' /Users/ankit/.rvm/gems/ruby-1.9.2-p290@rails3/gems/ruby-openid-2.1.8/lib/openid/dh.rb:60:in `next' -- C level backtrace information ------------------------------------------- 0 libruby.1.9.1.dylib 0x000000010509451e rb_vm_bugreport + 110 1 libruby.1.9.1.dylib 0x0000000104f88533 report_bug + 259 2 libruby.1.9.1.dylib 0x0000000104f886a1 rb_bug + 161 3 libruby.1.9.1.dylib 0x000000010508fea0 vm_call0 + 1248 4 libruby.1.9.1.dylib 0x0000000105082f23 rb_iterate + 179 5 libruby.1.9.1.dylib 0x000000010508306d rb_block_call + 45 6 libruby.1.9.1.dylib 0x0000000104f81586 enum_zip + 294 7 libruby.1.9.1.dylib 0x00000001050823e6 call_cfunc + 102 8 libruby.1.9.1.dylib 0x0000000105086972 vm_call_method + 738 9 libruby.1.9.1.dylib 0x0000000105089dce vm_exec_core + 11214 10 libruby.1.9.1.dylib 0x000000010508deae vm_exec + 94 11 libruby.1.9.1.dylib 0x000000010508fb83 vm_call0 + 451 12 libruby.1.9.1.dylib 0x0000000105086fa2 vm_call_method + 2322 13 libruby.1.9.1.dylib 0x0000000105089dce vm_exec_core + 11214 14 libruby.1.9.1.dylib 0x000000010508deae vm_exec + 94 15 libruby.1.9.1.dylib 0x00000001050871b1 rb_vm_invoke_proc + 161 16 libruby.1.9.1.dylib 0x000000010509abdb thread_start_func_2 + 283 17 libruby.1.9.1.dylib 0x0000000105097be4 thread_start_func_1 + 116 18 libsystem_c.dylib 0x00007fff87b128bf _pthread_start + 335 19 libsystem_c.dylib 0x00007fff87b15b75 thread_start + 13 [NOTE] You may have encountered a bug in the Ruby interpreter or extension libraries. Bug reports are welcome. For details: http://www.ruby-lang.org/bugreport.html Abort trap: 6
{ "language": "en", "url": "https://stackoverflow.com/questions/7557675", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: A hyperlink on Crystal Reports should open another report and pick Session value I am using Visual Studio 2005 Professional Edition [ASP.NET with C#]. I have a Crystal Report with a column is shown as a hyperlink. On clicking any hyperlinked value of any row, another report should open but I have three issues to be addressed: * *The URL of the second report should be handled via Server.Transfer method to hide the page name from the URL. *The hyperlinked text, where the user has clicked to open second report, should be passed to the second report. *The second report is connected with SQL command as database back-end. I want to pass a Session value as a parameter to the SQL command being used by the second report. A: * *You're hyperlink will need to reference a URL that will perform a Server.Transfer--Crystal Reports does not support this. *You will need to embed this text in the query string. *You will need to embed the logon token in the query string. To dynamically construct a querystring, edit the conditional formula that is associated with the field's Hyperlink infomation (right click field; Format Field...; Hyperlink tab). It might resemble: //change to reflect your situation "http://server:port/resource/redirect.aspx?reportname=" + [report name here] + "&token=" + [logon token here] If you are using BusinessObjects Enterprise, you may want to investigate URLReporting.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PDO connect error on xampp for windows I'm new to PDO and am trying to use it on xampp for windows. I keep getting an error relating to the host and have tried changing 'localhost' to everything possible such as ip address and sockets but i believe i'm not doing it right. I've also tried changing the variable for pdo_mysql.default_socket but I don't believe that it's working/I'm doing that right either.This is the error I'm getting: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000] [1044] Access denied for user 'admin'@'localhost' to database ''xxxxxx''' in C:\xampp\htdocs\faculty\classes\db.class.php This is what i currently have in my php self::$instance = new PDO("mysql:host=localhost;dbname='xxxxxx'", 'admin', 'xxxxxxx'); A: Have you created an account for admin@localhost in mysql? PDO's connecting just fine, but you're using incorrect credentials to log into the database. Specific docs on creating accounts: http://dev.mysql.com/doc/refman/5.5/en/adding-users.html A: remove single quotes around dbname as in self::$instance = new PDO("mysql:host=localhost;dbname=xxxxxx", 'admin', 'xxxxxxx'); A: I had the same problem today and turns out my xampp mysql database had two "any" entries that were generating a warning in the users page of phpmyadmin that I was ignoring. I managed to connect with PDO once I removed those two entries... go figure. To sum up: remove the "any" users from your php users list, if they are there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do i use regex in javascript to find three periods inside of a string? Ok, this is probably a simple regex but i am not familiar with them. I have a bunch of strings like this: '11.9.2.1 Fusion' or '11.9.1 Fusion' etc... All of them have ' Fusion' at the end of them. I am trying to find only the ones with three periods (or four sets of numbers) in them. This is some pseudo code like what i have: $(xml).find("Asset").each(function(){ var projectName = $(this).find("Attribute[name='SecurityScope.Name']").text(); if(projectName.match(where-ive-been-putting-regex-statements)){ var patch = true; }else{ var patch = false; } }); Any ideas? A: Something like this? - /(\d+\.){3}\d+/ It matches 3 groups of numbers (at least 1 digit) followed by a period and a fourth number. A: This should do it: \d+\.\d+\.\d+\.\d+\s+Fusion Matches 4 groups of any digit (one or more) separated by a literal dot, followed by one or more whitespace, followed by literal string "Fusion" Matches: 11.9.2.1 Fusion But does not match: 11.9.1 Fusion Live example: http://jsfiddle.net/Jqvtp/ A: This matches strings like '11.9.2.1 Fusion': projectName.match(/^(\d+\.){3}\d+ Fusion$/) A: A regex to match a string that contains three periods would be .*\..*\..*\..* (where the first and last .*s may be superfluous depending on whether your regex engine offers a "contains"-style match.) The critical part here is that . by itself is a character wildcard so will match anything. Escaping it with the backslash turns it into a match for a literal period. So what we have is (with line breaks for explanation) .* // Match any character, any number of times. Then: \. // Match a literal period. Followed by: .* // Any character, any number of times. Followed by: (etc...) A: Try: [\d]+\.[\d]+\.[\d]+\.[\d]+ Fusion
{ "language": "en", "url": "https://stackoverflow.com/questions/7557688", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: appcelerator titanium - edit button in tabgroup doesn't go away Using Titanium mobile sdk 1.7.2, I created a tabgroup with 11 tabs. The problem is when I open any of the tabs inside the 'more' tab, if the child window has a right navbar button, some times the 'edit' button of the 'more' tab doesn't go away.. my code is: app.js: var tabGroup=Titanium.UI.createTabGroup({top:20}); ............ /** list of windows and tabs **/ ............ var win9 = Titanium.UI.createWindow({ url:'discover.js', title:'Discover', navBarHidden:true, barColor: navBarColor }); var tab9 = Titanium.UI.createTab({ icon:'images/icons/Discover.png', title:'Discover', window:win9 }); discover.js: win=Titanium.UI.currentWindow; var btn=Titanium.UI.createButton({title:'Discover'}); btn.addEventListener('click',function (){ //do some stuff }); win.rightNavButton=btn; the problem is, sometimes when I open the 'tab9' which opens 'win9' my button (btn) doesn't appear, the 'edit' button of the 'more' is shown instead. N.B: the click event listener works just fine, It is the 'edit' title that persists. Any one knows how to solve this? thank you, A: You need to set allowUserCustomization:false in your Tabgroup. var tabGroup=Titanium.UI.createTabGroup({top:20,allowUserCustomization:false}); A: try to set win.rightNavButton = null; win.rightNavButton = btn;
{ "language": "en", "url": "https://stackoverflow.com/questions/7557689", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I connect to a sql database through sql developer? So, I have a .sql file that I have downloaded and was wondering how I connect to it via sql developer which I have also downloaded. Do I need to create a connection with hostname and port etc? can I just connect to a file manually/directly or something? Also, can anyone recommend a good database to practice/learn on for a beginner? Should I just download oracle 11g and play around with that? Thanks. A: You'll need the SID as well as the ip address and port number (typically 1521) that tns listener is listening on. Once you've connected, you'll be able to run your sql file against that database. And yes, it would be a good idea to have a good understanding of Oracle before wandering off blindly into the world of database access (.sql files, for example) A: You cannot connect to a .sql file because it is not a database. Oracle runs as a server in its own right. If you do not already have access to a server then you will need to get one. Fortunately, Oracle publishes a server you can use free of charge that will help get you into the swing of things. Have a look at Oracle Lite I think you might find it quite a challenge getting yourself set up with a development environment but if you are patient and determined you can get there. Once you have a server to play with you can start to experiment with Sql, which is the language you use to interrogate the database. Best of luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557694", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: What would be a viable design alternative to nesting an interface inside a concrete class? When I read about nesting an interface inside of a class, the intention appears to be to encapsulate the abstract behavior of the interface through composition. However, to me it makes more sense to create the interface outside the class, then use a getter/setter and return an instance of the interface type. There must be a benefit that I'm not seeing. Is this simply a matter of "choice". A: If the interface strongly related with some class, it might be reasonable to nest it within the class. For example: SurfaceHolder.Callback which allows a client to receive information about changes to the surface in Android. The Callback interface is nested within the SurfaceHolder, and it is easier to access and find it within that context. However, for generic interfaces such as Runnable which is implemented by a class whose instances to be executed by a thread, it is completely outside of a class (in the java.lang package for this example). This make more sense because, this interface could be used by any class, not necessarily within a specific context). A: It is not a matter of choice if we talk about highly complex, scalable and re-usable systems. There are so named S.O.L.I.D. design principles (dependency injection and inversion of control if we talk specifically) which suppose the use of interfaces. The reasons to use them are: 1) the decoupling of the models inside your code. If you create the objects inside a class when your classes cannot be used in other projects as they are tightly coupled 2) possibility of creating mocks for right unit tests. You can test concrete layers, in your case by testing the highest level you invoke all the methods of the lower levels. 3) Interfaces can be combined and used throughout the whole system in many places so a lot of other classes can use the mailer server, for example
{ "language": "en", "url": "https://stackoverflow.com/questions/7557697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UML Tool to reverse engineer object diagrams from java source? I have been playing around with a few various UML tools- Enterprise Architect, Visual Paradigm; in the end I found Intellij IDEA good enough for producing quick UML class diagrams. However, I found creating UML object diagrams quite fiddly in EA and VP. I was wondering if there was anything out there that could reverse engineer some simple java code that creates some class instances - then create UML Object Diagrams from this? A: We use UmlGraph embedded into a maven build, so we get graphs in the generated javadoc. A: You should explore ObjectAid, it has an eclipse plugin as well. A: There's a plugin for eclipse called AmaterasUML that does a nice job on a hand full of source files. It's not very useful for long term documentation but for quick and dirty "what's this package do?" it rocks. A: Why not try Star UML.. its free and very easy to use.. http://staruml.sourceforge.net/en/ A: You can use the 30 days evaluation licence and create all needed diagrams for documentation. No need to purchase if you save diagrams as image and paste and copy them into your documentation. Just unzip and it works. The build is available at: http://www.uml2.org/eclipse-java-galileo-SR2-win32_eclipseUML2.2_package_may2010.zip
{ "language": "en", "url": "https://stackoverflow.com/questions/7557698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where to declare ViewControllers for a custom tab view? I'm trying to figure out how to use a custom tab view I found called JMTabView by Jason Morrissey on GitHub. (I tried asking him directly but got no response.) I know how to programmatically create a UITabBarController and assign view controllers. What I can't figure out is where to declare my four UITableViewControllers and other VC's for each of the four tabs in this example. The code: // TabDemoAppDelegate.m -> do I declare them here? - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { TabDemoViewController * demoViewController = [[[TabDemoViewController alloc] initWithNibName:nil bundle:nil] autorelease]; self.navigationController = [[[UINavigationController alloc] initWithRootViewController:demoViewController] autorelease]; //[self.navigationController setNavigationBarHidden:YES]; self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; [self.window addSubview:self.navigationController.view]; [self.window makeKeyAndVisible]; return YES; } // TabDemoViewController.m -> or somewhere in here? -(void)addCustomTabView; { // this is a private method JMTabView * tabView = [[[JMTabView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 60., self.view.bounds.size.width, 60.)] autorelease]; tabView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth; [tabView setDelegate:self]; UIImage * standardIcon = [UIImage imageNamed:@"icon3.png"]; UIImage * highlightedIcon = [UIImage imageNamed:@"icon2.png"]; CustomTabItem * tabItem1 = [CustomTabItem tabItemWithTitle:@"One" icon:standardIcon alternateIcon:highlightedIcon]; CustomTabItem * tabItem2 = [CustomTabItem tabItemWithTitle:@"Two" icon:standardIcon alternateIcon:highlightedIcon]; CustomTabItem * tabItem3 = [CustomTabItem tabItemWithTitle:@"Three" icon:standardIcon alternateIcon:highlightedIcon]; CustomTabItem * tabItem4 = [CustomTabItem tabItemWithTitle:@"Four" icon:standardIcon alternateIcon:highlightedIcon]; [tabView addTabItem:tabItem1]; [tabView addTabItem:tabItem2]; [tabView addTabItem:tabItem3]; [tabView addTabItem:tabItem4]; [tabView setSelectionView:[CustomSelectionView createSelectionView]]; [tabView setItemSpacing:1.]; [tabView setBackgroundLayer:[[[CustomBackgroundLayer alloc] init] autorelease]]; [tabView setSelectedIndex:0]; [self.view addSubview:tabView]; } He mentions blocks... if they're relevant, what are they and is this where I would declare the VC's? If so, how? // You can run blocks by specifiying an executeBlock: paremeter // #if NS_BLOCKS_AVAILABLE // [tabView addTabItemWithTitle:@"One" icon:nil executeBlock:^{NSLog(@"abc");}]; // #endif A: I'm not familiar with that particular library, but if it follows a similar pattern to UITabViewController I would create properties for your tab (if you need to reference them later) in your App Delegate's .h file and then create your instances in the .m. If you are just placing the tabs and don't need to reference them directly anymore you should be able to define them in the .m (probably in applicationDidFinishLaunching) and then assign them as tabs and let the tab controller take it from there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing Google Stock XML I've spent a silly amount of time trying to figure this out, but at this point it's driving me insane. I'm trying to parse the XML for Google's unofficial stock api like this: http://www.google.com/ig/api?stock=GOOG I've never dealt with XML that uses only attributes, so I don't know if that's what's making me completely useless at figuring this out. I'm pulling in the XML via a simple PHP snippet, then attempting to parse it using jQuery.parse(). <script> var xml = '<? echo get_url_contents('www.google.com/ig/api?stock=GOOG'); ?>', xmlDoc = $.parseXML( xml ), $xml = $( xmlDoc ), $title = $xml.find( "last" ); /* append stock value to #goog */ $( "#goog" ).append( $this.attr($title) ); </script> Am I just completely on the wrong track here? Any guidance would be fantastic. A: Here’s what that last line would look like: $("#goog").text($title.attr("data")) (Although I’m not sure why the variable holding the <last> element is called $title?)
{ "language": "en", "url": "https://stackoverflow.com/questions/7557704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calculate percentage of total columns based on total column in SSRS Matrix Looking to add a column in my SSRS Matrix which will give me the percentage from the total column in that row. I'm using the following expression, but keep getting 100% for my percentages (I'm assuming this is because the total is evaluated last, so it's just doing Total/Total? =FORMAT((Fields!ID.Value/SUM(Fields!ID.Value)), "P") The field ID is calcuted within SQL, not SSRS. For example Site | Value 1 | %1 | Value2 | %2 | Total 1 | 20 | 50% | 20 | 50% | 40 A: Hard to provide details without more info on the setup of your groups, but you should look at using the scope option to the aggregate operators like SUM or first: =SUM(Fields!ID.Value, "NameOfRowGrouping") / SUM(Fields!ID.Value, "TopLevelGroupName") Also, to keep things clean, you should move your format out of the expression and to either the placeholder properties or textbox properties that contains your value. A: Probably this is happening because you need define the right scope for the SUM function: SUM(Fields!ID.Value,"group_name") instead of plain SUM(Fields!ID.Value) Updated: I needed some time to make an example since I didn't have reporting services available the first time I answered you. You can see the result and the field values
{ "language": "en", "url": "https://stackoverflow.com/questions/7557705", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Best way to transfer mixed unicode and single byte characters over boost::asio We're trying to use winapi widestring functions to retrieve registry information. We then need to transfer that information across the network. LPWSTR PerfData = (LPWSTR) malloc(8192); RegQueryValueEx(hSubKey, TEXT("DisplayName"), NULL, NULL, (LPBYTE) PerfData, &cbData); Now that we have the widestring characters we will be padding them with xml in single byte characters. It is important to save as much bandwidth as possible because as this iterates over thousands of computers it already clogged our network when we were using the single bytes. Also, how am I going to separate these on the other side? A: The cheapest (in terms of bandwidth) protocol I've used so far was Google's protobuf. I strongly recommend it. As for boost-asio, it's not causing any overhead - asio is a good choice. You can also consider compressing it (use boost iostreams gzip filter with asio).
{ "language": "en", "url": "https://stackoverflow.com/questions/7557706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: perforce on sourceforge Has anyone set up a perforce server on sourceforge.net? Is this even possible? Any tips appreciated! I'd like to investigate it and possibly move from Subversion. A: You might look into http://info.perforce.com/FreeTrial_Cloud_Offer.html A: No. SourceForge isn't a free-for-all where you can run whatever you want... You can only use the tools they provide. Perforce is a heavily server-based VCS, so you need to be able to run the Perforce server somewhere centrally. If you want to use Perforce you'll have to find a provider that offers Perforce, or a straight server, so that you can install your own programs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How long will a non-clearing notification stay? If my app fires a notification and marks it as non-clearing (i.e. tapping it does not remove it), what will result in the notification being removed? Would I be right in assuming that if the app is shut down by the memory manager that this will cause the notification will be removed? Or will the notification persist even if the app is recycled? My app needs to show a persistent notification, and I need to understand whether I can set it up in the app, or if I need to build a service to manage it. A: When you start a notification with the FLAG_NO_CLEAR it will persist until you cancel it in the NotificationManager with a call to NotificationManager.cancel(int notificiationId) I'm not sure what would happen to the notification if your app were uninstalled, although I suspect it would be cleared then too. That said it should be really easy to test. Create an activity that creates a notification. Then close it, kill it, uninstall it, etc... and see what happens.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557711", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jstl el function error on websphere I am using a similar conditional check using JSTL in a jspx file <jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:fn="http://java.sun.com/jsp/jstl/functions"> <c:choose> <c:when test="${fn:startsWith(check.defApplication, 'Mail')}"> <c:set var="mySet" value="messages"/> </c:when> <c:otherwise> <c:set var="mySet" value="messagesagain"/> </c:otherwise> </c:choose> but its throws the error Unable to locate the el function startsWith in the tld with uri http://java.sun.com/jsp/jstl/core The el function is defined for uri http://java.sun.com/jsp/jstl/functions but still it gives the wrong uri in the error message. I changed the order in the uri declarations, but the error message remained the same. The uri is properly defined in web.xml. The above code works perfectly fine on tomcat, but gives error on Websphere 7.0.0.19. Any idea what might be going wrong ? A: I'm not sure about the real cause of the problem. However the following statements indicates that something is not entirely right: The uri is properly defined in web.xml. You should not define them in your web.xml. Just having the JAR file in runtime classpath ought to be sufficient. In case, you should also not have extracted the JSTL JAR file(s) and put its loose contents around in your webapp's /WEB-INF. The above code works perfectly fine on tomcat, but gives error on Websphere 7.0.0.19. Websphere ships with its own JSTL library. This conflict indicates that you've dropped the JSTL JAR file(s) in webapp's /WEB-INF/lib. You'd like to remove them and put them in Tomcat's own /lib folder. See also: * *Our JSTL wiki page A: Check this : https://www.ibm.com/developerworks/community/forums/html/topic?id=869d42f2-6ef6-4708-b5fd-dec19afe1f03&ps=25 They believe that webpshere not allow to run jsp inside web-inf
{ "language": "en", "url": "https://stackoverflow.com/questions/7557713", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to access workitem link and attachment history I am working with TFS API and trying to create the history tab exactly same as what we see in TFS explorer. So far I am able to figure our the changes to Fields via WorkItem > Revisions > Fields I am not able to create the proper history for Links and Attachment changes. Links have Link Type, Work Item, Comment and Change I can see the Link type and Comment fields in WorkItem > Links but how to figure out change and WorkItem columns? Similarly for attachments. Any idea? A: Given you have gained access to a WorkItem "myWorkItem" you can retrieve what you 're after with: WorkItemLinkCollection LinkedWIs = myWorkItem.WorkItemLinkHistory; foreach (WorkItemLink workItemLink in LinkedWIs) { string AddedDate = workItemLink.AddedDate.ToString(); } AttachmentCollection AttachedTokens = myWorkItem.Attachments; foreach (Attachment attachedToken in AttachedTokens) { string FileName = attachedToken.Name; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557723", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to create a rounded image border? is it possible to do rounded CSS borders once the user has uploaded the image? I want the css to make a rounded border like the image below: I know you can do it with CSS3 but I am using aspdotnetstorefront and it forces IE7 mode. So any css needs to work with IE7.. :( A: You can use CSS3 PIE or CurvyCorners. A: CSS3PIE would save your life -webkit-border-radius: 20px; -moz-border-radius: 20px; border-radius: 20px; background: #EEFF99; behavior: url(/PIE.htc); A: Photoshop can help you. You cannot do any CSS3+ effects with IE7-
{ "language": "en", "url": "https://stackoverflow.com/questions/7557730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it a BAD idea to have a static connection and transaction for a Unit Test Fixture? I plan to create static private variables for SqlConnection and SqlTransaction which I plan to create in [ClassInitialize()] signed method and then dispose in [ClassCleanup] signed methods. What I want to achieve is to share the connection and transaction all along the tests and then roll back everything in the end of the last unit test run. Like below. Is this a BAD idea? Should I worry about thread safety? [ClassInitialize()] public static void DataManagerTestInitialize(TestContext testContext) { // Create Connection for Test Fixture _connection = new SqlConnection(ConnectionString); // Open Connection for Test Fixture _connection.Open(); // Open Transaction for Test Fixture _transaction = _connection.BeginTransaction(); } [ClassCleanup] public static void CleanUp() { if(_transaction!=null) _transaction.Rollback(); if(_connection.State != ConnectionState.Closed) _connection.Close(); } A: This is a bad idea. Connections are meant to be opened - used - then closed. The same goes for transactions. Besides - your tests should be independent of each other and sharing a connection / transaction violates this principle. A: You should worry about locks in the database if someone is debugging a specific unit test. If the database you use is the same database as your development occurs on this can be very frustrating when you're developing something (for example) and performance is really bad or he even gets timeouts because of someone putting locks on the database. If you don't want to change your database (which you don't when unit testing) you should be able to mock/replace the code that hits the database. There are several ways to achieve this but my favorite is to use Dependency Injection. This makes your application a lot easier to maintain as it forces you to think carefully about what methods are exposed by the various parts of your application. Plus the abstraction will make it easier to refactor.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: VS 2010 RDLC -Desginer We have a VS2008 solution with a project that had RDLC files. We generate them dynamically in code, and don't need the viewer. However, when we converted to VS2010, when I open the .rdlc i don't get the designer, it just opens as XML. Even if I create a new rdlc from scratch in 2010, it opens in xml, not with the designer. Help!!! A: Reporting Services development is done in Business Intelligence Development Studio (BIDS), which uses the Visual Studio shell. The Visual Studio 2010 shell is not yet supported. You'll have to edit the report in BIDS using the VS2008 shell. Check the second note here for more info.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557738", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Comet-style Long-Poll in AIR using URLStream I'm attempting to connect to an existing Comet-style long-poll service using an AIR app. The service expects a client to make a GET request with a Connection: Keep-Alive header. This request will remain open for long periods of time so that the server can push data through. In my app, the connection is terminated with an IOError after 30 seconds. Is this an undocumented limitation of URLStream? A restriction on adl (I've only been running my app through adl)? The server does not send any "keep-alive" messages to the client but, unfortunately this is not something i have control over. Update To test this, I've set up a stripped-down version using a little php script (linked by leggetter below) and am hitting it from a simple AIR app. I'm finding that my connections are closed after 30 seconds whether I use URLStream or URLLoader. the PHP: <?php set_time_limit(0); sleep(40); echo("START!"); header('Content-type: text/plain'); echo str_pad('PADDING', 2048, '|PADDING'); $sleep_time = 1; $count = 0; while($count < 20) { echo($count); flush(); $count = $count + 1; sleep($sleep_time); } echo("end"); ?> And the Actionscript: private function beginSubscribeToNotifications():void { var req:URLRequest = new URLRequest(myPHPFile); req.method = URLRequestMethod.GET; req.requestHeaders.push( new URLRequestHeader("Connection", "Keep-Alive")); _urlLoader = new URLLoader(); _urlLoader.addEventListener(Event.COMPLETE, onComplete); _urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError); _urlLoader.load(req); } private function onComplete(e:Event):void { _message = (String)(_urlLoader.data); } If i adjust the initial sleep time in the php script to anything over 30 seconds, the IOError event is triggered. If I lower the sleep time, but the request continues adding data past 30 seconds, the onComplete event is called, but _urlLoader.data is empty. The only way this process completely successfully is if the entire thing is over before 30 seconds elapses. A: Well, this is somewhat embarrassing, but I figured I'd post in case someone else runs in to this. I have solved my issue by setting the value of URLRequestDefaults.idleTimeout. According to the documentation: When this property is set to 0 (the default), the runtime uses the default idle timeout value defined by the operating system. The default idle timeout value varies between operating systems (such as Mac OS, Linux, or Windows) and between operating system versions. I guess for Windows 7 it was 30 seconds.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to align this button to the right of the screen? I've tried adding style: float: right to the button but it isn't working. myapp.cards.home.add({ xtype: 'button', id: 'previmagebutton', // text: 'p', iconCls: 'arrow_left', iconMask: true, style: 'float: right' }); myapp.cards.home = new Ext.Panel({ scroll: 'vertical', id: "home-card", layout:{ type:"vbox", align:"center" }, items: [header] }); myapp.mainPanel = new Ext.Panel({ fullscreen: true, layout: "card", cardAnimation: 'slide', items: [myapp.cards.home] }); I have to use the add method if that is what's causing the problem. Many thanks. A: In your myapp.cards.home object you have the layout set up to align:"center". A: I've succeeded in creating a floating button by using floating:true config on the button. It is a private member, so I'm still looking for an official way. A: This should work :: layout : { type : 'vbox', align : 'left' } or you can add a spacer if its in the toolbar, or if you stretch the element, then add another hbox element on its side with a flex that occupies as much space that you don't need
{ "language": "en", "url": "https://stackoverflow.com/questions/7557750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Submit form with Enter - Cannot select previously entered value with arrow keys + Enter I'm using a simple javascript to submit a form when the Enter key is pressed: $("input").keypress(function (e) { if (e.which == 13) { $(this).closest("form").submit(); return false; } }); Now there is a problem with this. Browsers remember what you have typed in text fields before. So lets say I chose something from the "auto completion". I hit my down arrow key and hit enter, wanting to select a previously entered value. Then the forms obviously submits, due to the keypress event. Is there even a way to solve this? A: The keypress event is fired before the browser fills in the input field. Keep track of what's in the field before the user hits Enter, and you can tell if the value changed by some means other than a keypress. It won't submit if the user hit Enter to select an auto-filled value. This works in at least FF and Chrome: var typed = ""; $(document).ready(function(){ $("#input-field").keypress(function (e) { if (e.which == 13) { if($("#input-field").val() != typed) { $(this).closest("form").submit(); //alert($("#input-field").val()); return false } } typed = $("#input-field").val(); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7557754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JPQL query: selecting a single Boolean which is the AND of two of object's fields Suppose that I have a JPA-annotated class called MyData with a primary identifier field (BigDecimal type called "primaryID"), and two Boolean fields called "fieldA" and "fieldB". What I want to do is create a JPA query that will select fieldA AND fieldB for a given MyData instance. final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); final CriteriaQuery<Boolean> boolQuery = builder.createQuery(Boolean.class); final Root<MyData> data = boolQuery.from(MyData.class); boolQuery.select(builder.isTrue(builder.and(data.<Boolean> get("fieldA"), profile.<Boolean> get("fieldB")))); final Predicate primaryIDPredicate = builder.equal(profile.<BigDecimal> get("primaryID"), 1000); boolQuery.where(primaryIDPredicate); final TypedQuery<Boolean> myQuery = entityManager.createQuery(boolQuery); When my entityManager executes this query, I get: org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: and near line 1.... This leads me to believe that I need something different (other than the builder.isTrue method) to designate that I want to take a Boolean and of two fields of my object. Any ideas on how I should construct this query? A: OK, what I ended up doing was simply moving the booleans I wanted to "AND" into the predicate instead, and just checking whether anything was returned. Of course, I could have simply retrieved the entire object (MyData) based on the primary ID, and done the "AND" in Java code, but the point was to avoid fetching the full object because it has a large number of nested joins to its referenced collections, and those would be unnecessary for this case. final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); final CriteriaQuery<BigInteger> primaryIDQuery = builder.createQuery(BigInteger.class); final Root<MyData> data = primaryIDQuery.from(MyData.class); primaryIDQuery.select(data.<BigInteger> get("primaryId")); final Predicate primaryIDPredicate = builder.equal(profile.<BigInteger> get("primaryId"),1000); final Predicate otherPredicate = builder.or( builder.isTrue(profile.<Boolean> get("fieldA")), builder.isTrue(profile.<Boolean> get("fieldB"))); primaryIDQuery.where(primaryIDPredicate , otherPredicate); final TypedQuery<BigInteger> existenceQuery = entityManager.createQuery(primaryIDQuery); boolean whatIWant = existenceQuery.getResultList().size() > 0;
{ "language": "en", "url": "https://stackoverflow.com/questions/7557755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Apply multiple Filtering to WPF datagrid using C# I have a datagrid which is boud to a database table. I could filter the datagrid using an ICollectionView using the code below: lstOrdsRlsd = new ObservableCollection<OrdsRlsd>(GV.dbContext.OrdsRlsds); view = CollectionViewSource.GetDefaultView(lstOrdsRlsd); if (lstOrdsRlsd.Count > 0) { dgRecords1.ItemsSource = view; } private void FilterRecords(string FieldName, string Condition, object Value1, object Value2) { OrdsRlsd vitem; switch (FieldName) { case "OrderNo": view.Filter = item => { vitem = item as OrdsRlsd; switch (Condition) { case "=": if (vitem.OrderNo == Convert.ToDouble(Value1)) return true; break; case ">=": if (vitem.OrderNo >= Convert.ToDouble(Value1)) return true; break; case "<=": if (vitem.OrderNo <= Convert.ToDouble(Value1)) return true; break; case "between": if (vitem.OrderNo >= Convert.ToDouble(Value1) && vitem.OrderNo <= Convert.ToDouble(Value2)) return true; break; } return false; }; break; case "DateRqd1": view.Filter = item => { vitem = item as OrdsRlsd; switch (Condition) { case "=": if (vitem.DateRqd1 == Convert.ToDateTime(Value1)) return true; break; case ">=": if (vitem.DateRqd1 >= Convert.ToDateTime(Value1)) return true; break; case "<=": if (vitem.DateRqd1 <= Convert.ToDateTime(Value1)) return true; break; case "between": if (vitem.DateRqd1 >= Convert.ToDateTime(Value1) && vitem.DateRqd1 <= Convert.ToDateTime(Value2)) return true; break; } return false; }; break; } It works for me when there is only one filtering condition. But when i apply multiple conditions the datagrid filters by the last condition. This is the code executed when the user clicks the filter button. private void BtnFilter_Click(object sender, RoutedEventArgs e) { foreach (var rec in lstClsFilterGrid) { FilterRecords(rec.FieldName, rec.Condition, rec.Value1, rec.Value2); } } where lstClsFilterGrid is a llist of class objects with the filter conditions. I am attaching a screenshot of my form. A: So the workflow on this form is, User creates a condition to filter on and can optionally filter the collection or add another condition, is that correct? If so, then you will have to be able to pass a collection of conditions (probably to an overloaded filter method). I have previously filtered on multiple (fixed) conditions (i.e. several checkboxes bound to properties that map to pre-arranged conditions, say "Past 30 days", "Completed Orders", "Overdue Shipments", etc.). My filter would check the items based on all of those properties. In your case, you have an indeterminate number of dynamic conditions. If this were me, I would have a list to which I would add conditions, then pass the whole collection into a filtering method then each object would have to satisfy all of the conditions in a for loop to return true.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Best way to get database information to a program (windows and mac) I'm using delphi at the moment and have a program that connects to another program (a server) which has the mysql database on it and sends the data back to the client. I have a web server that has the server program and the database but my question is can I just go straight from the client program I have made (windows and future mac) to the mysql database on the web server? Or do I really need the server program? If so, what do I need to do to connect my client program to the MySQL database over the internet? A: You should be able to access the mysql database directly as long as you've created a user/pw combo for the database that allows remote access (Security discussion aside). You'll then want to search for a compatible mysql library that would ease the communication between your program and mysql. At the far technical end you might have to read/write directly to the mysql socket but that's possible as well. A: Depends on whether your client programs will continue to be native applications or whether you plan to migrate to browser based clients. If they're native applications you can obtain library components for the languages they're written in which will be able to communicate directly with the MySQL database. There are plenty of options for Delphi; I'm not familiar with what options might be available for native Mac development (but, of course, Embarcadero is in the process of rolling out a Delphi that can generate Mac applications). If, however, you're planning on making your clients browser-based, ajax solutions want to talk to a web server rather than a database server. In that case, you will need to maintain your middleware. For a discussion of whether it's possible or desirable to have a browser based application communicate directly with a database server see this question. A: I would use SOAP/XML for this, and leave the SQL out of the client entirely. A: This is a typical use case where REST (for example using JSON encoded database records) can be helpful. It is easy to implement a Delphi client using lkJSON or SuperObject, to put the database records from the HTTP response into a TClientDataSet. A: Yes, it's possible, but is it a good idea? here's a basic discussion of 2 tier v 3 tier architecture
{ "language": "en", "url": "https://stackoverflow.com/questions/7557767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Facebook App not working tihe facebook.php SDK Not sure why this isn't working, and was hoping someone might be able to point me in the right direction. I have a facebook tab app that should display different content depending on whether a user "likes us or not." require_once('src/facebook.php'); $app_id = "142214XXXXXXXX"; <--this is correct just hidden $app_secret = "31275c8895XXXXXXXX"; $facebook = new facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'cookie' => true )); $signed_request = $facebook->getSignedRequest(); $like_status = $signed_request["page"]["liked"]; //just for testing (nothing shows up, nor does print($signed_request) echo "the page is ".$page_id; if(!$like_status){ echo "Please LIKE US to get this offer or check back on Sept 27"; } else { echo '<img src="https://www2418.ssldomain.com/frightfurnace/SLOSSbogo.jpg"/><BR /> <a href="http://www.frightfurnace.com/coupon.asp">Printable Page</a>'; } Now, I know that the SDK is installed and working properly since it does work with the example: http://www.frightfurnace.com/Facebook/example.php I have also made sure I am using absolute urls in my Facebook App settings. I am using http://www.frightfurnace.com/Facebook/coupon.php Same with SSL. Any ideas, kinda stymied. All help appreciated. A: Well found the answer in case anyone else needs it. Go to your apps on Facebook https://developers.facebook.com/apps/ Go to edit settings On the left click Advanced signed_request for Canvas: (Make it enabled) iframe Page Tab: (enabled) Under Canvas Settings make sure Canvas Type is iFrame Seemed to work for me. A: Another thing to check: the tab/canvas url must be EXACTLY the same as required. If there is a redirect to another page, then signed request and other values will not be sent. You can check using a browser sniffer, if a call to the page responds with a 300 (301/302 etc) redirect, then you need to change to what it redirects to. Examples: https://example.com/ may need to be https://www.example.com/ (add www., or remove www. depending on how server is set up) www.example.com/ may need to be www.example.com/index.php (add index.php, or the right page). Check you are using http:// and https:// correctly in the URLs, and that https:// returns a valid page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557769", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Analyzing text within a word document - How I can get it to ignore bookmarks? I have a VSTO add-in that is able to match against specific codes in the body of a document. The codes themselves are just strings that I syntactically match for validation. My parsing using StoryRange works fine, but of course, I get the rare exception where a user is doing something funky in their document. I've noticed that some users are introducing bookmarks into the middle of the code string and this throws off my validation match. Instead of of code being '34-RD-345', when you reveal the hidden formatting in Office 2007, you will see something like '34-RID-345'. The bookmark formatting looks similiar to an uppercase i (I) and I can see that a bookmark is present using the bookmark option in the ribbon. Does anyone know how I might be able to ignore the bookmark when I'm scanning the text? Maybe an even better alternative maybe to just confine my parsing to [a-Z][0-9]. Is something like that possible? A: You can get all bookmarks, then delete them all, then parse the document again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557771", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cygwin Gcc - Access I'm currently on Windows Vista Basic. I have recently started on Eclipse, and for that I was required to install cygwin. After that I made an edit in the PATH environment variable in "My Computer>Properties>Advanced Settings". In order to check the functionality, I started cmd-prompt and types C:>gcc This gives the following output: ACCESS IS DENIED I know it's a security permission problem, but I don't know where exactly to do the change in the security settings. Last time I tried it started showing "error-illegal operation" and some error code. A: You can not use gcc in your cmd. you must use it in cygwin shell that installed when you install cygwin A: You can use gcc without using the cygwin shell !! But you will probably end up with some configuration problems, such as not having the correct dll's in the right places. Another common error that can occur, is if you have multiple instances of cygwin installed, the search paths get confused and the gcc system can't find relevant compiler or tries to use the wrong compiler. All the same this is very possible, I've done it myself hundreds of time, when testing compilers I have written. You might want to try invoking 'cc1.exe' for c, or 'cc1plus.exe' for c++, remember to copy the cygwin dll's into the same directory as cc1 or cc1plus, Other than that it could be your user account permissions. Hope this helps. /Tony
{ "language": "en", "url": "https://stackoverflow.com/questions/7557775", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Zend_valdiate_alpha combined with special characters Zend_valdiate_alpha combined with special characters Need to combine An alphanumeric character or underscore with string . for example : need to add control for City name with not necessary with zend_alpha it can be another way any suggestions ?? A: I have exactly the same problem. I need to allow commas, alphas, and whitespaces. The most simple solution, I can think of, is to define callback validation function like this: $myValidator = new Zend_Validate_Callback(function($value) { $value = preg_replace('/,/', '', $value); $alphaValidator = new Zend_Validate_Alpha(array('allowWhiteSpace' => true)); if ($alphaValidator->isValid($value)) return true; return false; }); And using it like this: if ($myValidator->isValid($input)) { // input valid } else { // input invalid } I know this is old but perhaps it can help somebody and I would be interested if there is a simpler solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Qt4 child thread edit Gui on mainthread I have a tablewidget which needs to be appended with data from a child thread. I get this error It is not safe to use pixmaps outside the GUI thread. In c# I used a Disptacher to tell the mainThread to append data in a gui object. I assume there is some how something close to this? Am using qt4.7 I have made a slot in the parent and a signal within the thread object.. an emit signal from the child thread to send a signal to a slot in the parent. but the signal is not firing. when i execute the method like so object->run(); (i.e from mainthread) it works fine.. but when i execute it from the thread object->start(); the signal is not fired.. i neeed to do somework with a thread not in mainthread.. UPDATE--27/09 i just got to the root of the problem.. the signal and slot are working but the child thread is lauching a qnetworkaccessmanger object that is causing all this trouble.. i commented the networkaccess object and no error.. I need the thread to call a network request.. and update the results in the gui.. A: The easiest way is to use Qt's signal/slot mechanism with a connection type of Qt::QueuedConnection. This queues the call to the slot in the thread the receiver object lives in automatically.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is the best approach for inserting data into Excel (2007 and 2010) using C# My current scenario is that I have 20 Excel files that need to be populated by running multiple scripts. Currently this is a manual process. I am about to start a small project that should automate most if not all of the work. Tools: I am currently using Excel 2007, but could potentially be working with Excel 2010 in the near future. I am currently planing to use VS 2005 Professionl or C# Express 2010. My approach is to create templates for the 20 files, so that formatting and data that is not changing is already saved. Through C# I plan to then insert data at appropriate cells within each "Sheet" per file. I have come across multiple approaches that I read on (here and other sites), namely - * *Excel Interop *OLE DB *ADO.NET *Open XML I am trying to find out if someone has done something similar before and which one of the technologies would work best (if possible with some explanation or link for more information). I am sorry if the question is too subjective and not appropriate. I will understand if someone decides to close it. Thanks. A: I might be missing something, but I would think OLE DB and ADO.Net end up being the same if you are talking C#. Basically, you would use the OLE DB provider for Excel for ADO.Net. I recommend http://www.connectionstrings.com/ for how to setup your provider. However, if you are going to use templates, it's pretty easy. Just setup your "tables" in your Excel files. Make sure you use named ranges. All that is left is to write some basic SQL like: INSERT INTO customers(id,name) VALUES (?, ?) And that is it. I have used it occasionally for data manipulation. I do use it far more often for data reading. Regards, Eric. A: I think OLE DB is the easyest way to do this. A: OLEDB is for me the best way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: django with nginx + uwsgi I am trying django on nginx + uwsgi. It works very well (faster than apache mod_wsgi), but if I have more than 100 concurrent connexion ( ie : tested with ab -n 100000 -c 150 http://localhost:8081/ ), I have some broken pipe on uwsgi logs : nginx.conf : user myuser; worker_processes 8; events { worker_connections 30000; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream django { ip_hash; server unix:/home/myuser/tmp/uwsgi.sock; } server { listen 8081; server_name localhost; location / { uwsgi_pass django; include uwsgi_params; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } } uwsgi is started like that : /usr/local/bin/uwsgi -s /home/myuser/tmp/uwsgi.sock --pp /home/myuser/projects/django/est/nginx --module django_wsgi -L -l 500 -p 8 And the error messages from uwsgi are : writev(): Broken pipe [plugins/python/wsgi_headers.c line 206] write(): Broken pipe [plugins/python/wsgi_subhandler.c line 235] version are : 1.0.6 for nginx and 0.9.9.2 for uwsgi Do you know how to solve these error messages ? A: I found the solution, The problem is not at uwsgi side, there is a linux limitation : socket are 128 request long, so to enlarge the waiting queue, you have to tune the kernel : ie : echo 3000 > /proc/sys/net/core/netdev_max_backlog echo 3000 > /proc/sys/net/core/somaxconn A: 150 connection for 8 workers with a listen queue of 100 could be a too high value. Probably you only need to increase the listen queue. This is showed in the uWSGI homepage (under the benchmark sections)
{ "language": "en", "url": "https://stackoverflow.com/questions/7557795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Is it possible to show an alertDialog is still showing when starting a child activity? Is it possible to show an alertDialog that is still showing when starting a child activity? I am asynchronously fetching results from a server. The request is sent from activtiy A which then shows a progressDialog. When the first result is received, activity A starts activity B, which will receive the following results. But the progressDialog shown from A should still be shown when B starts. How can I do this? thanks A: I'm not sure if it will work but you could try changing the owner activity from Activity A to Activity B with: Dialog.setOwnerActivity() for more info see the dialog docs
{ "language": "en", "url": "https://stackoverflow.com/questions/7557796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to locate Anonymous Types in source code files using Visual Studio During the process of obfuscating a .NET assembly (using Dotfuscator), I have found myself tweaking how things are renamed. This often involves looking at the assembly in ILDASM and tracing a Type back to the source code file that it is defined in. Usually this is a simple process. But I have found that locating an Anonymous Type is very difficult -- especially in a large assembly. If I am trying to find the location of an anonymous type, such as the following line of code: new { Name = 'Gene', Age = 30 } Which is compiled as: <>f__AnonymousType0`2'<'<Name>j__TPar','<Age>j__TPar'>` And appears as the root of the assembly in the ILDASM tree. If I want to locate the anonymous type in the source code, I am left without much help: * *No Namespace *No symbols to search on *Nothing in the Solution Navigator *Nothing in the Class View *Nothing in the Object Browser Am I missing something? Are there any tools to help locate an Anonymous Type in code files? A: Obviously the code for the anonymous class itself isn't present in the original source code, but there's source code which leads to the creation of the anonymous class, and I assume that's what you're trying to find. However, There may be multiple source files involved. For example, in your example, there could be: Class1.cs: var x = new { Name = "Jon", Age = 10 }; Class2.cs: var y = new { Name = 100, Age = 10m }; // And potentially many other source files Both of those would use the same generic type, but with different type arguments. Basically you'd need to find every anonymous-object-creation-expression expression using the same property names in the same order. I wouldn't be surprised if the metadata contained nothing to help you here directly. EDIT: The generated code will contain a reference to the constructor of the anonymous type, of course - so you could look for that. It's not clear what tools you're using, but searching for the name of the anonymous type within the IL would fine the uses.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NSKeyedUnarchiver - how to prevent a crash I guess this is very obvious, but I have a question about loading data. If have a file called library.dat which stores all kind of information about objects in the app. It's set up all nicely (in terms of the initWithCoder and encodeWithCoder methods etc.), but I was just wondering what happens if the library.dat ever gets corrupted. I corrupted it a bit myself and the app will then crash. Is there any way to prevent a crash? Can I test a file before loading it? Here is the bit which can potentially be very fatal: -(void)loadLibraryDat { NSLog(@"loadLibraryDat..."); NSString *filePath = [[self documentsDirectory] stringByAppendingPathComponent:@"library.dat"]; // if the app crashes here, there is no way for the user to get the app running- except by deleting and re-installing it... self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; } I had a look at *NSInvalidUnarchiveOperationException but have no idea how I should implement this in my code. I'd be grateful for any examples. Thanks in advance! A: Have you tried 'try/catch' blocks? Something like this: @try { self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; } @catch (NSException* exception) { NSLog(@"provide some logs here"); // delete corrupted archive // initialize libraryDat from scratch } A: You can wrap the unarchive call with @try{}@catch{}@finally. This is described in Apple docs here: http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/ObjectiveC/Chapters/ocExceptionHandling.html @try { self.libraryDat = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; } @catch ( NSInvalidUnarchiveOperationException *ex ) { //do whatever you need to in case of a crash } @finally { //this will always get called even if there is an exception }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557800", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Can I use jquery to blank textarea fields or ajax like input boxes? I always use this snippet in my work: <input type="text" onblur="if (this.value=='') { this.value='your email'; }" onfocus="if (this.value == 'your email') { this.value=''; }" value="your email" /> Basically it will show a text box with "your email" as the value, when the clicks the text input box - the value becomes blank.. thus they type their email.. if they don't type an email it will reset back to the "your email". I want to do this or similar with textarea and convert it to jQuery (also the above code in jQuery)? <textarea name="msg">Message:</textarea><br /> A: This ought to do the trick: Will work for both inputs and textareas -- Whatever default you set for each will persist. Use as is. See Fiddle here : http://jsfiddle.net/leifparker/DvqYU/2/ (This pulls and stores the default value in a data attribute) HTML <textarea>I love bananas ..</textarea> <textarea>How about you?</textarea> <input type="text" value="Time for a bath .."> <input type="text" value=".. because I smell"> JS $('textarea, input[type=text]') .each(function(){ $(this).data('defaultText', $(this).val()); }) .focus(function(){ if ($(this).val()==$(this).data('defaultText')) $(this).val(''); }) .blur(function(){ if ($(this).val()=='') $(this).val($(this).data('defaultText')); }); EDIT: An alternative brought up by ANeves, and which makes use of the HTML5 placeholder attribute is below. If you don't care about old browsers, you can use the placeholder HTML on its own (and it works natively, with results similar to the JS above), or otherwise, as below, you'll need to add a JS fallback. Fiddle here : http://jsfiddle.net/leifparker/DvqYU/14/ HTML <textarea placeholder="A few words about yourself"></textarea> <textarea placeholder=".. and a few more about your mangy cat."></textarea> <input type="text" placeholder="Your Awesome City"> <input type="email" placeholder="rickastin@youjustgot.com"> JS function hasPlaceholderSupport() { var input = document.createElement('input'); return ('placeholder' in input); } if (!hasPlaceholderSupport()){ $('textarea, input[type=text], input[type=email]') .each(function(){ if ($(this).val()=='') $(this).val($(this).attr('placeholder')); }) .focus(function(){ if ($(this).val()==$(this).attr('placeholder')) $(this).val(''); }) .blur(function(){ if ($(this).val()=='') $(this).val($(this).attr('placeholder')); }); } A: Use native html attribute title to specify the mask text, and then apply following script: html <input type="text" value="your email" title="your email" /> <input type="text" value="your name" title="your name" /> <textarea title="your description">your description</textarea> JS $('input[type=text], textarea').focus(function() { var $ctrl = $(this); var title = $ctrl.attr('title'); $ctrl.removeClass('mask'); if ($ctrl.val()== title) { $ctrl.val(''); } }).blur(function() { var $ctrl = $(this); if ($ctrl.val().length == 0) { var title = $ctrl.attr('title'); $ctrl.val(title); $ctrl.addClass('mask'); } }); And in this case you will need only to provide titles to the controls. Code: http://jsfiddle.net/pJrG9/7/ A: You could use data attributes for a generic solution that would apply to textareas and input boxes - HTML <textarea name="msg" data-notext="text here">Message:</textarea><br /> <input id="email" type="text" data-notext="email here"/> jQuery $("textarea, input[type=text]").bind('focus blur', function() { if ($(this).val() == '') $(this).val($(this).data('notext')); }) Demo - http://jsfiddle.net/3jwtA/ A: i think you are referring to Placeholder like this: http://andrew-jones.com/jquery-placeholder-plugin/ Hope it helps. A: This is how I would do it, hope it helps. HTML <input type="text" value="Enter your email:" /> <textarea>Message:< /textarea> SCRIPT $("input[type=text]").focus(function(){ if($(this).val() == "Enter your email:") $(this).val(""); }).blur(function(){ if($(this).val() == "") $(this).val("Enter your email:"); }); $("textarea").focus(function(){ if($(this).val() == "Message:") $(this).val(""); }).blur(function(){ if($(this).val() == "") $(this).val("Message:"); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7557801", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UIAlertView, how to place a lot of buttons inside it? In UIAlertView, how can I place a lot of buttons inside it? I've got an alert view and want to place ten buttons inside of it, but when in place, then they don't fit in the screen? Moreover, how should I make the buttons look a little bit different, and how can I change their sizes? UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Фильтр по категориям" message:@"Выбирите категорию:" delegate:self cancelButtonTitle:@"Отменить" otherButtonTitles:@"Все", @"Избранное", @"Тосты", @"Рассказы", @"Стихи", @"Анекдоты", @"Афоризмы", @"Объявления", @"Разное", nil]; In English: UIAlertView * alert = [[UIAlertView alloc] initWithTitle: @ "Filter by Category" message: @ "Choose a category:" delegate: self cancelButtonTitle: @ "Cancel" otherButtonTitles: @ "All", @ "Music", @ "Toast", @ "Stories", @ "Poems", @ "Jokes", @ "Aphorisms", @ "Announcements", @ "Other", nil]; A: You should not place ten buttons inside a UIAlertView. I don't know Russian so I have no clue as to the context of your problem. But there's no reason to put that many choices in an alert view. A: Lorean is correct. On the iPhone, for selecting a category filter, you should use a modal ViewController (with presentModalViewController), which will roll over your main view, allow them to select their category and then disappear. On the iPad, you should use a UIPopoverController. A: You might want to look on alternative alert view implementations https://github.com/TomSwift/TSAlertView But be honest to yourself, if so many buttons make sense on a alert view. You also can use presentModalViewController to present a custom view, where you have all flexibility.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there any way to get a direct pointer to a Java array via JNI? I need to get a pointer containing the direct memory address of a Java array, via JNI, without invoking some sort of copying (ie direct access). GetArrayElements returns a pointer to a copied array - I need to be able to modify an int[] on the Java layer directly from a the native layer. Casting from a jintArray to an int* returns the memory address successfully, but I'm not sure if this is particularly stable...? Is there anything I can do here...? A: You can use an IntBuffer using direct memory (with native byte order). In JNI you can use the address as a pointer. In Java you have to use the get() and put(). A: Maybe. There are methods you can call that might give you a direct pointer to the Java memory, but that depends on the capabilities of the JVM. From http://java.sun.com/docs/books/jni/html/objtypes.html#4099 : The JNI supports a family of Get/ReleaseArrayElements functions (including, for example, Get/ReleaseIntArrayElements) that allow the native code to obtain a direct pointer to the elements of primitive arrays. Because the underlying garbage collector may not support pinning, the virtual machine may return a pointer to a copy of the original primitive array. Note that you need to release the pointer when you're through with it. EDIT: In JDK 1.3, the functions Get/ReleasePrimtiveArrayCritical() were added to obtain a direct pointer even if the JVM does not support pinning. "These restrictions make it more likely that the native code will obtain an uncopied version of the array, even if the VM does not support pinning. For example, a VM may temporarily disable garbage collection when the native code is holding a pointer to an array obtained via GetPrimitiveArrayCritical." However, you're expected to release the pointer as soon as possible, and there are restrictions on your interactions with the JVM. An alternative, if you have frequent but sparse interactions with a large array, is to get only small regions in the array, with GetArrayRegion() functions. A: Another way is getting its address and set one pointer to it with GetDirectBufferAddress method. You can find more information below link: double * cArr = (double *)((char *)env->GetDirectBufferAddress(inpObject)); GetDirectBufferAddress example for a complex object
{ "language": "en", "url": "https://stackoverflow.com/questions/7557804", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Timer working in Console Application I'm trying to get a timer working in my c++ application. I can define my timer: #define IDT_TIMER WM_USER + 200 UINT Timeval; UINT TimerID = 1; UINT TimerMS = 20; Start Stop Timer methods: UINT NAHDPbx::StartTimer (UINT TimerID) { UINT TimerVal; TimerVal = thewindow->SetTimer(TimerID, TimerMS, NULL); // Starting the Timer return TimerVal; }// end StartTimer BOOL NAHDPbx::StopTimer (UINT TimerID) { if (!KillTimer (TimerID)) { return FALSE; } return TRUE; } // end StopTimer And I start the timer like this: Timeval=StartTimer(TimerID); However in my code the timer tick never fires: void NAHDPbx::OnTimer(UINT nIDEvent) { StopTimer(TimerID); //Do stuff StartTimer(TimerID); } Any examples of getting a timer to work? My end goal is to receive data via UDP, and need a way to send and receive at the same time. A: If the console application exits, the timer handler will go out of scope and nothing will happen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does it matter if this is used in a C++ setter? Suppose I have a c++ class with a private variable, x. For it's setter, is there any difference using this? Is there the potential for unwanted / unexpected behavior is I don't use this? Setter: void setX(double input) { x = input; } Setter using this: void setX(double x) { this->x = x; } A: These two code fragments (assuming they're inline member functions, since there's no ClassName:: bit) are exactly equivalent. Use whichever you prefer. I would tend to recommend against naming parameters the same as member variables though; it's too easy get them mixed up. A: Because of two-phase lookup for class templates, this might be required to * *explicitly state you mean a member *because of lookup rules, the compiler might assume another entity that is visible there is meant (see the first example) Both are equivalent. In a non-template situation, you usually avoid using this; the generated code will be the same, thus there won't be any difference (see the second example). The reason for this is that the compiler will try to lookup every symbol it sees. The first place to lookup is in class-scope (except for block and function scope). If it finds a symbol of that name there, it will emit this implicitly. In reality, member functions are just ordinary functions with an invisible parameter. class Foo { void foo () { x = 0; } void bar () const { std::cout << x; } void frob(); int x; }; void Foo::frob() {} Is actually transformed into class Foo { int x; }; inline void foo (Foo *const this) { this->x = 0; } inline void bar (Foo const * const this) { std::cout << this->x; } void frob (Foo * const this) {} by the compiler. Behavioral example for this in templates: #include <iostream> void foo() { std::cout << "::foo()\n"; } template <typename> struct Base { void foo() const { std::cout << "Base<T>::foo()\n"; } }; template <typename T> struct Derived_using_this : Base<Derived_using_this<T> > { void bar() const { this->foo(); } }; template <typename T> struct Derived_not_using_this : Base<Derived_not_using_this<T> > { void bar() const { foo(); } }; int main () { Derived_not_using_this<void>().bar(); Derived_using_this<void>().bar(); } Output: ::foo() Base<T>::foo() Example assembly for non-template: With this: pushq %rbp movq %rsp, %rbp subq $16, %rsp movq %rdi, -8(%rbp) movq -8(%rbp), %rax movl (%rax), %eax movl %eax, %esi movl $.LC0, %edi movl $0, %eax call printf leave ret Without this: pushq %rbp movq %rsp, %rbp subq $16, %rsp movq %rdi, -8(%rbp) movq -8(%rbp), %rax movl (%rax), %eax movl %eax, %esi movl $.LC0, %edi movl $0, %eax call printf leave ret Verify yourself: test.cc: #include <stdio.h> // Don't use this. I just did so for nicer assembly. class Foo { public: Foo () : i(0) {} void with_this() const { printf ("%d", this->i); } void without_this() const { printf ("%d", i); } private: int i; }; int main () { Foo f; f.with_this(); f.without_this(); } Run g++ -S test.cc. You'll see a file named test.s, there you can search for the function names. A: The this variant makes a syntactical difference when templates are involved. However, it is semantically the same; the this-> variant just makes it clearer you are accessing the current objects and avoids potential collisions. A: void setX(double x) { this->x = x; } If the member variable x would be obscured by the argument x, then this-> is explicitly needed to ensure you are assigning to the correct variable. Otherwise it is not needed. But I don't recommend you name your argument the same thing as a member variable anyway. The first example you give has fewer pitfalls. A: There is no difference between them. A: Although your code will work, it is poor code and likely to confuse somebody. Much better to give the "setX()" parameter a different name. e.g. void setX(double new_x) { x = new_x; } A: Doesn't matter. I've worked with code conventions stating that all private vars should be accessed through this in order to make the code more readable. But other than readability I don't think there is any difference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557816", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Mysql: joining tables for translation records I have 2 tables with this configuration: table language('id', 'language_name', 'iso_code') table translation('id', 'language_id', 'translated_text') In the first table I have records: --------------------------------- | id | language_name | iso_code | --------------------------------- | 1 | English | en | | 2 | Espanõl | es | | 3 | Français | fr | --------------------------------- The second table: -------------------------------------- | id | language_id | translated_text | -------------------------------------- | 1 | 1 | Good Morning | | 2 | 1 | How are you? | | 1 | 2 | Buenos dias | | 2 | 3 | Comment ça va? | -------------------------------------- All English text strings exist, but some of the other languages dont. I would like to show a table with ALL English text strings and corresponding translations, like: ---------------------------------------- | text_id | en | es | ---------------------------------------- | 1 | Good Morning | Buenos dias | | 2 | How are you? | | ---------------------------------------- or ------------------------------------------- | text_id | en | fr | ------------------------------------------- | 1 | Good Morning | Comment ça va? | | 2 | How are you? | | ------------------------------------------- Any ideas? A: Just keep doing left joins to same table on the ID, but extra columns representing their language... Edited to show English if no value in corresponding columns per comment inquiry. select eng.id, eng.translated_text InEnglish, coalesce( spn.translated_text, eng.translated_text ) InSpanish, coalesce( frn.translated_text, eng.translated_text ) InFrench from translation eng left join translation spn on eng.id = spn.id and spn.Language_ID = 2 left join translation frn on eng.id = frn.id and spn.Language_ID = 3 where eng.Language_id = 1 order by eng.id
{ "language": "en", "url": "https://stackoverflow.com/questions/7557817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Prevent duplicate user from being added to database I want to prevent the same user from being added to the database automatically. I want to check this against the FacebookID field/column set in my database. How would I do this? Below is the code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVCFacebookTestApp.Models; using Facebook; using Facebook.Web; namespace MVCFacebookTestApp.Controllers { public class HomeController : Controller { public FacebookSession FacebookSession { get { return (FacebookWebContext.Current.Session); } } public ActionResult Index() { string request = Request.Form["signed_request"]; string accessToken = ""; if (Request.Form["access_token"] != null) { accessToken = Request.Form["access_token"]; } FacebookApplication app = new FacebookApplication(); FacebookSignedRequest result = FacebookSignedRequest.Parse(app.InnerCurrent, request); if (String.IsNullOrWhiteSpace(accessToken)) { accessToken = result.AccessToken; } dynamic data = result.Data; bool liked = data.page.liked; //bool liked = true; if (!liked) { Home h = Home.NotLiked(); return View(h); } else { Home h = Home.Liked(); FacebookWebClient fb = null; if (String.IsNullOrWhiteSpace(accessToken)) { var fbRequest = FacebookWebContext.Current; if (fbRequest.IsAuthorized()) fb = new FacebookWebClient(fbRequest); accessToken = fbRequest.AccessToken; } else { fb = new FacebookWebClient(accessToken); } if (fb != null) { dynamic r = fb.Get("/me"); //h.TestString2 += " Ha! We captured this data about you!"; //h.TestString2 += " Name: " + r.name; //h.TestString2 += " Location: " + r.location; //h.TestString2 += " Birthday: " + r.birthday; //h.TestString2 += " About Me: " + r.aboutme; //h.ImgUrl = "http://graph.facebook.com/" + r.id + "/picture?type=large"; //string fqlResult = ""; //var fbApp = new FacebookClient(accessToken); //basic fql query execution //dynamic friends = fbApp.Query("SELECT uid FROM page_admin WHERE page_id='160828267335555'"); //SELECT uid FROM page_fan WHERE page_id = 160828267335555 //"SELECT uid FROM page_fan WHERE uid=me() AND page_id=<your page id>"; //loop through all friends and get their name and create response containing friends' name and profile picture //foreach (dynamic friend in friends) //{ // fqlResult += friend.uid + ".... "; // //fqlResult += friend.name + "<img src='" + friend.pic_square + "' alt='" + friend.name + "' /><br />"; //} h.AddUser(r.id, accessToken, r.first_name, r.last_name, DateTime.ParseExact(r.birthday, "MM/dd/yyyy", new System.Globalization.CultureInfo("en-GB")), r.email, DateTime.Now, r.gender, "http://graph.facebook.com/" + r.id + "/picture?type=large"); //ViewBag.Likes = fqlResult; } else { //Display a message saying not authed.... } // if statement to stop same user from being added to the database... if () { //condition here } else { //condition here } return View(h); } } } } I'm trying it this way at the moment using the if else if and else statement. var User = SELECT from User WHERE FBID = FBID(); if (User.Count==0) { User.AddUser(facebookID as string, accessToken as string, fName as string, lName as string, dob as DateTime, email as string, dateLiked as DateTime, gender as string, imageURL as string); //Create newUser } else if (User.Count ==1) { //set properties to User[0] } else { // THROW EXCEPTION } and these are my properties to the database that i have created; //public string UserID { get; set; } public string FBID { get; set; } public string AccessToken { get; set; } public string FName { get; set; } public string LName { get; set; } public string Gender { get; set; } public DateTime DOB { get; set; } public string Email { get; set; } public DateTime DateLiked { get; set; } public string ImageURL { get; set; } //public string TestString { get; set; } //public string TestString2 { get; set; } public bool IsLiked { get; set; } //public string ImgUrl { get; set; } public void AddUser (string facebookID, string accessToken, string fName, string lName, DateTime dob, string email, DateTime dateLiked, string gender, string imageURL) { //UserID = userID; FBID = facebookID; AccessToken = accessToken; FName = fName; LName = lName; DOB = dob; Email = email; DateLiked = dateLiked; Gender = gender; ImageURL = imageURL; User newUser = new User(); Entities newContext = new Entities(); //newUser.UserID = 1; newUser.FacebookID = facebookID; newUser.AccessToken = accessToken; newUser.FName = fName; newUser.LName = lName; newUser.Gender = gender; newUser.DOB = DOB; newUser.Email = email; newUser.DateLiked = dateLiked; newUser.ImageURL = imageURL; newContext.Users.AddObject(newUser); newContext.SaveChanges(); } } } I hope it makes sense, newbie here so go easy on me. =) A: To preserve the integrity of your database you should add a unique constraint to this column in your database and then catch the exception of the violation of this constraint when performing the UPDATE/INSERT query.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-8" }
Q: Changing default route after a user is logged in How do I change the default route after a user is logged in? I'm using the CodeIgniter framework. A: Rather than changing the default route, you could simply have your controller act differently if they are logged in. Something like: class Welcome extends CI_Controller { public function index() { if($logged_in) { $this->load->view('authenticated'); } else { $this->load->view('guest'); } } } A: You can change the default route with $route['default_controller'] = 'route'; in application/config/routes.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7557825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do you get the ouput from an EXEC statement into a variable (calling procedure on mysql linked server)? I am able to call a procedure on a linked server (MySQL) from Sql2k5. The procedure returns a single row, single column: declare @Statement nvarchar(200) set @Statement = 'call database.procedure(''some string'');' exec (@Statement) at [linkedserver] ... results: some string What I need now is to set a variable to the value returned from the procedure I found a somewhat related post here. but when I try to insert the executed results: insert into sometable exec (@Statement) at [linkedserver] I get this error: OLE DB provider "MSDASQL" for linked server "linkedserver" returned message "[MySQL][ODBC 5.1 Driver]Optional feature not supported". Msg 7391, Level 16, State 2, Line 3 The operation could not be performed because OLE DB provider "MSDASQL" for linked server "linkedserver" was unable to begin a distributed transaction. Is there a way to get around this, or a much better way to get at those results? Thanks, A: Linked servers are a real pain, especially when metadata gets screwed up. An “insert” is a distributed transaction no matter if you use BEGIN/COMMIT TRAN though (inserts cause log usage). Have you tried OPENQUERY yet? Or try these ideas: http://www.sqlservercentral.com/Forums/Topic714869-338-1.aspx#bm716699 Note the provider and the linked server options in the following link: http://www.infi.nl/blog/view/id/4/How_To_MySQL_as_a_linked_server_in_MS_SQL_Server
{ "language": "en", "url": "https://stackoverflow.com/questions/7557830", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Serialize xml different elements to several properties in c# I have next xml: <table-display-fields> <field name="NAME/> <field name="DESCRIPTION" /> </table-display-fields> I deserealize that with next code: [XmlArray("table-display-fields")] [XmlArrayItem("field")] public TableDisplayField[] TableDisplayFields; Then I add new xml element to table-display-fields node: <table-display-fields> <record-number-field name="ID" /> <field name="NAME/> <field name="DESCRIPTION" /> </table-display-fields> Then add next code to deserealize record-number-field: [XmlArray("table-display-fields")] [XmlArrayItem("record-number-field")] public TableDisplayField[] RecordTableDisplayFields; [XmlArray("table-display-fields")] [XmlArrayItem("field")] public TableDisplayField[] TableDisplayFields; This doesn't work. How do I deserealize new xml, and save the existing property path? A: You must remove XmlArrayItem() attribute. [XmlArray("table-display-fields")] public object[] TableDisplayItems; Each object in the TableDisplayItems will be either a field or a record-number-field. Of course, if you only have one single record-number-field on top of your array, the solution can be much nicer. Is it the case ? A: It would help if you can give a more elaborate description on your requirement and then the direction of your approach. If a normal Serializing/Deserializing is what you are looking for you can try the below solution: using System.Collections.Generic; using System.Xml.Serialization; namespace Serialization01 { [XmlRoot( "table-display-fields" )] public class TableDisplayFields { [XmlElement( "record-number-field" )] public string RecordNumberField { get; set; } [XmlElement( "field" )] public List<string> FieldName { get; set; } public TableDisplayFields ( ) { FieldName = new List<string>( 5 ); } } } and use the below code for writing and reading the serialized data: using System.IO; using System.Xml.Serialization; using System; namespace Serialization01 { class Program { static void Main ( string [] args ) { // Initiate the class TableDisplayFields t = new TableDisplayFields( ); t.RecordNumberField = "ID"; t.FieldName.Add( "NAME" ); t.FieldName.Add( "DESCRIPTION" ); TextWriter tw = new StreamWriter( Path.Combine( Environment.CurrentDirectory, "Data.xml" ) ); XmlSerializer xs = new XmlSerializer( t.GetType( ) ); xs.Serialize( tw, t ); tw.Flush( ); tw.Close( ); TextReader tr = new StreamReader( Path.Combine( Environment.CurrentDirectory, "Data.xml" ) ); TableDisplayFields t2 = xs.Deserialize( tr ) as TableDisplayFields; Console.WriteLine( "RecordNumberField for t2 is {0}", t2.RecordNumberField ); foreach ( string field in t2.FieldName ) { Console.WriteLine( "Found field '{0}'", field ); } } } } Hope that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557832", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Facebook mobile web OAuth issue I'm seeing a problem requesting permissions with Facebook connect on iPhones. Everything had been working fine and then it just started out of nowhere. I can't seem to sort it out, so I posted it here to see if anyone's experiencing the same issues? I'm trying to log users into a mobile website and here's what I'm seeing: * *On Android, everything is A-OK, as are regular web browsers. *On the iPhone 3, users get the login page ok, but are not redirected to the request permissions page, just to mobile facebook. If they leave and come back and click on the login button again, they are taken to the request permissions page, and after they allow/don't allow, they are taken back to our site. This is also the same for iPad users *On the iPhone4, users get the login page ok, but are not redirected to the request permissions page, just to mobile facebook. If they leave and come back, they are taken to the mobile facebook site and never are prompted for their permissions. Highlights: * *Everything was fine 3 weeks ago *Everything is still fine on Android using the very same FBConnect url, but it blows on iOS *What happens on iPhone 3 is different that what happens on iPhone 4 I've tried doing this with 3 different urls, but StackOverflow will only let me put 2 in here because I'm a new user: http://www.facebook.com/dialog/oauth?client_id=[OUR_CLIENT_ID]&redirect_uri=[OUR_URL]&display=wap&scope=email,user_location,read_friendlists,publish_stream,offline_access http://m.facebook.com/dialog/oauth?client_id=[OUR_CLIENT_ID]&redirect_uri=[OUR_URL]&perms=email,user_location,read_friendlists,publish_stream,offline_access"; The other URL was similar to these, but used the graph API Anyone have any ideas? Thanks! A: Facebook has since removed the WAP interface and replaced that with Javascript SDK interfaces for Android and iOS, and now normal wap enabled phones have been shut out.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Split with line with perl Possible Duplicate: Split line with perl I have a line: regizor: Betty Thomas Distribuţia: Sandra Bullock (Gwen Cummings) Viggo Mortensen (Eddie Boone) Dominic West (Jasper) rendező: David Mamet, Robert Elswit szereplő(k): Chiwetel Ejiofor (Mike Terry) Alice Braga (Sondra Terry) Emily Mortimer (Laura Black) I want to split with perl in: regizor: Betty Thomas Distribuţia: Sandra Bullock (Gwen Cummings) Viggo Mortensen (Eddie Boone) Dominic West (Jasper) rendező: David Mamet Robert Elswit szereplő(k): Chiwetel Ejiofor (Mike Terry) Alice Braga (Sondra Terry) Emily Mortimer (Laura Black) A: How about: my @splitBits = split /(?=\S+: )/, $str; This will split the string before every occurrence of a "word" (a sequence of non-space characters) followed by a colon and a space (and without producing an empty field at the beginning). A: You could use the following regex: $line =~ s/(\S+:)/\n$1/sg; This says "Find any non-space character (\S), at least once (+), which has a colon after it, and stick a new line in front of it." You'll get a leading newline which you can chop off easily. When I ran it on your line, I got regizor: Betty Thomas Distribuţia: Sandra Bullock (Gwen Cummings) Viggo Mortensen (Eddie Boone) Dominic West (Jasper) rendező: David Mamet, Robert Elswit szereplő(k): Chiwetel Ejiofor (Mike Terry) Alice Braga (Sondra Terry) Emily Mortimer (Laura Black) A: perl -p -e 's/ ([^ ]*?:)/\n$1/g' <file.txt Gives: regizor: Betty Thomas Distribu.ia: Sandra Bullock (Gwen Cummings) Viggo Mortensen (Eddie Boone) Dominic West (Jasper) rendez.: David Mamet, Robert Elswit szerepl.(k): Chiwetel Ejiofor (Mike Terry) Alice Braga (Sondra Terry) Emily Mortimer (Laura Black)
{ "language": "en", "url": "https://stackoverflow.com/questions/7557843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Is it possible to setup a generic stream/view for building releases from any baseline? Is there a way to set up a single stream/view that can be used to build releases from any existing baseline (new and old) on any stream of a ClearCase UCM project? A: What I usually use is a base ClearCase dynamic view, in order to quickly change baselines in its config spec. A baseline is a label put on every files of a component, so the config spec would be: element /vob/Component/... MY_BASELINE element * /main/LATEST Note that it will only work with fully labeled baselines (and not incremental baselines) You can use also a snapshot view, for the compilation will be quicker (but you will have to support the update download time)
{ "language": "en", "url": "https://stackoverflow.com/questions/7557845", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TemplateField HeaderText ASP I want HeaderText to be displayed only when Edit Mode is active <asp:TemplateField> <EditItemTemplate> <asp:FileUpload ID="fileUploadControl" runat="server" /> </EditItemTemplate> </asp:TemplateField> I don't have Insert Template And I want header text to be displayed in only during edit mode A: One way to do so would be to subscribe to the RowDataBound (assuming you are using a GridView). Check if a Row is in the Edit state, and update the corresponding header text for the Cell. protected void grd_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowState == DataControlRowState.Edit) { grd.HeaderRow.Cells[0].Text = "Upload a File"; // Cell 0 in this case may need to be changed to match your Cell. } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: set auto increment initial value for mysql table I'm trying to create a table in my sql using PHP but I'm not sure how to set an initial value for the auto increment field. This is what i have so far: function create_table($db_host,$db_user,$db_pswrd,$db_name){ $connect = mysql_connect($db_host,$db_user,$db_pswrd) or die(mysql_error()); mysql_select_db($db_name, $connect); $sql = "CREATE TABLE MY_TABLE ( table_id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(table_id), table_1 varchar(45), table_2 varchar(45), table_3 varchar(999), table_4 varchar(45) )"or die(mysql_error()); mysql_query($sql,$connect)or die(mysql_error()); mysql_close($connect); } So i need to know how to set the initial Auto Increment value on this table, upon creation? Thanks A: Assuming your auto increment column is the first one: $sql = "CREATE TABLE MY_TABLE ( table_1 INT AUTO_INCREMENT, table_2 varchar(45), table_3 varchar(999), table_4 varchar(45) ) AUTO_INCREMENT = 231"; The starting value will be, here, 231. I changed the column type to INT, because you can't use a VARCHAR for auto-increment. (and remove the or die(mysql_error()) on this line btw, its pointless because it's just a variable creation, not a SQL query being executed) A: If you don't have the auto-increment column in the table yet: $sql = "ALTER TABLE MY_TABLE ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD INDEX (id);"; Then to set the auto-increment starting value: $sql = "ALTER TABLE MY_TABLE AUTO_INCREMENT = 111111;"; Potential duplicate of this post.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Get the value of an AttachedProperty of a UI item not (yet) displayed I'm trying to do the following using MVVM, Binding and AttachedProperty * *Create a ViewObj (System.Windows.Controls.Control derived class) * *The ViewObj has 1 AttachedProperty named "Order" (OrderProperty) declared in a class named View. *The attached property is bound on a property of the ViewModel in the xaml *Create the ViewModel *Set the ViewModel as DataContext of the ViewObj Before the ViewObj is displayed/rendered/etc. * *Get the order in code doing var order = View.GetOrder(ViewObj) *The ViewObj is displayed and is showing the bound value ... If the AttachedProperty is a value and not a binding expression, the value returned by View.GetOrder(ViewObj) is the good one and not the default one. Any ideas? EDIT: I forced the databinding expression to be evaluated using the BindingExpression class. I discovered that the BindingExpression.Status was set to Unattached which seems to explain why it is not working. I think the binding is attached when the element is attached to the visual tree. But ... that do not help me a lot with my problem ... A: I discovered that (in my case at least), the Binding was Unattached, but the DataContext was set. So I decided to get the DataContext (the ViewModel) and to work with it. Any others suggestions are welcome.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557857", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Coverting json array to js objects I have a json string like this [ { "name":"sourabh", "userid":"soruabhbajaj", "id":"11", "has_profile_image":"0" }, { "name":"sourabh", "userid":"sourabhbajaj", "id":"12", "has_profile_image":"0" }] Now, I want to convert this json array to the string like this so that I can access any object using its id on the entire page. { "11": { "name":"sourabh", "userid":"soruabhbajaj", "id":"11", "has_profile_image":"0" }, "12": { "name":"sourabh", "userid":"sourabhbajaj", "id":"12", "has_profile_image":"0" }} Suggest some code please. Thanx in advance EDIT: Will this work: user.(function(){return id;}) And then accessing objects like this user.id.name I mean is this a correct way of defining object? A: var data = ... the initial array var result = {}; for (var i = 0; i < data.length; i++) { var element = data[i]; result[element.id] = element; }; A: var data = [ {"name":"sourabh", "userid":"soruabhbajaj", "id":"11", "has_profile_image":"0"}, {"name":"sourabh", "userid":"sourabhbajaj", "id":"12", "has_profile_image":"0"} ]; var newData = {}; for (var i = 0; i < data.length; i++) { var item = data[i]; newData[item.id] = item; } Now newData is an object where the keys are the ids of the people and the data for each key is the person object itself. So, you can access an item like this: var id = "11"; var name = newData[id].name;
{ "language": "en", "url": "https://stackoverflow.com/questions/7557864", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-8" }
Q: How to clear the static content cache of JRun How can I clear the cache used by JRun for static content? We use LCDS (that runs on JRun), and serve some SWF files with it. When replacing SWFs with newer versions, we would like the new versions of the SWFs to be served, without restarting JRun/LCDS. this is because we don't want any downtime. Many thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7557865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails form_for with associations defined and multipart set to true not working So I have one form working just fine: <%= form_for([@document, @comment]) do |f| %> And then I have another form where I need to include a Carrierwave upload that is like this: <%= form_for([@document, @comment]), :html => { :multipart => true } do |f| %> The first one works fine but the second one breaks by pointing to the form definition with the error: undefined method `comments_path' for #<#<Class:0x0000010475dde8>:0x0000010475a440> Any ideas? Running Rails 3.0.0 with Ruby 1.9.2p180 A: <%= form_for([@document, @comment], :html => { :multipart => true }) do |f| %> A: <%= form_for (@comment, :url => [@document, @comment], :html => {:multipart => true}) do |f| %> I believe that will fix it for you.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: document.head, document.body to attach scripts I have often used, and seen recommended, dom-access structures like this for adding content to pages dynamically: loader = document.createElement('script'); loader.src = "myurl.js"; document.getElementsByTagName('head')[0].appendChild(loader); Now, by chance, I find that this works in Google chrome: document.head.appendChild(loader); A little more investigation, and I find that this works, apparently cross-browser: document.body.appendChild(loader); So my primary question is: are there any reasons why I shouldn't attach elements to the BODY like this? Also, do you think document.head will become more widely supported? A: document.body is part of the DOM specification, I don't see any point why not to use it. But be aware of this: In documents with contents, returns the element, and in frameset documents, this returns the outermost element. (from https://developer.mozilla.org/en/DOM/document.body) document.head currently isn't defined in any DOM specification (apparently I was wrong on that, see Daniel's answer), so you should generally avoid using it. A: The answers given as far as now focus two different aspects and are both very useful. If portability is a requirement for you, in documents not under your ownership where you can't control the DOM coherence, it may be useful to check for the existence of the element you have to append the script to; this way, it will works also when the HEAD section has not been explicitly created: var script = document.createElement('script'); var parent = document.getElementsByTagName('head').item(0) || document.documentElement; parent.appendChild(script); Apart of CORS policy and other easily detectable logic errors, I don't see cases in which this DOM manipulation task should fail, so checking for document.body as a fallback is not necessary by my point of view. As other users outlined too, document.head was not widely supported yet, at the time the question was posted, as it is a HTML5 spec, while document.body is, that's why you saw the latter working on all the browsers. So you could get the HEAD with: document.head || document.getElementsByTagName('head').item(0) but I don't see it very useful, as the latter won't ever be wrong and is a readable and standard DOM query, unless you find out that document.head is faster from a performance perspective. Another possible advantage I can see about this form is a code transition from older JavaScript to a more modern HTML5 compliant code, brief and more readable. If compatibility is a must, you could use tricks adopted by libraries for which portability is mandatory (e.g. solutions from Google, Yandex and others): var parent = document.getElementsByTagName('head')[0] || document.documentElement.firstChild; parent.appendChild(script); This way, in the improbable case the HEAD element does not exist while the BODY (or another element) does, you are sure to append the script to it. I also add a useful bit: the HTTP request of the script source is sent from the browser when the src attribute is set and it is appended to the DOM. No matter in which order these two conditions are met, the last of these two events causes the HTTP request to be dispatched. A: I tried implementing this code and ran into a bit of trouble, so wanted to share my experience. First I tried this: <script> loader = document.createElement('script'); loader.src = "script.js"; document.getElementsByTagName('head')[0].appendChild(loader); </script> And in the script.js file I had code such as the following: // This javascript tries to include a special css doc in the html header if windowsize is smaller than my normal conditions. winWidth = document.etElementById() ? document.body.clientWidth : window.innerWidth; if(winWidth <= 1280) { document.write('<link rel="stylesheet" type="text/css" href="style/screen_less_1280x.css">'); } The problem is, when I did all of this, the code wouldn't work. Whereas it did work once I replaced the script loader with simply this: <script src="script.js"></script> That works for me, so problem solved for now, but I would like to understand the difference between those two approaches. Why did one work and not the other? What's more is that in script.js I also have code such as: function OpenVideo(VideoSrcURL) { window.location.href="#OpenModal"; document.getElementsByTagName('video')[0].src=VideoSrcURL; document.getElementsByTagName('video')[0].play();} And that code does work fine regardless of which way I source the script in my html file. So my window resizing script doesn't work, but the video stuff does. Therefore I'm wondering if the difference in behavior has to do with "document" object...? Maybe "document" is referencing the script.js file instead of the html file. I don't know. Thought I should share this issue in case it applies to anyone else. Cheers. A: I can’t see any reason why it would matter in practice whether you insert your <script> elements into the <head> or the <body> element. In theory, I guess it’s nice to have the runtime DOM resemble the would-be static one. As for document.head, it’s part of HTML5 and apparently already implemented in the latest builds of all major browsers (see http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-document-head).
{ "language": "en", "url": "https://stackoverflow.com/questions/7557868", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Detecting if you are one kilometre from point of interest I have an interesting question. I have a latitude value of 51.445376 and a longitude value of -0.190624 (as an example, say this was recieved by an androids location listener). This particular location (and it's values) is a point of interest and it is stored in my database. I am using a location listener on my android, and I will send the users current location to the server to detect if the user has come within a one kilometre radius of that particular point of interest. Does anyone know what algorithm to use to check if the users current longitude and latitude is within that one kilometre radius of the point of interests longitude and latitude? Or something I can see? Perhaps someone could help me out, as my math is not the greatest in the world. A: For geographic coordinates, use this function (public domain): public static double distanceInKM( double latStart,double lonStart, double latEnd,double lonEnd ){ latStart=Math.toRadians(latStart); latEnd=Math.toRadians(latEnd); return 6370.997*Math.acos( Math.cos(Math.toRadians(lonEnd - lonStart))*Math.cos(latStart)* Math.cos(latEnd)+Math.sin(latStart)*Math.sin(latEnd)); } Calculating the shortest geographic path is called the "inverse geodesic problem", and this is discussed in C.F.F. Karney's article "Algorithms for geodesics, 2012. The method above shows a distance function based on the spherical law of cosines, which is a less accurate way to compute this path, especially because it assumes Earth is a perfect sphere. A: This post from 2008 might be helpful. It links to a MovableType description of how to use the Haversine formula to calculate the distance between two points on a sphere. It's important to note that it's not 100% accurate since the Earth is not a perfect sphere (it's equatorial radius is some 20km different from its polar radius) but should be sufficient for your needs. The MovableType link also describes how to use an equi-rectangular projection (translation of lat/long to rectangular coordinates) and the pythagorean theorem to determine a rougher (but faster) approximation of the distance (good for small distances of ~1-2km.) A: A simple solution: Simply find the distance, by first finding dx and dy. Say I have point 1 (p1) and point 2 (p2) dx = p2.x - p1.x; dy = p2.y - p1.y; Now find the distance d as follows d = sqrt(dx^2 + dy^2) In a programming language like java, you can use the following lines: double d = Math.sqrt(dx*dx + dy*dy); Hope this helps as your starting point! Note: x & y must be calculated accordingly for your lat&lon info. I was going to write a short code snippet but I saw someone else has a nice solution (I upvoted his response).
{ "language": "en", "url": "https://stackoverflow.com/questions/7557870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: VB.NET open source ORM (Like Doctrine for PHP) What is the most doctrine-like ORM for VB.NET? With good documentation. What are the most popular object relational mappers (ORMs) for VB.NET which is like Doctrine (PHP) and have a good extensive documentation? NHibernate seems to be the main one. A: look at Luna, an opensource ORM for vb.net http://www.diegolunadei.it/luna
{ "language": "en", "url": "https://stackoverflow.com/questions/7557872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Migrate commits from another branch, without common parent I've got a repository which was created simply by checking out upstream version at some point. I know the exact commit it came from. Is there an easy way to merge the remaining commits now? How can I do "merge everything after xyz" disregarding missing common history before that commit? A: git format-patch ancestor..HEAD on the source repo, and git am on the target repo would probably work. A: A good solution for exactly this problem is to use git's "grafts" mechanism, which is designed for stitching together different histories. There's some explanation here: * *What are .git/info/grafts for? ... and a nice tutorial here: * *http://sitaramc.github.com/concepts/grafting.html As those links suggest, you will probably want to use git filter-branch after adding the graft to rewrite your history, enabling other people to clone the complete history, including everything grafted in. (Although this should have the usual warnings about rewriting history.) A: One option here would be to rebase your work on-top of the current HEAD of the repository you branched from. What git rebase does there is wind back your branch to the common ancestor, then fast-forward all the new commits on the branch you are rebasing against, and lastly, tries to apply each of your commits in turn until you have a linear history including everything from the other branch, followed by all of your own work. Warning: never rebase branches where you have shared your state with someone else or another branch and you care about maintaining that relationship: this essentially rewrites history and will create entirely new commits with no relationship to your existing ones. Further information about rebasing can be found here: I recommend reading that page before you go on. With that caveat in mind you would do the following: git remote add source git://host.that.has.source/repo git fetch source git rebase source/master I've made a few assumptions here. * *That you have access to the original repository: you need to import all the commits since you made your original branch for this to work. *That you want to keep in step with the master branch of that repository: if you want to use a different branch replace the word "master" with the name of the remote branch you want to rebase against (git branch -rto see them all). Note: when you run the rebase command, you may be faced with situations where you have to resolve conflicts: do so in the normal way. In the case of the commit you mentioned in the comments which was previously cherry-picked or merged and is causing conflicts, it should be safe to assume that the upstream copy of that code trumps your version: when git tries to apply that commit and encounters errors, you can just git reset --hard HEAD and then git rebase --continue to use their version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Cant insert data into second database connection See the code below, there are two databases connections. First it get the data from first connection and then insert into second database connection but it will not insert - I can an error saying Unknown column 'fullname' in 'field list' When I tried SQL query manually in phpMyAdmin and it work fine... $db_new = mysql_connect('localhost', 'root', 'password'); if (!mysql_select_db("menu_new", $db_new)) { die("Cant connect menu_new DATABASE"); } $db_old = mysql_connect('localhost', 'root', 'password'); if (!mysql_select_db("old_menu", $db_old)) { die("Cant connect old_menu DATABASE"); } $SQL_old = "SELECT * FROM old_table"; $q = mysql_query($SQL_old, $db_old); while ($row = mysql_fetch_assoc($q)) { $name = $row['name']; $SQL = "INSERT INTO tbl_name (fullname) values ('$name')"; //Problem Here - It wont insert into second database mysql_query($SQL, $db_new) or die(mysql_error($db_new)); } A: Nothing is strange in this behavior. Just add the $link parameter on your mysql_connect calls, and set it to true. By default it is False and it means that reusing this function with the same parameters, which is what you're doing as the db name is not on your mysql-connect, will reuse existing connexion with same parameters. So you have two variables but only one connexion. It means you're simply moving the db used in this connexion. Prefixing with the db name fixed the problem as MySQL allow inter-base manipulations from the same connexion if it's on the same db server. A: Thanks @Konerak for suggestion and that does work! To Insert/Select data from Database connection, you will have to include database name before the table name. For Example From: mysql_query("INSERT into tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new)); To: mysql_query("INSERT into menu_new.tbl_name (fullname) values ('1')", $db_new) or die(mysql_error($db_new)); That is really odd though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SocketException when creating new InternetExplorerDriver with Selenium 2.7.0 I'm trying to create a new instance of the Selenium InternetExplorerDriver to run a simple test and I'm receiving the following exception message: SocketException occurred No connection could be made because the target machine actively refused it ::1:56335 What exactly is it trying to connect to at this point? I've tried setting proxy settings for the driver with the following code but still receive the same error: var proxy = new Proxy { ProxyAutoConfigUrl = "http://myworkproxy.removed.com:1234" }; var capabilities = DesiredCapabilities.InternetExplorer(); capabilities.SetCapability(CapabilityType.Proxy, proxy); driver = new InternetExplorerDriver(capabilities); I've had a search but can't find much documentation for the latest version of Selenium. Any suggestions? A: If you are using the latest version of Selenium (selenium-webdriver), then the SocketException occurred, because your code cannot connect to the Selenium Server on the default port (I believe 4444). This might be because you haven't launched the selenium server (comes as a jar file - see the Selenium home page) or there might be another application that is using the same port that you are trying to connect to.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557881", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how can i get the same effect comes by "ctrl + k" in stackoverflow question, in my html code? see by writting some code here we select that code & press ctrl + K and that code now prints in something different format. printf("this is code"); see now i copy uper sentences code & paste it below in ctrl+ k mode printf("this is code"); okey so now i want to know how can i get same effect in my wordpress-blog's post? any plugin or any technique or any html tag ? A: It looks like you are looking for a WP plugin which can handle source code syntax highlighting. Here are some examples which may work for you: http://wordpress.org/extend/plugins/wp-syntax/screenshots/ http://wordpress.org/extend/plugins/google-syntax-highlighter/screenshots/ A: You'll want a code highlighter. For WordPress, Geshi-backed highlighters are pretty common. http://wordpress.org/extend/plugins/tags/geshi A: You'll be looking for the <pre> tag.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: rtl issue on ie I am in development of hebrew website (with rtl direction of course). My page is working fine on firefox and chrome also safari. But i have no luck, my page is disorder when opening that on ie. It is very helpful if any of you can give me suggestion or any other information to help me out from this issue. A: Maybe you are using IE6 ? This great tool may help you ... http://ipinfo.info/netrenderer/ Online tool allowing to verify how websites appear in Microsoft Internet Explorer 5.5, 6 and 7.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XmlSerializer with Specified pattern not working We're trying to consume a web service (Soap) and have generated an adapter for the schema using SvcUtil.exe. We have a field recurrenceCount which should not be provided unless it has a value and so we have added a property recurrenceCountSpecified as according to MSDN . Even though recurrenceCountSpecified is false, the field recurrenceCount property is still specified in the outgoing xml. What are we doing wrong ? Adapter code : [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel","3.0.0.0")] [System.ServiceModel.ServiceContractAttribute(Namespace="http://sas.elluminate.com/", ConfigurationName ="SASDefaultAdapterV2Port")] public interface SASDefaultAdapterV2Port { [System.ServiceModel.OperationContractAttribute(Action="http://sas.elluminate.com/setSession",ReplyAction = "*")] [System.ServiceModel.FaultContractAttribute(typeof(sas.elluminate.com.ErrorResponse), Action = "http://sas.elluminate.com/setSession", Name="ErrorResponse")] [System.ServiceModel.XmlSerializerFormatAttribute()] sessionResponseCollection setSession(setSessionRequest request); } The modified class is : [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel","3.0.0.0")] [System.ServiceModel.MessageContractAttribute(WrapperName="setSession", WrapperNamespace = "http://sas.elluminate.com/",IsWrapped = true)] public partial class setSessionRequest { [System.Xml.Serialization.XmlIgnoreAttribute()] public bool recurrenceCountSpecified; [System.ServiceModel.MessageBodyMemberAttribute(Namespace="http://sas.elluminate.com/", Order = 19)] public int recurrenceCount; } A: The behavior you're attempting to use (xxxSpecified properties) does not apply if you're using a MessageContract. It applies only to the XmlSerializer. You have correctly specified that XmlSerializer should be used for the operation. However, because you have also specified that MessageContracts are to be used, the XmlSerializer only kicks in at the next level of serialization - i.e. when serializing each message member.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Discover mobile devices using wifi I'm doing some work for my theses in networking, and have stumbled into a little problem. One of the first steps in the work I must do consists on having a computer working as an AP (I am using hostapd for this) and with it, detect all the devices in the room which currently have wifi turned on (do not need to be associated with any AP). I have found a thread that pretty much asks the same ( discover mobil devices using wifi ), and I understand the answers that were given, but they don't give any hint as to how this can be done. The post ends saying that the person was able to do this using Kismet, however I can only seem to use Kismet to discover clients already associated with an AP. Can someone point me in the right direction here please? If not using Kismet, then maybe suggest a different tool that works with Ubuntu. Ps. I will need to run a continuous scan of the "room" to find any new devices and then send this information to an event manager written in Java. A: I guess you could have a WiFi card, in monitor mode, scanning every channel for beacons. On Linux, aircrack-ng is the tool suite you are looking for. airodump-ng is the tool that shows you a list of devices present around your location. It is designed to display first the hotspots with the potentials clients, but also shows all the devices that are connected to an AP or trying to probe to an AP. However, you won't be able to scan devices having their WiFi connection turned down. I'm not sure about devices not associated to an AP, my guess is you will be able to detect them if they send beacons one way or another (for example, to detect WiFi hotspots). If you need this in Java, you can write a wrapper to airodump-ng, or you can launch airodump-ng as a service outputing to a file and read this file from a Java app. No concrete answer I'm afraid, but I hope these will help you figure a way to solve your problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557889", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Right click on a menu item and show options I have menu ServerList, I am adding the menuItems dynamically using C# code. It reads the servers list from file and populate the menu items. I have added the right click options for each server. Edit & Delete. All this is working fine. the problem is how do I read actual server name when Edit/Detele is clicked. Here is the code public MainWindow() { InitializeComponent(); LoadMenuItems(); } //Currently static values, but reads from file. later private void LoadMenuItems() { MenuItem item2 = new MenuItem(); item2.Header = "Server1"; AddContextMenu(item2); MenuItem item3 = new MenuItem(); item3.Header = "Server2"; AddContextMenu(item3); ActualMenu.Items.Add(item2); ActualMenu.Items.Add(item3); } private void AddContextMenu(MenuItem item) { MenuItem item1 = new MenuItem(); item1.Header = "Edit"; item1.Click += item_Click; MenuItem item2 = new MenuItem(); item2.Header = "Detlete"; item2.Click += item_Click; ContextMenu menu = new ContextMenu(); menu.Items.Add(item1); menu.Items.Add(item2); item.ContextMenu = menu; } void item_Click(object sender, RoutedEventArgs e) { MenuItem item = sender as MenuItem; string header = item.Header.ToString(); } A: For this use PlacementTarget. private void AddContextMenu(MenuItem item) { MenuItem item1 = new MenuItem(); .... ContextMenu menu = new ContextMenu(); .... menu.PlacementTarget = item; /// 'Connects' context menu to source menu item. item.ContextMenu = menu; } void item_Click(object sender, RoutedEventArgs e) { MenuItem item = sender as MenuItem; string header = ((MenuItem)((ContextMenu)((MenuItem)sender).Parent).PlacementTarget).Header; } Cheers. A: By default, the Header of a MenuItem uses a TextBlock to display content. So, in this case you need to convert the Header to a TextBox, then look at the Text property. For example, void item_Click(object sender, RoutedEventArgs e){ string servername = ((sender as MenuItem).Header as TextBlock).Text; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to bind CheckBoxFor I have a collection of "permissions". Each permission would have three properties: Id, Name, and HasPermission. So as an example, consider the following object: public class AccessPerm { int PermId {get;set;} string PermName {get;set} bool HasPerm {get;set;} } public class UserProfile { Collection<AccessPerm> UserPerms {get;set;} } So I want to use the CheckBoxFor helper to create checkboxes so that one can set the user's permissions. If you check the box, then HasPerm should be true. If you uncheck it, HasPerm should be false. The problem I am having is I don't see a way to bind both the PermId and the HasPerm properties to the checkbox. I used the following code to bind the HasPerm property, but it is not useful because I don't know the PermId. <% for(int ix=0; ix< Model.UserProfile.Perms.Count; ix++) { Html.CheckBoxFor(model => model.UserProfile.Perms[ix].HasPerm); } %> This code does indeed bind HasPerm, and the value is correct. However, since I don't have the id, I can't do anything with the value. Please advise. A: You could include it as hidden field: <% for(int ix = 0; ix < Model.UserProfile.Perms.Count; ix++) { %> <%= Html.HiddenFor(model => model.UserProfile.Perms[ix].PermId) %> <%= Html.CheckBoxFor(model => model.UserProfile.Perms[ix].HasPerm) %> <% } %> This way you will get the same list in your POST controller action containing the id and whether it is selected. A: You might try building a SelectList object and bind it to checkbox list.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Overriding default template for specific nodes in a databound (XML/XPath) TreeView TL;DR up front: I would like to use a "default" HierarchicalDataTemplate for all but a specific few nodes in a WPF TreeView. These nodes come from an XMLDocument and are not fully known until runtime. Is there a way to do this? At runtime, I am analyzing specific parts of a system, and building an XML document that I'm then binding to a TreeView like so: MyTree.DataContext = MyXMLDocument; This is my WPF declaration of the TreeView: <TreeView x:Name="MyTree" ItemsSource="{Binding Mode=OneWay, XPath=/Analysis}" ItemTemplate="{StaticResource GenericElementWithChildren}"/> The template starts like this... <HierarchicalDataTemplate x:Key="GenericElementWithChildren" ItemsSource="{Binding XPath=child::node()}"> So for example, I might have some long XML document about different aspects of the analysis I just ran and I'd like some particular element like "Disk" or "Proprietary Foo Service" to have a special template because it should be displayed nicely, while everything else just gets a generic template. I've thought about using a DataTemplateSelector but it seems like there must be a better way. I'm not even sure how I'd do that for XML. Do any of you smarter folks have any wisdom to impart, or am I stuck figuring out how to write a DataTemplateSelector against XML? A: DataTemplate and HierarchicalDataTemplate also have a DataType property. When you remove the x:Key and supply a DataType, these Templates are implicit. So you can define your different templates as implicit and they will be used automatically, as long as you don't supply a ItemTemplate or ItemTemplateSelector on the inital TreeView. <HierachicalDataTemplate DataType="{x:Type ProprietaryFooService}"> Personally i try to avoid that, because this also means that other controls that can show your data are using these Templates aswell. Imo the best would be to use a DataTemplateSelector, especially when you deal with the same types that you need to show in different ways. Edit: Sorry i missed that you are using Xpath. I guess it will not work there. I will leave this answer here, but can't guarantee that it suits your needs. Maybe it helps in another way anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Visual Studio add in to provide solution statistics Years ago I used to have a visual studio plug in (2003 era) which produced a nice little report showing number of lines per code by solution, then project then class, etc. I've been looking for something similar ever since with no joy. Can anyone recommend one? Thanks A: it's not exactly what you want but doesn't do Code Metrics the job? And if you want to extract them there are Powertools for it. PS: I think you need professional or above for this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fluent Automapper issue with tag creation POST EDITED - see edit below I have a query about the FLuent Automapping which is used as part of the SHarp Architecture. Running one of the tests cases will generate a schema which I can use to create tables in my DB. I'm developing a site with Posts, and Tags associated with these posts. I want a tag to be able to be associated with more than one post, and for each post to have 0 or more tags. I wanting to achieve a DB schema of: Post {Id, Title, SubmitTime, Content} Tag {Id, Name} PostTag {PostId, TagId} Instead, I'm getting: Post {Id, Title, SubmitTime, Content} Tag {Id, Name, PostID (FK)} I'm using sharp architecture, and may classes look as follows (more or less): public class Post : Entity { [DomainSignature] private DateTime _submittime; [DomainSignature] private String _posttitle; private IList<Tag> _taglist; private String _content; public Post() { } public Post(String postTitle) { _submittime = DateTime.Now; _posttitle = postTitle; this._taglist = new List<Tag>(); } public virtual DateTime SubmitTime { get { return _submittime; } private set { _submittime = value; } } public virtual string PostTitle { get { return _posttitle; } private set { _posttitle = value; } } public virtual string Content { get { return _content; } set { _content = value; } } public virtual IList<Tag> TagList { get { return _taglist; } set { _taglist = value; } } public class Tag : Entity { [DomainSignature] private String _name; public Tag() { } public Tag(String name) { this._name = name; } public virtual String Name { get { return _name; } private set { _name = value; } } public virtual void EditTagName(String name) { this.Name = name; } } I can see why it's gone for the DB schema set up that it has, as there will be times when an object can only exist as part of another. But a Tag can exist separately. How would I go about achieving this? I'm quite new to MVC, Nhibernate, and SHarp architecture, etc, so any help would be much appreciated! EDIT* OK, I have now adjusted my classes slightly. My issue was that I was expecting the intermediate table to be inferred. Instead, I realise that I have to create it. So I now have (I've simplified the classes a bit for readability's sake.: class Post : Entity { [DomainSignature] String Title [DomainSignature] DateTime SubmitTime IList<PostTag> tagList } class Tag : Entity { [DomainSignature] string name } class PostTag : Entity { [DomainSignature] Post post [DomainSignature] Tag tag } This gives me the schema for the intermediate entity along with the usual Post and Tag tables: PostTag{id, name, PostId(FK)} The problem with the above is that it still does not include The foreign key for Tag. Also, should it really have an ID column, as it is a relational table? I would think that it should really be a composite key consisting of the PK from both Post and Tag tables. I'm sure that by adding to the Tag class IList<PostTag> postList I will get another FK added to the PostTag schema, but I don't want to add the above, as the postList could be huge. I don't need it every time I bring a post into the system. I would have a separate query to calculate that sort of info. Can anyone help me solve this last part? Thanks for your time. A: Ok, I'd been led to believe that modelling the composite class in the domain was the way forward, but I finally come across a bit of automapper override code which creates the composite table without me needing to create the class for it, which was what I was expecting in the first place: public class PostMappingOverride : IAutoMappingOverride { public void Override(AutoMapping map) { map.HasManyToMany(e => e.TagList) .Inverse() .Cascade.SaveUpdate(); } } This will now give me my schema (following schema non simplified): create table Posts ( Id INT not null, PublishTime DATETIME null, SubmitTime DATETIME null, PostTitle NVARCHAR(255) null, Content NVARCHAR(255) null, primary key (Id) ) create table Posts_Tags ( PostFk INT not null, TagFk INT not null ) create table Tags ( Id INT not null, Name NVARCHAR(255) null, primary key (Id) ) alter table Posts_Tags add constraint FK864F92C27E2C4FCD foreign key (TagFk) references Tags alter table Posts_Tags add constraint FK864F92C2EC575AE6 foreign key (PostFk) references Posts I think the thrower is that I've been looking for a one-to-many relationship, which it is, but it is called HasManytoMAny here...
{ "language": "en", "url": "https://stackoverflow.com/questions/7557901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3 Active Admin add preset value to new record I have tried to do it from the controller and from the active admin override controller and I can't make it work. A user creates a website. current_user has an id attribute website has an user_id attribute So when I create a new website I want to add the current_user.id into website.user_id. I can't. Anybody know how? Right now I need it on the new/create actions but I'll probably need this on the edit/update actions too. A: You need to add a 'new' method to the controller. The 'new' method creates an empty website object that will be passed to the form. The default 'new' method just creates an empty @website object. Your 'new' method should create the empty object, and then initialize the value of user to current user: ActiveAdmin.register Website do controller do # Custom new method def new @website = Website.new @website.user = current_user #set any other values you might want to initialize end end A: This seems to work for me: ActiveAdmin.register Website do controller do # Do some custom stuff on GET /admin/websites/*/edit def edit super do |format| # Do what you want here ... @website.user = current_user end end end end You should be able to override other controller actions in the same way. A: ActiveAdmin.register Model do # also look in to before_create if hidden on form before_build do |record| record.user = current_user end end See https://github.com/activeadmin/activeadmin/blob/master/lib/active_admin/resource_dsl.rb#L156
{ "language": "en", "url": "https://stackoverflow.com/questions/7557914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Eclipse svn code changes notification plugin I was wondering - is there a plugin for eclipse that will notify all the contributors to a certain svn project that someone has commited in trunk with some message containing the names of the changed classes and can afterwards show a diff between the changed/unchanged versions of the classes commited. Thanks. A: If the user has these projects checked out and are using a plugin like Subclipse, they can just use the Team > Synchronize option. This can be configured to refresh automatically every hour or whatever interval is desired. The Synchronize view lets you examine the changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Setting relative Tex-Master file in Latex I use Aquamacs and TeX Live 2009 to edit my LaTeX files. As my publications tend to get quite big, I want to structure the source folder containing all my LaTeX files. Like e.g. * *[bib] *[images] *[chapters] * *chapter1.tex *chapter2.tex *main.tex One can define the %%% TeX-master: "main" local variable at the end of each "sub" file to define a master file that contains all headers etc. That works fine if the subfiles are in the same directory as the main file. If I try to define the main file here (e.g. main.tex in chapter1.tex), LaTeX cannot find the specified file. What can I do in this case? A: In Aquamacs' menu bar go to Latex / Multifile/Parsing / Reset Buffer or Shortcut ^C ^N. When specifying %%% TeX-master: "../main" in one of the chapters in the subfolders, the main tex file is correctly compiled! A: Just an idea (not tested): %%% TeX-master: "../main" .. is the usual Unix shortcut for one directory level above. I don't know if this works for the TeX-master variable of AUCTeX, but it is worth a try. A: The main latex file which contains all the headers and gets compile can include all the chapter files via: [...] \input{chapters/chapter1.tex} \input{chapters/chapter2.tex} \input{chapters/chapterTitleOfChapter.tex} [...] You do not need to have each chapter include the main file. Or am I missing something you are doing?
{ "language": "en", "url": "https://stackoverflow.com/questions/7557931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: I want to strip off everything but numbers, $, comma(,) I want to strip off everything but numbers, $, comma(,). this only strip letters string Cadena; Cadena = tbpatronpos6.Text; Cadena = Regex.Replace(Cadena, "([^0-9]|\\$|,)", ""); tbpatronpos6.Text = Cadena; Why doesn't my regex work, and how can I fix it? A: you want something like this? [^\\d\\$,] A: I suspect this is what you want: using System; using System.Text.RegularExpressions; class Test { static void Main(string[] args) { string original = @"abc%^&123$\|a,sd"; string replaced = Regex.Replace(original, @"[^0-9$,]", ""); Console.WriteLine(replaced); // Prints 123$, } } The problem was your use of the alternation operator, basically - you just want the set negation for all of (digits, comma, dollar). Note that you don't need to escape the dollar within a character group.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Network Simulation Cradle with Linux Stack 2.6.35 I am struggling to integrate the network stack of Linux Kernel 2.6.35 with the Network Simulation Cradle (http://www.wand.net.nz/~stj2/nsc/). Has anyone done it before ? If yes please reply. I am getting an error saying : fatal error: when writing output to : Broken pipe. Well, I cannot proceed further explaining what I have done till now, as that would make no sense if no one here has worked with this Network Simulation Cradle. So, if anyone has worked with this, please reply. Regards A: You're probably better asking off on the ns-3 mailing list, or emailing the author of the NSC directly. Either way, you'll need to include more information in your question!
{ "language": "en", "url": "https://stackoverflow.com/questions/7557940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error Writing to Memory of Particular Data Member Okay, I have a struct, TextBlock, that simulates moving blocks of text around the screen. Here's the header: struct TextBlock { RECT textArea; RECT rectArea; double whatBlock; double x; double y; double angle; double speed; double width; double height; char *word; bool stuck; }; When it's like this, everything works perfectly fine. The problem comes when I add another member that I need. The way it works is that I have two arrays of TextBlocks. The first is for moving ones, the second is for ones that don't move, signifying where the moving ones need to go. The words are all randomized from a sentence to a jumble, so this data member will be set (commented out) to the index of which static block belongs to the moving one so I know when it's in the right place. int whatBlock; After creating this, I go through all of the created objects and set tb[i][j].whatBlock = 0; //same area as other data members being set, moving text stb[i][j].whatBlock = 0; //static text block When I try to run this, without doing anything else to the data member, it comes up with an error: The instruction at [address] referenced memory at [different address]. The memory could not be "written". Note that if I don't try to modify it, and just create the data member, it works. At this point of almost being done and having tons of these kinds of problems, I'm getting a bit fed up with this program >.> Any help at all on this would be greatly appreciated. EDIT: This issue is now fixed. I replied to the accepted answer with the explanation, but it poses another problem, even if it doesn't affect this program. A: * *Force a rebuild of everything. You may have an object file that is out-of-date with respect to the header file that defines TextBlock *If that doesn't fix it, run your program under a debugger and see what the faulting instruction is. Either that will allow you to fix the program, or you can ask again with mroe informatin. A: Without you posting more code, I can only tell that you likely have a memory corruption bug in your program - i.e. you are reading or writing beyond the end of allocated memory. If you post more code, I'll edit this answer accordingly. A: I can't really give advices since we cannot access the complete source code. Anyway, I can suggest you that it may be not in the struct TextBlock where really hides the bug. For instance, every access to TextBlock's member means that you are accessing to this hidden variable. If this pointer is corrupted, you may experience problem where you don't expect it, leading you to search in the wrong places.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent the extra view displaying an access code when using Google OAuth 2.0 I followed http://googlemac.blogspot.com/2011/05/ios-and-mac-sign-in-controllers.html to allow users to use Google to login to an iPhone app. After I tap "Allow access" button I get an extra screen that says, "Please copy this code, switch to your application and paste it there: (code in a textbox)." This is what I have: - (IBAction)googleLoginTapped:(UIButton *)sender { [self loginToGoogle]; } - (void)loginToGoogle { // For Google APIs, the scope strings are available // in the service constant header files. NSString *scope =@"https://www.googleapis.com/auth/userinfo.profile"; // Typically, applications will hardcode the client ID and client secret // strings into the source code; they should not be user-editable or visible. // But for this sample code, they are editable. NSString *clientID = @"my clientID"; NSString *clientSecret = @"my clientSecret"; // Display the autentication view. SEL finishedSel = @selector(viewController:finishedWithAuth:error:); GTMOAuth2ViewControllerTouch *viewController; viewController = [GTMOAuth2ViewControllerTouch controllerWithScope:scope clientID:clientID clientSecret:clientSecret keychainItemName:nil delegate:self finishedSelector:finishedSel]; // For this sample, we'll force English as the display language. NSDictionary *params = [NSDictionary dictionaryWithObject:@"en" forKey:@"hl"]; viewController.signIn.additionalAuthorizationParameters = params; // Optional: display some html briefly before the sign-in page loads NSString *html = @"<html><body bgcolor=silver><div align=center>Loading sign-in page...</div></body></html>"; viewController.initialHTMLString = html; viewController.signIn.shouldFetchGoogleUserProfile = YES; [self presentModalViewController:viewController animated:YES]; } - (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error { if (error != nil) { // Authentication failed (perhaps the user denied please see this link it is to good https://developers.google.com/accounts/docs/OAuth2InstalledApp A: I tried this approach, and work fine, put this in your webViewDidFinishLoad method : if ([webView.request.URL.absoluteString rangeOfString:@"https://accounts.google.com/o/oauth2/approval?"].location != NSNotFound) { webView.hidden=YES; } A: I have found the answer. Initially I was using the Client ID for an installed application. This did not give the option to set up the Redirect URI. It gave a default Redirect URI of urn:ietf:wg:oauth:2.0:oob http://localhost. So when I sent a request for authentication using this code: viewController = [GTMOAuth2ViewControllerTouch controllerWithScope:scope clientID:clientID clientSecret:clientSecret keychainItemName:nil delegate:self finishedSelector:finishedSel]; It returned an success code that is then used to authorize native applications. Please reffer here for more on returned codes or tokens. To fix my issue I went ahead and used a Client ID for web application. This allowed me to explicitly set a Redirect URI and also allowed me to set the response_type to token instead of code here: https://accounts.google.com/o/oauth2/auth? client_id=21302922996.apps.googleusercontent.com& redirect_uri=https://www.example.com/back& scope=https://www.google.com/m8/feeds/& response_type=**token** So when I am authenticated and the redirect_uri is served back from the server it comes with an "access_tocken" appended as a query string like this: https://www.example.com/back?access_token=returned_access_tocken Now you can use a regular expression code: -(void)checkForAccessToken:(NSString *)urlString { NSError *error; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"access_token=(.*)&" options:0 error:&error]; if (regex != nil) { NSTextCheckingResult *firstMatch = [regex firstMatchInString:urlString options:0 range:NSMakeRange(0, [urlString length])]; if (firstMatch) { NSRange accessTokenRange = [firstMatch rangeAtIndex:1]; NSString *accessToken = [urlString substringWithRange:accessTokenRange]; accessToken = [accessToken stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [_delegate accessTokenFoundGoogle:accessToken]; accessTokenFound = YES; } } } to pluck the access_code and use it for your authorization request here: "https://www.googleapis.com/oauth2/v1/userinfo?oauth_token=put_your_accesstoken_here" to send a request for authorization Then you can just send your request and get back in this case the user's profile info in JSON format. You can refer to this question and answer for using Facebook's graph api to login users. Then just modify the code to work with the new Google OAuth 2.0 using the suggestions and request urls I have included here. Just a suggestion to speed things for you when converting the code for Facebook, create a new init method like this: - (id)initWithDelegate:(id<GoogleLoginDialogDelegate>)delegate; - (id)initWithDelegate:(id<GoogleLoginDialogDelegate>)delegate { if ((self = [super initWithNibName:@"GoogleLoginDialog" bundle:[NSBundle mainBundle]])) { self.delegate = delegate; } return self; } So that you can easly work with the delegate methods from your Google login dialog. If you follow the Facebook example carefully, you should have Google login with OAuth working great! A: It turns out this is pretty straightforward. In the login callback, simply dismiss and remove viewController from the parent view controller. - (void)viewController:(UIViewController *)viewController finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error { if (error == nil) { // Get rid of the login view. // self.parentViewController was saved somewhere else and is the parent // view controller of the view controller that shows the google login view. [self.parentViewController dismissViewControllerAnimated:NO completion:nil]; [viewController removeFromParentViewController]; // Tell the delegate that the user successfully logged in ... } else { // Error handling code ... } } A: I fixed this by nesting the view controller inside of a UINavigationController. No idea why did that did the trick, but it did. So instead of [self presentModalViewController:viewController animated:YES]; ... use UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; [self presentModalViewController:navigationController animated:YES]; A: When using gtm-oauth2 to sign in to Google services, be sure the Google API Console project registration shows in the API Access section that the Client ID is issued for an installed application. This is described in the gtm-oauth2 documentation. A: while creating Client ID , Choose web Application instead of installed application , this will solve your problem . happy coding :) A: I tried this trick and it gets work... replace the webview shouldStartLoadWithRequest with this below method in GTMOAuth2ViewControllerTouch.h. It will not show the authentication code page. *- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { if (!hasDoneFinalRedirect_) { hasDoneFinalRedirect_ = [signIn_ requestRedirectedToRequest:request]; if ([request.URL.absoluteString rangeOfString:@"https://accounts.google.com/o/oauth2/approval?"].location != NSNotFound) { self.redirectView.frame=[UIScreen mainScreen].bounds; //webView.frame=[UIScreen mainScreen].bounds; [self.activityView startAnimating]; [webView addSubview:self.redirectView]; return YES; } else if(hasDoneFinalRedirect_) { // signIn has told the view to close return NO; } } return YES; }* in this I am adding my own custom view (redirectView) to this authentication page by checking this approval url https://accounts.google.com/o/oauth2/approval? and You should also add activityView in xib of GTMOAuth2ViewControllerTouch to show the loader while redirecting back to the application. A: After at least 20 hours of configuring things, I finally got this running. I also previously imported my swift file into my GTMOAuth2ViewControllerTouch.m file. Not sure if that impacted it but I added: #import "myBundleId-Swift.h" Then, in the viewController.swift file I needed to add the final 2 lines: // Handle completion of the authorization process, and updates the Drive service // with the new credentials. func viewController(viewController: GTMOAuth2ViewControllerTouch , finishedWithAuth authResult: GTMOAuth2Authentication, error:NSError? ) { if let error = error { self.showAlert("Authentication Error", message:error.localizedDescription) self.driveService.authorizer = nil } else { print("Authentication success") self.driveService.authorizer = authResult //This where we need to get rid of the copy the code screen: self.parentViewController?.dismissViewControllerAnimated(false, completion:nil) viewController.removeFromParentViewController() } } That got rid of the copy this code screen.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: My tab menus exit the page width So I'm editting the CSS and the tab menu has a whitespace: nowrap property, which means it doesn't overlap but it ends up exiting the page. Setting the width of the tab menu itself does nothing even with !important and hierarchy CSS. Looks like this http://i.imgur.com/yxblJ.jpg When I do whitespace: pre, or any of the others they end up overlapping. A: It looks like you are using a floated list. Can't be certain without looking a code, but you may need to either extend the width of the containing div or clear the float.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Module import Error Python I just installed lxml for parsing xml file in python. I am using TextMate as an IDE. Problem is that when I try to import lxml (from lxml import entree) then I get ImportError:'No module named lxml' But when I use Terminal then everything is fine Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from lxml import etree >>> root=etree.element("root") >>> root=etree.Element("root") >>> print (root.tag) root >>> root.append(etree.Element("child1")) >>> child2 = etree.SubElement(root, "child2") >>> child3 = etree.SubElement(root, "child3") >>> print (etree.tostring(root,pretty_print=True)) <root> <child1/> <child2/> <child3/> </root> It's pretty weird. Does it have something to do with TextMate? Suggestion Please! A: This most probably means that you have more than one python installation on your system and that TextMate and the Terminal using different ones by default. One workaround: In your python file, you can specify an interpreter directive to point to the python installation (and executable) of your choice: #!/usr/local/bin/python # Even thought standard python is in /usr/bin/python, here we want another ... A: You need to define the shell variables in TextMate's settings, specifically 'TM_PYTHON' needs to point to your Python binary. To find which Python your using, in a terminal you could type 'which python' A: It's likely that TextMate is using a different PYTHONPATH than your terminal. I'm not a TextMate user so I can't help you there, but it should point you in the right direction. A: You might be be running a different version of Python from TextMate. I had a similar issue with RedHat having 2 versions of Python. I had installed the module to one, but was trying to execute with another.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF Authentication with Credentials in Message's Body I am developing a webservice which must conform to a WSDL specification required by a given application, and in which every SOAP request carries a username and password in clear, plain text (I know that's a pretty bad idea, but that was not my design choice). Now I must authenticate every call to my service's methods by checking those credentials against a database of valid credentials. I have heard about WCF's UserNamePasswordValidator but, from what I understood, that applies only if the credentials are passed through the SOAP headers, which they are not. What are my options here? A: You know this a bad idea, so I'm not going to question your setup :-) If you have username and password send in clear text over the wire inside your soap body, simple use the info to validate the against your database instance manually. Take the username and password and validate that (or its MD5 hashes) with an SQL query, returning a row only when the values are found in the database. When the row returns, you know the user is authenticated. A: What are my options here? What you need to do in this case is implement a Custom Authorization Manager for your service. This is not too difficult to do as I have done it several times before. In a nutshell, you configure your service to point to a newly overridden method named CheckAccessCore where you preform the authorization logic. You should be able to inspect the context and the message body to get any credentials you need. The one thing to understand is there is some performance implications to inspecting the message body at this point, but if you have no choice at least a working solution will suffice. This all happens prior to the actual method being called getting executed which is efficient because the method is never called if they are not authorized. So here might be a typical configuration (some other configuration left out for brevity): <behaviors> <serviceBehaviors> <behavior name="MySvcBehavior"> <serviceAuthorization serviceAuthorizationManagerType="MyWCFService.CustomAuthorizationManager, MyWCFService" /> </behavior> </serviceBehaviors> <behaviors> In your code for the service you might have something similar to the following, or use your own needs to inspect the message body: public class CustomAuthorizationManager : ServiceAuthorizationManager { protected override bool CheckAccessCore(OperationContext operationContext) { IIdentity primaryIdentity = operationContext.ServiceSecurityContext.PrimaryIdentity; if (primaryIdentity.Name == "user1") { return true; } else { return false; } } } Here were some notes in particular from my code comprised from the MSDN: The Identity Model infrastructure in Windows Communication Foundation (WCF) supports an extensible claims-based authorization model. Claims are extracted from tokens and optionally processed by custom authorization policies and then placed into an AuthorizationContext. An authorization manager examines the claims in the AuthorizationContext to make authorization decisions. By default, authorization decisions are made by the ServiceAuthorizationManager class; however these decisions can be overridden by creating a custom authorization manager. To create a custom authorization manager, create a class that derives from ServiceAuthorizationManager (this class) and implement CheckAccessCore method (done in this class). Authorization decisions are made in the CheckAccessCore method, which returns 'true' when access is granted and 'false' when access is denied. Here are (2) additional links that exampnd on this. The 1st is a MSDN link that uses claims within the method. Just remember you can do anything you require within CheckAccessCore. It just requires by the end returning true or false. The second link is one from my blog where I have a full implementation but using Windows Authentication. Once again, the details for you will be to inspect the message body to get the needed details within that CheckAccessCore method. How to: Create a Custom Authorization Manager for a Service: http://msdn.microsoft.com/en-us/library/ms731774.aspx How To: Create an ASP.NET style Windows Authentication Policy for WCF Services: http://allen-conway-dotnet.blogspot.com/2010/01/how-to-create-aspnet-windows.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7557953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Strategy for implementing multiple view controllers My application is for studying. It will have three screens, one for studying (reading), one for reviewing, and one which acts as the main menu (for managing documents and selecting study or review). The main menu will be the first screen when the app is loaded. I am trying to decide on the best approach with regards to what view controllers and views I need. Approach A: (4 x View Controllers - root, menu, study, review) This approach has a root view controller with no on-screen controls. It will always contain one of the other view controllers as a subview. For some reason I am attracted to this approach but I have seen no other examples of this so maybe I am being stupid. I am wondering if there is a reason why this is inherently wrong. Approach B: (3 x View controllers - root (menu), study, review) In this approach the menu IS the root controller and the other controllers load in subviews of the menu. I think this is more of a standard way of doing things. I would be grateful to hear any thoughts on which approach is best. I am a newbie to software development. I have worked through a number of books on iOS software development and messed around for a bit and now I am starting my first app for iPad. A: Whenever you're determining how to layout your views and controllers, they're very often based on the application flow (from an end user's standpoint). So from your original question I'm not sure I exactly understand the flow- is the user forced to start at the main menu, and then from there is able to toggle between two mutually exclusive views (study & review)? If that's the case, I would recommend using a tab bar controller for the 'Study' and 'Review' views, as it allows for saving states of the views and switching between them without you having to do any extra work (from both of the approaches you described it sounds like you'd largely be recreating this behavior yourself). Then, for the main menu (which I assume is displayed when the app first starts?) You can simply open it modally (note you don't have to animate the opening, so it can instantly appear instead of sliding up from the bottom, and the user will never be the wiser). Once the user selects what they need to select in the main menu, dismiss the modal view and you're ready to go with your 2-tab controller.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Massive performance degradation rendering menus with submenus Whenever I render a menu item, for each of the menu item I found from the database, I use it to check its sub-menus. My Controller rendering the menu item and recursive function to detect its sub-menus are as follows public function renderAction() { $menu = $this -> _request -> getParam('menu'); $itemArray = $this -> getSubItems($menu); $container = new Zend_Navigation($itemArray); $this -> view -> navigation() -> setContainer($container); } private function getSubItems($menu, $parent = 0) { $mapperMenuItem = new Apanel_Model_Mapper_MenuItem(); $menuItems = $mapperMenuItem -> getItemsByMenu($menu, $parent); if(count($menuItems) > 0) { $itemArray = array(); foreach($menuItems as $item) { $label = $item -> label; $uri = $this -> getSubItemUrl($item); $subItems = $this -> getSubItems($menu, $item -> id); if(count($subItems)) { $tArray['pages'] = $subItems; } $tArray['label'] = $label; $tArray['uri'] = $uri; $itemArray[] = $tArray; unset($tArray); } if(count($itemArray)) { return $itemArray; } else { return null; } } else { return null; } } private function getSubItemUrl($item) { if(!empty($item -> link)) { $uri = $item -> link; } else { $pageMapper = new Apanel_Model_Mapper_Page(); $details = $pageMapper -> getPageDetails($item -> page_id); $pageClass = "CMS_Content_Item_".ucwords($details['namespace']); $page = new $pageClass($item -> page_id); $title = str_replace(" ", "-", strtolower($details['name'])); $uri = $this -> view -> url(array( "namespace" => $details['namespace'], "title" => $title ),'page-view'); } return $uri; } And function getItemsByMenu in MenuItem Mapper public function getItemsByMenu($menuId, $parent = 0) { $select = $this -> getDbTable() -> select(); $select -> where("menu_id = ?", $menuId) -> where("parent = ?", $parent) -> order("position"); $items = $this -> getDbTable() -> fetchAll($select); if($items -> count() > 0) { return $items; } else { return null; } } I have about 4 different types of menu rendered in my app and I am noticing significant performance degradation in the execution. I often get Execution timeouts, the difference between the rendering time with the menus are about 35 sec and without are 22 sec approx. And this all in localhost. Is there any flaw in my recursion? What measure can I take to improve the performance of the code? A: I can't see anything in there that would explain 35 second execution time, unless you have 100,000s of items in your menus table with no indexes at all. Suggestions: * *Make sure you have an index on the menu items table on: menu_id, parent, position (that's one index on three fields, with the fields in that order. *I assume getPageDetails is doing another database query. Ideally you'd want to load these details when you load the menu items (by joining in the pages table), so you could then just pass the array of page data to getPageDetails instead of having to do an additional query per item. If that doesn't give any miraculous improvements, try enabling the DB profiler so you can see whether it's volume or speed of the database queries that is causing the issue. A: The obvious problem here is the way you fetch your menu from the database. If for each menu item you do a request to fetch it's submenus, you will quickly end with a lot of requests. An easy solution would be to implement caching, but you could first try to improve the way you query your menu. A good alternative for mapping trees, instead of referencing the parent item is to use a materialized path. This means that you store in a field a string containing the path to the current item, comma-separated. The real benefit is that you could get a whole tree in only one request using a regexp on the path field : //get the whole tree of menu 1 SELECT * FROM menuitems WHERE path REGEXP '^1' ORDER BY path; | ID | Name | Path | | 1 | Hardware | "1" | | 2 | Printers | "1,1" | | 3 | Laser printers | "1,1,1"| | 4 | Ink printers | "1,1,2"| | 5 | Screens | "1,2" | | 6 | Flat Screens | "1,2,1"| | 7 | Touch Screens | "1,2,1"| Then with a little code, like some recursive function you build your whole navigation. And consider caching this sort of things
{ "language": "en", "url": "https://stackoverflow.com/questions/7557955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to disable pruning with GWT compiler How do I disable pruning in the GWT compiler? (I'm trying to use the GWT compiler to create a Javascript version of a some game logic written in Java) Maybe pruning is not the issue? I'm testing with the following Java class and none of the fields or the string "test123" are in the generated .js file; Test1.java package com.joyplay.web.games.mmrb.shared.d1; public class Test1 { public String field1; public int field2=0; public void onModuleLoad() { field1 = "test123"; } public int doSomething1(int a){ return a+555; } public int doSomething2(){ return ++field2; } } Test1.gwt.xml <module rename-to="hello"> <inherits name="com.google.gwt.core.Core" /> <source path="d1"/> <entry-point class="com.joyplay.web.games.mmrb.shared.d1.Test1"/> </module> A: (I'm trying to use the GWT compiler to create a Javascript version of a some game logic written in Java) Have a look at the gwt-exporter project. A: GWT compiler will remove all of the code above, since it is doing nothing. You can turn off optimization using -draftCompile or -optimize 0 flags A: Mainly this depends on how you build it. For maven: <gwt.jsStyle>PRETTY</gwt.jsStyle> Or regarding to the official documentation: -style Script output style: OBF[USCATED], PRETTY, or DETAILED (defaults to OBF)
{ "language": "en", "url": "https://stackoverflow.com/questions/7557957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Explorer Panel in Java does anyone know a free windows explorer type of project written in java? Basically i just want to implement a simple windows explorer but dont want to start from scratch with all the drag and drops, icon arrangements and so on. Thanks A: See File Browser GUI. A: You can explore common navigator framework for eclipse, it would use swt, jface, draw2d. It provides with drag and drop options.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is Safari on iPad more efficient at rendering CSS gradients or images? I'm looking to use CSS gradients for an element of my web app that is drawn repetitively, as it would allow me more flexibility in dynamically changing its appearance. However, my question is whether gradients are more expensive for the browser to render than bitmap images. Or do images use more processing power? (And I'm not concerned with cross-browser compatibility- the app will only be used on the iPad) A: According to an article on the Webkit Wiki, images perform better: Sometimes it's tempting to use webkit's drawing features, like -webkit-gradient, when it's not actually necessary - maintaining images and dealing with Photoshop and drawing tools can be a hassle. However, using CSS for those tasks moves that hassle from the designer's computer to the target's CPU. Gradients, shadows, and other decorations in CSS should be used only when necessary (e.g. when the shape is dynamic based on the content) - otherwise, static images are always faster. On very low-end platforms, it's even advised to use static images for some of the text if possible. Source: https://trac.webkit.org/wiki/QtWebKitGraphics#Usestaticimages Of course, you have to balance that CPU time with the extra time it would take to load the image from the server. Also, for Internet Explorer, filters are extremely slow, especially if you have many on one page. This above answer is directly lifted from How does the performance of using background-gradients in CSS vs using images? These links can be useful read for you Browser Repaint/Reflow performance: using CSS3 Gradients vs PNG Gradients CSS gradients are faster than SVG backgrounds http://leaverou.me/2011/08/css-gradients-are-much-faster-than-svg/ Runtime Performance with CSS3 vs Images http://jacwright.com/476/runtime-performance-with-css3-vs-images/
{ "language": "en", "url": "https://stackoverflow.com/questions/7557964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: a strange use of typedef I have never see a grammar in c++ like this before: typedef int (callback)(int); what really does this really mean?I just find that if I create a statement callback a; It's effect is very very similar to a forward function declaration. below is the code I had written #include<cstdio> int callbackfunc(int i) { printf("%d\n",i); return i*i; } // you can also use typedef int (callback)(int) here! typedef int (*callback)(int); void func(callback hook) { hook(hook(3)); } int main() { func(callbackfunc); getchar(); return 0; } You can use typedef int (*callback)(int);//this is very common to use in this code,but if we change it to typedef int (callback)(int); //I'm puzzled by this ! this will also get the same result! and I know typedef int (*callback)(int) and typedef int (callback)(int) are two completely different stuff. A: It's because a function implicitly becomes a function pointer where necessary. These are identical: func(callbackfunc); func(&callbackfunc); A: Its because of the fact that in the parameter declaration, the function-type is adjusted to become a pointer-to-function-type. typedef int type(int); typedef int (*type)(int); The first typedef defines a type which is called function-type, while the second typedef defines a type which is called pointer-to-function-type. In the parameter declaration, function-type is adjusted to become a pointer to function type. §13.1/3 (C++03) says, Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5). [Example: void h(int()); void h(int (*)()); // redeclaration of h(int()) void h(int x()) { } // definition of h(int()) void h(int (*x)()) { } // ill-formed: redefinition of h(int()) ] An interesting example of the exclusive usage of function-type Suppose you've a typedef, defined as: typedef void funtype(); then you can use this to define member-function as: struct A { //member function declaration. funtype f; //equivalent to : void f(); }; void A::f() //definition { std::cout << "haha" << std::endl; } Test code: int main() { A a; a.f(); //call member function } Output: haha Online demo: http://ideone.com/hhkeK
{ "language": "en", "url": "https://stackoverflow.com/questions/7557968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: WCF 3.5 UserNameAuthentication is not working? What I'm trying to do is to secure my service. To do this I'm using UserNameAuthentication. I did the binding and everything but some reason when I start the service I don't get the Validation prompt! Validate method is not triggered! Here is my webConfig I don't know what I'm missing here! <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <services> <service behaviorConfiguration="IPhone.Service1Behavior" name="MobileService.IPhone"> <endpoint address="" binding="wsHttpBinding" contract="MobileService.IIPhone" bindingConfiguration="SafeServiceConf"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="IPhone.Service1Behavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true" /> <serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MobileService.CustomValidator, MobileService" /> </serviceCredentials> </behavior> </serviceBehaviors> </behaviors> <bindings> <wsHttpBinding> <binding name="SafeServiceConf" maxReceivedMessageSize="65536"> <readerQuotas maxStringContentLength="65536" maxArrayLength="65536" maxBytesPerRead="65536" /> <security mode="TransportWithMessageCredential"> <message clientCredentialType="UserName" /> </security> </binding> </wsHttpBinding> </bindings> Here is my code in IPhone.svc for validation I put the CustomValidator class inside the service! public class CustomValidator : UserNamePasswordValidator { public override void Validate(string userName, string password) { if (userName == "test" && password == "test") return; throw new SecurityTokenException( "Unknown Username or Password"); } } Any help? A: The validation prompt would not come from WCF. The UI is responsible for that (i.e. ASPX web form). To pass a user name and password from a client to a service, you would do something like this: proxy.ClientCredentials.UserName.UserName = "myUserName"; proxy.ClientCredentials.UserName.Password = "password";
{ "language": "en", "url": "https://stackoverflow.com/questions/7557970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to resize / rezoom webpage in ipad I have a website that uses jquery mobile for it's mobile version. I have a problem when I am changing it from portrait to landscape it zooms in correctly, but when I flip to portrait, it stays same zoom level and is wider then the view which breaks user experience. I use regular: <meta name="viewport" content="width=device-width, initial-scale=1"> from all the search I did, this should do. Unfortunately it isn't working for me. Here is my question, I can use onorientationchange event to trigger resizing of the page, I am just not sure how to go about it. Can you help please? P.S. website is here if you would like to take a peek http://tmg.dev.dakic.com/mobile Thank you, Zeljko A: Try this, I had a similar issue: $(window).bind('orientationchange', function(event) { if (window.orientation == 90 || window.orientation == -90 || window.orientation == 270) { $('meta[name="viewport"]').attr('content', 'height=device-width,width=device-height,initial-scale=1.0,maximum-scale=1.0'); $(window).resize(); $('meta[name="viewport"]').attr('content', 'height=device-width,width=device-height,initial-scale=1.0,maximum-scale=2.0'); $(window).resize(); } else { $('meta[name="viewport"]').attr('content', 'height=device-height,width=device-width,initial-scale=1.0,maximum-scale=1.0'); $(window).resize(); $('meta[name="viewport"]').attr('content', 'height=device-height,width=device-width,initial-scale=1.0,maximum-scale=2.0'); $(window).resize(); } }).trigger('orientationchange'); Try otherwise using the resize() function at certain events: $(window).resize(); A: I typically use the orientationchangeevent to add / remove CSS classes to the content, and go from there, rather than re-size the viewport. Apple provide some stand-alone example code, although from memory I think that it only includes 90° and 0° orientations—you need -90° and 180° too, as in @zyrex comment. iPhoneOrientation sample code (developer.apple.com) Update per comment: To clarify, I don't re-size HTML entities themselves, rather change the classes being used, and rely on CSS to style accordingly. To take a simplistic example, say I want to switch between two classes on the body element, depending on device orientation, I would do something like this in my Javascript: window.onorientationchange = updateOrientation; // (Might want to do this onload too) function updateOrientation(){ var o = window.orientation, body = document.querySelector('body'); switch(o){ case 0: case 180: body.className = 'portrait'; break; case 90: case -90: body.className = 'landscape'; break; } } … and something like this in the default mark-up: <body class="portrait"> <!-- stuff here --> … and then CSS which does whatever is required—e.g. a different position for the body element's background: body {background: url('images/something.png') no-repeat} body.portrait {background-position: 30% 50%} body.landscape {background-position: 10% 25%} Update #2 You may also need to tinker with the maximum-scale directive in your meta tag. Mobile Safari typically does a zoom when changing from portrait to landscape, instead of re-doing the page layout, and that may be what you're seeing. The maximum-scale value prevents this, but you should note that this also means users can't do the normal pinch-to-zoom thing. Here's how the tag would look: <meta name="viewport" content="initial-scale=1, maximum-scale=1"> Be sure to check the answers here too: How do I reset the scale/zoom of a web app on an orientation change on the iPhone? A: It seems no-one knows. From what I could see, content on the page somewhere is wider then device-width and this is where the problem originates. However, how to go about solving this is still not quite clear.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557971", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: grails - testing delete() I just wonder why one method to test delete() works as expected, but another does not? In the following test case: def cFound = new Client( ... ).save() def cFoundId = cFound.id cFound.delete() assertEquals 0, Client.count() ... assertEquals 0, Client.count() passes, but ... assertFalse Client.exists( cFound.id ) assertNull Client.get(cFoundId) ... both fail. What could be the underlying reason? Thanks in advance. A: Try to flush the context, in order to clean the caches: cFound.delete(flush: true)
{ "language": "en", "url": "https://stackoverflow.com/questions/7557975", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Excel VBA to insert line until text is matched I've got an Excel file that should have the text 'UNK' as the first 3 letters of cell A10 (I don't care what comes after the UNK). If it does NOT match this text, I need to insert a blank line at the top of the Excel file. For some reason my code is not evaluating correctly and I'm not sure why. I'm using: If Left(A10, 3) <> "UNK" Then Rows("1:1").Select Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove End If As you might be able to tell, I'm a novice with this type of code. Any help is much appreciated. A: What about this? It loops until either A10 is blank or it finds UNK. Do While Range("A10") <> "" If Left(Range("A10"), 3) <> "UNK" Then Rows("1:1").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Else Exit Do End If Loop A: I would change this to: If Left(Range("A10"), 3) <> "UIC" Then Range("A1").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove End If
{ "language": "en", "url": "https://stackoverflow.com/questions/7557976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C++ method name as template parameter How do I make the method name (here some_method) a template parameter? template<typename T> void sv_set_helper(T& d, bpn::array const& v) { to_sv(v, d.some_method()); } A: There is no such thing as a 'template identifier parameter', so you can't pass names as parameters. You could however take a member function pointer as argument: template<typename T, void (T::*SomeMethod)()> void sv_set_helper(T& d, bpn::array const& v) { to_sv(v, ( d.*SomeMethod )()); } that's assuming the function has a void return type. And you will call it like this: sv_set_helper< SomeT, &SomeT::some_method >( someT, v ); A: Here is a simple example... #include <iostream> template<typename T, typename FType> void bar(T& d, FType f) { (d.*f)(); // call member function } struct foible { void say() { std::cout << "foible::say" << std::endl; } }; int main(void) { foible f; bar(f, &foible::say); // types will be deduced automagically... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7557990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "26" }
Q: What torch.exe compares in wixpdb files for files without version I am creating patches for my installation using "purely wix" method. When I check created msp file against base msi file using Orca some of the changed files are not selected for patching. For example I have a txt file in which all 0 are replaced with 1. Old and new file are the same size but in Orca their MsiFileHash entries are completely different. I checked another txt file which is selected for patching and only difference is that it's size has changed. Is file size only rule of comparison when torch compares rows for unversioned files? I thought that torch compares database rows and if it finds some difference it selects that row for patching. Could somebody post a link or explanation of the rules torch.exe applies when comparing database rows for both versioned and unversioned files. Thanks in advance. A: This is the normal behavior. Patches include only files which have a different size or version. This is because File table has columns only for Size and Version, it doesn't contain hash or file content information. So if you want to include a file in a MSP patch, you need to change its size or increase its version.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What changes do i need to make to a canvas application to support the Oct 1 deadline I have a canvas app presently using Koala 1.1.0 and the Javascript SDK. I a have been using the OAuth authentication for months now but when I try and use "ouath:true" in my javascript to display the friend picker I am getting this error: API Error Code: 102 API Error Description: Session key invalid or no longer valid Error Message: Iframe dialogs must be called with a session key Are there extra migrations I need to turn on within the app settings to get things working? Do I need to be on SSL right now for this to work? Thanks, Mark A: You should upgrade Koala. Its Github repository suggests that version 1.2 supports OAuth 2.0 and the new cookie format.
{ "language": "en", "url": "https://stackoverflow.com/questions/7557996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing text with python and mapping to dictionary words I am trying to build a dictionary with frequent terms for my website. So basically I will retrieve a paragraph from my database and this paragraph most likely will contain terms which appear in the aforementioned dictionary. What I am looking for is a nice way (and fast) to parse the paragraph text and map the dictionary terms which might appear in that text with the dictionary entries. Is there a Python module which can assist me with this task? I am not looking for something fancy but it must be fast. Thanks A: Something like this? >>> s = "abc def, abcdef" >>> w = {"abc": "xxx", "def": "yyy"} >>> def replace(text, words): ... regex = r"\b(?:" + "|".join(re.escape(word) for word in words) + r")\b" ... reobj = re.compile(regex, re.I) ... return reobj.sub(lambda x:words[x.group(0)], text) ... >>> replace(s, w) 'xxx yyy, abcdef' Note that this only works reliably if all the dictionary's keys start and end with a letter (or a digit or underscore). Otherwise, the \b word boundaries fail to match.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558000", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: sin_port returned in getaddrinfo wrong I am writing a server-client program and in the server I use getaddrinfo and getsockname on the server to get info about the local IP addr and locally bound port number . Using this info, I start my client program and use the getaddrinfo and then just print out the returned values in the servinfo data structure: getaddrinfo(argc[1], argc[2], &hints, &servinfo); >> server hostname and server port number are passed via command line. But I notice that the sin_port in servinfo is not the port I am passing via the command line. 1) Does this getaddrinfo return the port number being used by the client as the source port number ? 2) My connect call after the getaddrinfo and socket calls in failing. I do not know why. How do I debug it ? My client code snippet: memset(&hints, 0 ,sizeof hints); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_CANONNAME | AI_NUMERICSERV; getaddrinfo(argc[1], argc[2], &hints, &servinfo); for (p = servinfo till p!=NULL) sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol) connect(sockfd, p->ai_addr, p->ai_addrlen) >>>>> Connect not going through. I start my client program like this: ./a.out myservername 18844 Thanks ! A: New answer: You are invoking your program with only one argument, so argv[1] contains "18844" and argv[2] is a null pointer. This is going to try to connect to a host with numeric IP 18844 and an unspecified port number (which will end up being 0 and failing). Old answer: (relevant but not your problem) sin_port and the whole sockaddr_in structure is in network byte order. You'll need to convert the port with ntohl to use it as a number, but you would be better off never touching sockaddr structures' internals whatsoever. Instead, use getnameinfo with NI_NUMERICHOST and NI_NUMERICSERV to get the address back into a string-based numeric form, then strtol to read the port ("service") number into an integer. This works even for non-IPv4 network address/protocol families (like IPv6) and requires no additional code for supporting new ones.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does a C compiler compile to generic assembly? I'm in a Computer Organization class, and we're programming stuff in assembly. However, since this is a class, I'm not getting a broader sense of anything, or any real-world use. We're using Altera's Nios II Assembly language. The professor hasn't told us anything about which assembly languages are used in current production, and what the semantics are, or how C code compiles to ALL of the assembly languages. Following that brief intro, am I correct in assuming that there are several assembly languages that C code compiles to? If so, what does it do to reach all of those assembly languages - parse it into a generic assembly language and then translate it from there? Or is there a separate process for each different assembly language? A: There is no requirement to compile C to any specific assemblies or any assembly at all, those are left to the implementor of a compiler, and not part of the language specification. Typically, every CPU manufacturer will develop a C compiler to target their specific architecture. There are more generic compilers like GCC and Clang though, which can target many different instruction sets. To use Clang as an example, it is based on the Low Level Virtual Machine, which is an abstract machine with an "intermediate representation" language, LLVM IR. A back-end is written for each architecture that LLVM can target for converting LLVM IR to the instruction set, and then any compiler which compiles to LLVM IR can then target the CPUs supported by LLVM. The compiler will decide which back-end to target at runtime based on the arguments you pass to it. The compiler typically has a default back-end which is set when building the compiler itself, through the configuration (which will probably default to the architecture you're building the compiler on). GCC probably uses a similar approach with some intermediate representation, but I'm not sure of the details. There's also a GCC back-end which can target LLVM too. A: C can be converted into any kind of assembler the compiler(s) support. Whether there's an intermediate representation is up to the compiler as well. Note that if you're writing direct assembler inside your C code (e.g. you're writing a hardware driver in C but need to do some very low-level stuff), then you've locked your code to that particular platform's assembler language. C (and the compiler) will NOT take some code with embedded x86 assembler and translate that into (say) MIPS or PPC.
{ "language": "en", "url": "https://stackoverflow.com/questions/7558012", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }