text
stringlengths
8
267k
meta
dict
Q: Scoring a Javascript Quiz Script Hi I some javascript code written to quiz the user on 5 questions and then in theory output their score. As far as I can tell the questions are being scored, I just can't figure out how to output the response. I am having no issues fetching the correct html elements and displaying them. I believe the issue is in the looping elements of the window.onload function. The code is below, <script type="text/javascript"> var rand = 0; var right = 0; window.onload = function () { reset(); Rrand(); var rangQ = document.getElementById('area').getElementsByClassName('divide'); correct = document.getElementsByTagName('a'), i = 0; for (i; i < correct.length; i++) { if (correct[i].className == 'correct') { correct[i].onclick = function () { right++; reset(); Rrand(); } } else if (correct[i].className != 'correct') { correct[i].onclick = function () { right--; reset(); Rrand(); } } } } function Rrand() { var rangQ = document.getElementById('area').getElementsByClassName('divide'); rangQ[rand].style.display = ''; rand++; } function reset() { var rangQ = document.getElementById('area').getElementsByClassName('divide'); for (var i = 0; i < rangQ.length; i++) { rangQ[i].style.display = 'none'; } } document.write(right); </script> A: window.onload is not executed immidiately. you are writing output, but variable right is changed after that. you need to either move line document.write(right); into window.onload as last line (or after loop) or figure out other way that will be best for you
{ "language": "en", "url": "https://stackoverflow.com/questions/7540984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any way to link to the background image url in CSS without providing the full url (ie. local path)? Say for example I have embeded the following CSS file: http://site.com/tpl/theme_name/stylesheet.css In the header of my site... http://site.com and the CSS file contained the following (in one of its lines) background-image:url(images/background.gif); But the actual url to images/background.gif is: http://site.com/tpl/theme_name/images/background.gif The CSS would not recognise the image right? (because the CSS file is not providing the full url). The problem is although I can add the full url within the CSS file for the background image to show, I don't want too...because if for some reason the theme name got renamed it will mean I'd have to manually edit all the CSS files for the themes. So I was wondering is there any way around this ie. could I do something like ../images/background.gif (append dots)? PS: I know I can just do so in PHP by writing a wrapper file which replaces the url with the full one, and sends the appropriate header (CSS) - but that may be resource intensive? A: The CSS would not recognise the image right? (because the CSS file is not providing the full url). URLs inside the CSS file are relative to the CSS file's directory, so what you show should work just fine. (This will no longer apply if you change the URL path later using JavaScript, but I don't think that's the issue here.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7540989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding TinyMCE instances using ajax - Grails I have a page when user can add 0 to N TinyMCE editors that need to have some div soup around it. I have the html code in a gsp _template because it is more then a few lines and I didn't want to stuff it in javascript. Basicaly everytime user clicks "add editor", an ajax call is made to the server with new id as the only parameter, controller renders the template with elements properly named using the new id, and it is appended by javascript to the page. I think its a pretty elegant solution, but what bothers me are the ajax calls that are fired for every new editor that is to be added to the page which has always the same code apart from different element id's. Will this have any performance impact? Is the template cached after first call? Thanks A: The GSP should be compiled (pre-compiled on grails war) and then there is some caching to help speed up GSP rendering. The performance issues are no different than considering any amount of traffic. The server doesn't care (or know) that the request is Ajax. It is just responding to a request. IF you remove ajax from your equation and just look at it that way, would you still be asking the performance question? That said, if all you need is an ID attached to the elements in the template, I might look into something like a javascript template solution (jquery.template() for example). That would negate the call to the server entirely.
{ "language": "en", "url": "https://stackoverflow.com/questions/7540996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Create a loop structure to display all integer values BETWEEN the smaller and larger number provided? Working on a homework assignment and am stuck with this task: Create a loop structure to display all integer values BETWEEN the smaller and larger number provided. Not looking for just an answer in code form. Would appreciate an explanation as to how and why it works. Data for the variables comes from users inputting a value between 1 and 100. I assume I will need a loop that will start with the lower of the two variables, count until it reaches the higher of the two variables, echo each integer in between and stop running. I am at a loss as to how to achieve this. I will also need a loop that will display only integers at certain intervals between the two numbers, such as only the multiples of five. EDIT: Here is my own solution, curious if this is the best method? Seems simple enough. if ( $num1 < $num2 ) for ($i=$num1+1; $i<$num2; $i++) echo $i . "<br />"; else for ($i=$num2+1; $i<$num1; $i++) echo $i . "<br />"; Here is some of the assignment thus far: <?php //Assign user input to variables $num1 = $_GET['firstNum']; $num2 = $_GET['secondNum']; //Determine if each number is odd or even, display results if( $odd = $num1%2 ) echo "First number is an ODD Number <br />"; else echo "First number is an EVEN Number </br />"; if( $odd = $num2%2 ) echo "Second number is an ODD Number <br />"; else echo "Second number is an EVEN Number </br />"; //Determine if the first number is larger than, smaller than, or equal to the second number, display results if ( $num1 == $num2 ) echo "First number is equal to second number <br />"; elseif ( $num1 > $num2 ) echo "First number is greater than second number <br />"; else echo "First number is less than second number <br />"; //Create a loop structure to display all integer values BETWEEN the smaller and larger number provided ?> A: if ( $num1 < $num2 ) for ($i=$num1+1; $i<$num2; $i++) echo $i . "<br />"; else for ($i=$num2+1; $i<$num1; $i++) echo $i . "<br />"; A: this may not perfectly fit your need. but hope this helps. $num_small=$num1; $num_large=$num2; $multiply=1; for ($i=$num_small; $num_large<=$i; $i+$multiply) { echo $i; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7540997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: getting the port number of a website How can i obtain the port number of a website using a program. Is there any method / way that i can use to know the port number of a website ? Or, if i know that my port number 52970 is connected with 212.58.241.131 this ip , can i know the port number with which the port number of my PC is connected ? A: The port number for http is port 80 and 443 for ssl. If you are on windows start up cmd and type netstat -a -b to see what program connects where. Please elaborate or post an example of what you want to achieve as it's not quite clear to me. €dit: in php you can find the remote or server port with $_SERVER['REMOTE_PORT'] or $_SERVER['SERVER_PORT'] If I am right, you are looking for the remote port. http://php.net/manual/en/reserved.variables.server.php for telnet look here : http://www.geckotribe.com/php-telnet/ A: I believe you need to review the concept of port numbers. By default, HTTP uses port 80. So an individual website you visit won't need access to any other port. TCP and UDP port numbers A: I am not sure what you are looking for but from a PHP script you can get the port the client uses to connect to your web server with $_SERVER["REMOTE_PORT"] A: I am not sure if this helps you at all but the gold standard for scanning ports has to be nmap. http://nmap.org/ You can scan open ports for a specific IP address. A: echo $_SERVER['SERVER_PORT']."<br/>"; echo $_SERVER['REMOTE_PORT']."<br/>"; 'SERVER_PORT' The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is. 'REMOTE_PORT' The port being used on the user's machine to communicate with the web server.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Java Web Start and Main Class I made an application and i would have an auto-update at start. Reading on stackoverflow many people suggest Java web start. So with Netbeans i enabled web start configuration and soon on. It generated launch.jnpl html , jar file and lib folder. In the main of program i insert DownloadService2 service = (DownloadService2) ServiceManager.lookup("javax.jnlp.DownloadService2"); ResourceSpec spec = new ResourceSpec("http://www.mysite:8080/.*", "1.*", service.JAR); ResourceSpec results[] = service.getCachedResources(spec); results = service.getUpdateAvailableResources(spec); SO i uploaded all files in dist folder to webserver. Now if i start the application with lunch.jnpl it starts without problem. But when i use my jar file i got error : Could not find main class "My class" program exit. Now if i dont use DownloadService2 it works with Jar File. So my question is : How could i use Java Web start to Update my program? For example if i release another version and put it codebase url, if i start program with jar file it should downloads new version. Could someone tell my if i wrong something or misunderstood how Java web start works ? Edit: i would that programs follows this line : 1) lunch with jar if it's possibile , Check for update...if it cant becouse offline use the old ones 2) if online check for update if aviable download update in the folder 3) if update not aviable use older one. repeat 1 2 3 A: Well this is a two parter now, isn't it: First, why do you get an error about your main class? Does your jnlp file have the correct package and name of the main class declared? It should be something like: <application-desc main-class="package1.package2.MyMainClass" /> Secondly, how does the update work. Well once someone accesses your jnlp file and starts your jar application from it, that jar is downloaded locally on the client's machine. Then, when he runs it a second time, the jnlp protocol will first check the url to see if the jar has been update. If so, then it gets that new version and that's what the client will run. If it hasn't been updated the previouslly downloaded jar will be run from local machine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541008", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SkinnableContainer+Layout vs Group+Rect+Hgroup I'm trying to add a custom background to my horizontally laid out container. There are two ways mentioned to accomplish this: * *Use a SkinnableContainer with a HorizontalLayout *Use a Group with a Rect and another HGroup inside it. Which is a better option according to memory? Also, is placing multiple groups, hgroups and vgroups in a nested fashion a major flaw in design? Thanks in advance! A: Which is a better option according to memory? You'll have to test and see, but from a theoretical approach; a SkinnableContainer will perform a lot more processing than a group. My first approach would be to use a group with a Rect inside it. Or, if you're doing mobile development, use a group and draw a Rect on top of it using the graphics API. Also, is placing multiple groups, hgroups and vgroups in a nested fashion a major flaw in design? Not a major design flaw, but it could very well contribute to the lack of performance in an application. It it becomes an issue, you should evaluate your use of containers and see if you can minimize. Sometimes using a basicLayout and writing a layout algorithm will give you a lot more performance, and flexibility. It may very well take longer to write, depending on the complexity, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web2py AJAX autocomplete and auth.user_id I got these tables db.define_table('sender', Field('id'), Field('user_id', auth.user_id), Field('name'), # e.g. Daniel Field('email'),# e.g. daniel@daniel.com Field('opening'), # e.g. Dear Daniel ...) db.define_table('receiver', Field('id'), Field('user_id', auth.user_id), Field('name'), # e.g. John Field('email'), # e.g. John@john.com Field('tel'), # e.g. 111 222 111 ...) db.define_table('letter', Field('id'), Field('user_id', auth.user_id), Field('sender', db.sender.id), # e.g. Daniel Field('receiver', db.receiver.id), # e.g. John Field('opening'), # should be filled automatically when choosing/changing the value of "sender" ...) i used this : db.letter.opening.widget = SQLFORM.widgets.autocomplete(request, db.receiver_profile.opening, id_field=db.receiver.id) it shows all values stored in receiver but i want to show only the values that's owned to the user (db(db.receiver.user_id==auth.user_id).select(db.receiver.opening)) A: replace db.letter.opening.widget = SQLFORM.widgets.autocomplete(request, db.receiver_profile.opening, id_field=db.receiver.id) with db.letter.opening.widget = SQLFORM.widgets.autocomplete(request, db.receiver_profile.opening, id_field=db.receiver.id,db=db(db.receiver.user_id==auth.user_id))
{ "language": "en", "url": "https://stackoverflow.com/questions/7541017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Manual installation of a Perl Module I have downloaded the module Digest::SHA1 and extracted it to a directory (../Digest-SHA1-2.13/) , then copied all the SHA1.* files into (../Digest-SHA1-2.13/Digest) and in the perl script, I did : use Digest::SHA1; launching the script like this: perl -I ../Digest-SHA1-2.13/Digest perlscriptname.pl I get this error: Can't locate loadable object for module Digest::SHA1 in @INC I assume it has something to do with a shared library (*.so)?, I have no idea how to continue from here. I can install it directly using CPAN (-MCPAN) module, as I dont have permissions on that server to do that, and can install only locally (where the application is running). My final goal is to use Algorithm::CouponCode which is dependent on Digest::SHA1 The weird part is, that I have Digest::SHA1 installed (perl -MDigest::SHA1 -e 'print $Digest::SHA1::VERSION' shows version 2.11), still Algorithm::CouponCode (which is installed the same way I did with Digest::SHA1) complains it can find it in @INC thanks! A: There are two kinds of Perl module: pure-Perl and XS. Pure-Perl modules are written entirely in Perl, and can usually be installed just by copying the .pm files to an appropriate directory. XS modules are written in both Perl and C (XS is processed into C code by the ExtUtils::ParseXS module) and require a C compiler to install them. As dsolimano said, the easiest way to install Perl modules for the system Perl when you don't have root access is to use local::lib. (You could do the same things that local::lib does yourself, but why bother?) The reason why Digest::SHA1 works by itself but not when you're using Algorithm::CouponCode is that the system Perl already has version 2.11 of Digest::SHA1 installed. When you use -I ../Digest-SHA1-2.13/Digest, then use Digest::SHA1 picks up the Perl code from ../Digest-SHA1-2.13/Digest, but the shared library that would be built from the XS code is not in the corresponding location. A: Any reason why you can't use local::lib? create and use a local lib/ for perl modules with PERL5LIB It is basically a tool to help you use a private (non-systemwide) directory as your Perl library directory. After setting it up, you could run a command like perl -MCPAN -Mlocal::lib -e 'CPAN::install(Algorithm::CouponCode)' and then your script would use your locally installed copy of Algorithm::CouponCode). A: Use this recipe for manually installing perl modules: tar zxf Digest-SHA1-2.13.tar.gz cd Digest-SHA1-2.13 perl Makefile.PL make make test make install Note that some distributions will have a Build.PL file instead of Makefile.PL. In that case use this recipe: tar zxf ... cd ... perl Build.PL ./Build ./Build test ./Build install (You may be able to get by with just running make install and ./Build install.) If you need to alter the installation dir then use: perl Makefile.PL INSTALL_BASE=... or perl Build.PL --install_base ... depending on the kind of module. For more info see the perldoc for ExtUtils::MakeMaker::FAQ and Module::Build
{ "language": "en", "url": "https://stackoverflow.com/questions/7541019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: Facade Design Pattern - Implementation I am referring the book Elements of Reusable Object Oriented Software by Eric Gamma on degign patterns. I however understood the concept of Facade pattern, but still not able to understand the implementation points which has been given in the book as I am little poor with the implementing part esp. The below are the 2 points mentioned in the book: * *Reduce client subsystem coupling: by making the Facade class an abstract class. *Public v/s Private subsystem classes. Could someone please explain me this with some example or with the code I have: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Facade_CSharp { class Program { static void Main(string[] args) { Facade facade = new Facade(); facade.ProcessA(); facade.ProcessB(); // Wait for user Console.ReadKey(); } } /// <summary> /// The 'Subsystem ClassA' class /// </summary> class SubSystemOne { public void MethodOne() { Console.WriteLine(" SubSystem One"); } } /// <summary> /// The 'Subsystem ClassB' class /// </summary> class SubSystemTwo { public void MethodTwo() { Console.WriteLine(" SubSystem Two"); } } /// <summary> /// The 'Subsystem ClassC' class /// </summary> class SubSystemThree { public void MethodThree() { Console.WriteLine(" SubSystem Three"); } } /// <summary> /// The 'Subsystem ClassD' class /// </summary> class SubSystemFour { public void MethodFour() { Console.WriteLine(" SubSystem Four"); } } /// <summary> /// The 'Facade' class /// </summary> class Facade { private SubSystemOne _one; private SubSystemTwo _two; private SubSystemThree _three; private SubSystemFour _four; public Facade() { Console.WriteLine("\nRequests received from Client System and Facade is in execution... "); _one = new SubSystemOne(); _two = new SubSystemTwo(); _three = new SubSystemThree(); _four = new SubSystemFour(); } public void ProcessA() { Console.WriteLine("\nProcessA of Facade uses the following subsystems to accomplish the task:"); _one.MethodOne(); _two.MethodTwo(); _four.MethodFour(); } public void ProcessB() { Console.WriteLine("\nProcessB of Facade uses the following subsystems to accomplish the task:"); _two.MethodTwo(); _three.MethodThree(); } } } Code with Abstract Class: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Facade_abstract { class Program { static void Main(string[] args) { FacadeAbs facade = new FacadeAbs(); facade.ProcessA(); facade.ProcessB(); // Wait for user Console.ReadKey(); } } class SubSystemOne { public void MethodOne() { Console.WriteLine(" SubSystem One"); } } /// <summary> /// The 'Subsystem ClassB' class /// </summary> class SubSystemTwo { public void MethodTwo() { Console.WriteLine(" SubSystem Two"); } } /// <summary> /// The 'Subsystem ClassC' class /// </summary> class SubSystemThree { public void MethodThree() { Console.WriteLine(" SubSystem Three"); } } /// <summary> /// The 'Subsystem ClassD' class /// </summary> class SubSystemFour { public void MethodFour() { Console.WriteLine(" SubSystem Four"); } } /// <summary> /// The 'Facade' class /// </summary> public abstract class Facade { //public abstract Facade(); public abstract void ProcessA(); public abstract void ProcessB(); } public class FacadeAbs : Facade { private SubSystemOne _one; private SubSystemTwo _two; private SubSystemThree _three; private SubSystemFour _four; public FacadeAbs() { Console.WriteLine("\nRequests received from Client System and Facade is in execution... "); _one = new SubSystemOne(); _two = new SubSystemTwo(); _three = new SubSystemThree(); _four = new SubSystemFour(); } public override void ProcessA() { Console.WriteLine("\nProcessA of Facade uses the following subsystems to accomplish the task:"); _one.MethodOne(); _two.MethodTwo(); _four.MethodFour(); } public override void ProcessB() { Console.WriteLine("\nProcessB of Facade uses the following subsystems to accomplish the task:"); _two.MethodTwo(); _three.MethodThree(); } } } A: Facade is used to reduce the coupling between the programs. As in the example ProcessA calls 3 methods - _one.MethodOne(); _two.MethodTwo(); _four.MethodFour(); And the client just calls the ProcessA method. The facade is used just to reduce the coupling, dependency. If no facade the client will be the one to call these methods. So the Facade class provides the following - * *Hides the multiple calls. This helps as the client will have to make just a single call. prevents tight coupling. e.g. ProcessA only *If any of the method changes add or removes the arguments, the client code needs to change. However in case of facade the change does not impact the client. *The client has just a few public access points to the server side. And the server side can encapsulate its code. Less points of failure.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Caching specific Javascript and CSS files How can I cache a few specific JavaScript & CSS files. I found advice from this site to put this in my .htaccess file AddOutputFilter DEFLATE css js ExpiresActive On ExpiresByType application/x-javascript A2592000 But it is incomplete. What is .htaccess and how do I create it, where to store it, in my web root folder? What is the meaning of the following statements: AddOutputFilter DEFLATE css js ExpiresActive On ExpiresByType application/x-javascript A2592000 I dont want to cache all my Javascript & CSS files rather just a few specific files which will never change. How can I do this? A: You can configure IIS to cache specific files by extension. For example: Select the folder where your css/js files reside and then click on Output Caching. Then add the file extensions that you want to cache: I don't think you can specify which ones to cache on a per file basis unless you write an http handler module to add the appropriate headers for each file independently, but from IIS this is how is done. Then you can verify that you are getting 304 responses using firebug / fiddler or your tool of choice. I hope this is helpful. A: That's cool i would anyways add a file revisions and make IIS cache css + js files. As Icarus specified. Then if you update the files on the server just add a new revision number this could also be a timestamp. * *http://particletree.com/notebook/automatically-version-your-css-and-javascript-files/ *http://davidwalsh.name/prevent-cache (just the opposite) *http://betterexplained.com/articles/speed-up-your-javascript-load-time/ *http://www.die.net/musings/page_load_time/ *http://ajaxpatterns.org/Patterns#Performance_Optimisation A: * *AddOutputFilter DEFLATE: output is compressed(usually gzip) before sent to server in this case css & js your css and js. *ExpiresActive On: Sets Expires and cache control headers to On *ExpiresByType: Set the expire rule for the content type in this case application/x-javascript to a month A2592000 => 24 * 3600 * 30 its in ms. I would recommend to instead of handling specific js via .htaccess you should add a revisions number to your js files, ala: <script src="link/to/file.js?rev=xxx"></script> Then when you update your files just update the rev number. And your clients will automatically be served the new files. Resources: * *http://httpd.apache.org/docs/2.0/mod/mod_deflate.html *http://httpd.apache.org/docs/2.0/mod/mod_expires.html *http://html5boilerplate.com/docs/htaccess/
{ "language": "en", "url": "https://stackoverflow.com/questions/7541032", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Is "refs/heads/master" same as "refs/remotes/origin/master" in Git? The question is simple: is refs/heads/master the same thing as refs/remotes/origin/master? If it is not in some cases, how can I know when it is not and what it is then? A: They are two different symbolic names that can point to different things. refs/heads/master is a branch in your working copy named master. Frequently that is a tracking branch of refs/remotes/origin/master because origin is the default name for the remote created by git clone and its primary branch is usually also named master. You can see the difference between them with git rev-list refs/heads/master..refs/remotes/origin/master which will be empty if they are the same and will otherwise list the commits between them. A: The key difference to understand is that the branches under refs/heads/ are branches that, when you have one checked out, you can advance by creating new commits. Those under refs/remotes/, however, are so-called "remote-tracking branches" - these refs just point to the commit that a remote repository was at the last time you did a git fetch <name-of-remote>, or a successful git push to the corresponding branch in that remote repository. (I wrote a blog post that talks about this difference at some length here.) A: I still felt confused reading the posts here. So, maybe this clarifies things and provides a better answer. The short answer is no these two references you list are not the same. One stores your local repo master reference commit, the other stores your remote repo reference commit. But read on... First Git documentation says the following: A ref is a file in which you store a SHA-1 value under a simple name so you can use that simple name rather than the raw SHA-1 value. A branch in Git is: a simple pointer or reference to the head of a line of work. So, what are these strange paths in Git? refs/ - This is simply a folder to references in the Git system that store assigned user-friendly names to hashed SHA-1 branches in your local repo. refs/heads/ - This is folder of files that store a set of user-friendly assigned branch names that map back to Git commit hash values. These commit values represent branches in your local repo and are the last commit point where you saved some code in each branch. You will often see files inside this folder with the name of each branch in your repo and inside the SHA-1 hash value which connects it to the last commit for that branch. "head" means its a list of HEAD's, or the last commit reference in a branch. So this folder of files would list all names of branches in your project with the hash to the last known commit at the end of the string of commits for the branch. refs/heads/master - This is actually a file reference to an individual branch file called "master", and holds a hash to the default or master branch reference Git assigns to every Git repo you create. As this "master" file is inside the "head" ref folder, that just means it stores the last known commit for the master branch in your project. refs/remotes/ - This is simply a list of the remote repositories associated with to your local repository, if any exist. This is a folder of more folders and files. refs/remotes/origin - This is simply a reference to the default remote reference associated with your local repo. This is a folder of files to your remote repo branches and could have a unique name other than the generic name. "origin" is created as the remote repo name the first time the remote repo is cloned. refs/remotes/origin/master - This points to a file that contains a hash and indicates the default or "origin" remote repo associated with your project and its "master" or default branch. Master would as above, store the last commit hash inside that master file, indicating on the remote repo the last commit location.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "41" }
Q: Losing xml data when parsing date and time in Savon I'm using Savon in my RoR app. This is my call to the service: client = Savon::Client.new(MY_SOAP_CLIENT) response = client.request :wsdl, :get_history do soap.body = "<startDate>2011-09-23</startDate><endDate>2011-09-24</endDate><userId>3</userId>" end And I'm getting the next response in XML: <soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soapenv:Body xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"> <resMessage xmlns=\"http://xxx-xxx.xxx.edu/xxx/\"> <result>date=2011-09-23?amount=13.00?time=08:50:38?user=a00123?type=transfer</result> <result>date=2011-09-23?amount=3.00?time=08:51:27?user=a00123456?type=transfer</result> <result>date=2011-09-23?amount=20.00?time=09:49:00?user=a00123456?type=transfer</result> </resMessage></soapenv:Body></soapenv:Envelope> But, the main problem is when I call response.to_hash I only get the Date objects part: => [Fri, 23 Sep 2011, Fri, 23 Sep 2011, Fri, 23 Sep 2011] This is great for the date, but the other part of the results are missing: amount, time, user and type. Also if I call response.body I keep getting the same results: => {:res_message=>{:result=>[Fri, 23 Sep 2011, Fri, 23 Sep 2011, Fri, 23 Sep 2011, Fri, 23 Sep 2011, Fri, 23 Sep 2011], :@xmlns=>"http://xxx-xxx.xxx.edu/xxx/"}, :"@xmlns:soapenv"=>"http://schemas.xmlsoap.org/soap/envelope/"} I didn't find the solution for this here nor Savon Issues Thanks in advance A: You could use: h = Hash.from_xml(response.to_xml) and that would give you a correct hash. Ruby (RoR) XML to hash and then show in views
{ "language": "en", "url": "https://stackoverflow.com/questions/7541042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to switch graphes (on Neo4j)? How do I come back on the Neo4J graph after using g = new TinkerGraph() I guess it's something like g.loadGraphML(...) EDIT: Your answer helped me to better understand how loadGraphML() works, but it didn't solve my problem. I'm going to rephrase my question. I use Neo4j and Gremlin, and when I first start the server, I get the following lines under Gremlin console. ==> Available variables: ==> g = neo4jgraph[EmbeddedGraphDatabase [/home/user/software/neo4j-community-1.5.M01/data/graph.db]] Then I type gremlin> g = TinkerGraphFactory.createTinkerGraph() ==> tinkergraph[vertices:6 edges:6] But how can I come back to "g = neo4jgraph[EmbeddedGraphDatabase [/home/user/software/neo4j-community-1.5.M01/data/graph.db]]" A: I don't fully understand your question, but I believe you mean that you have done some work with TinkerGraph and you want to import that data into Neo4jGraph? Moreover, given that you are doing g.loadGraphML(...), I will assume you are talking about doing this from Gremlin. If not, please use the respective GraphMLReader/Writer classes provided by Blueprints. gremlin> g ==>tinkergraph[vertices:6 edges:6] gremlin> g.V ==>v[3] ==>v[2] ==>v[1] ==>v[6] ==>v[5] ==>v[4] gremlin> h = new Neo4jGraph('/tmp/test') ==>neo4jgraph[EmbeddedGraphDatabase [/tmp/test]] gremlin> g.saveGraphML('test.xml') ==>null gremlin> h.loadGraphML('test.xml') gremlin> h.V ==>v[1] ==>v[2] ==>v[3] ==>v[4] ==>v[5] ==>v[6] In short, you can output your graph to GraphML from TinkerGraph and then load it up into Neo4jGraph via the loadGraphML() method. There is a GraphMigrator tool in Blueprints that you might be interested---see the Blueprints JavaDoc for more information. A: Within the gremlin console, you should be able to just type: g = new Neo4jGraph("/home/path_to_your_neo4j/data/graph.db") Let me know if this answers your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Node.js Installation Errors on Mac OSX: [Errno 13] Permission Denied error I am trying to install node.js on Mac OSX. I'm following this guide: http://theoutliers.com/getting-started-with-nodejs-on-mac-osx/ I'm currently at the "make" step. but I get an error: [Errno 13] Permission Denied error: '/usr/local/include/node/' * *Where is this directory on my computer? *How do I grant permission? I know these are elementary questions, but like I said, I'm learning. A: 1) Where is this on my computer The /usr directory is hidden in OS X. You will have to enable hidden files, or you can use Command + Shift + G from Finder to go there. Screenshot: http://o7.no/oaQCDL 2) How do I grant permission You can either go there in Finder, right-click and choose Show Info, select the Permissions area, and change to permissions that would allow your user to Write, for example: 775. Alternatively you can run the command sudo chmod 775 /usr/local/include/node. To grant permission temporary you can run make with sudo make install and enter your password. That will give the make process root permissions to install Node.js there. A: I would recommend using the excellent homebrew package manager for Mac OS X. The following post shows you how to install homebrew and use it to Install node.js: http://vivahate.com/2010/10/10/node-os-mac-os-x/ Hope this helps A: You could try to run the make/make install as root. (Only if you trust the source) Simply invoke the comand like sudo make or sudo make install and enter your password. Otherwise, you could own the directory that fails, but since /usr/local/include is not obviously in your "possession", I'd stick to being superuser. A: Either install as root as @iStefo suggests (perhaps slightly safer to run make install as yourself and let the install fail and thrn run make install as root qhich will just do the install) or change the install directory which you do when running ./configure (run ./configure --help to hopefully show you the parameter to use) Alternatively install C libraries and packages using a package manager e.g. macports, fink, homebrew
{ "language": "en", "url": "https://stackoverflow.com/questions/7541050", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Pinging an IP range with Scapy I'm attempting to write a Python script which uses the Scapy module to ping an internal IP range to determine which IP's are online. I've got this so far: #!/usr/bin/python from scapy.all import * conf.verb = 0 for ip in range(0, 256): packet = IP(dst="192.168.0." + str(ip), ttl=20)/ICMP() reply = sr1(packet) if "192.168." in reply.src: print reply.src, "is online" And the program will sit for a while doing nothing, and then if I kill it with CTRL+C I get an error message: Traceback (most recent call last): File "sweep.py", line 7, in <module> if "192.168." in reply.src: AttributeError: 'NoneType' object has no attribute 'src' However if I try it with a single IP address, instead of a range, it works. Like this: #!/usr/bin/python from scapy.all import * conf.verb = 0 packet = IP(dst="192.168.0.195", ttl=20)/ICMP() reply = sr1(packet) if "192.168." in reply.src: print reply.src, "is online" Anyone know how I can fix this problem? Or do you have any other ideas on how I can ping an IP range with Scapy, to determine which hosts are online? A: You just need to ensure that reply is not NoneType as illustrated below... sr1() returns None if you get a timeout waiting for the response. You should also add a timeout to sr1(), the default timeout is quite absurd for your purposes. #!/usr/bin/python from scapy.all import * TIMEOUT = 2 conf.verb = 0 for ip in range(0, 256): packet = IP(dst="192.168.0." + str(ip), ttl=20)/ICMP() reply = sr1(packet, timeout=TIMEOUT) if not (reply is None): print reply.dst, "is online" else: print "Timeout waiting for %s" % packet[IP].dst A: You can't show reply.src field if the return of variable is null. In other words, you need to validate if the variable has return with some value (if the ping was successful). You can make an IF condition to get the .src field only when variable is not null. A: FTR, Scapy supports implicit generators. This works: ans, unans = sr(IP(dst="192.169.0.1-255")/ICMP(), timeout=2) Then iterate through the answers. It is probably much better :)
{ "language": "en", "url": "https://stackoverflow.com/questions/7541056", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How do you treat a ReferenceProperty like a boolean in AppEngine Datastore? I have a model which might reference another model and which has a completed_on date. class Game(db.Model): challenge = db.ReferenceProperty(Challenge, required=False) completed_on = db.DateTimeProperty(default=None) I'd like to be able to select all of the completed Challenge games that were completed before a certain time period. Problem is I can't have 2 inequalities But http://code.google.com/appengine/docs/python/datastore/queries.html says: Inequality Filters Are Allowed on One Property Only: Which means I can't do challenge > '' and completed_on < datetime_value However I could do is_challenge=True and completed_on < datetime_value provided I add a new column to the db called is_challenge. With that in mind, is there someway to convince the datastore to treat challenge as a boolean? It appears it can't be done this way, and I'm hoping there is some other way to accomplish this without having to add yet another column to the model and probably yet another index to go with that column. I am expecting the list of games to be large enough to not want to filter it in python for every page displayed. A: The only way to do this is, as you observe, to add a boolean property that indicates if challenge is set or not. You can do this with ease by using ComputedProperty: class Game(db.Model): challenge = db.ReferenceProperty(Challenge, required=False) completed_on = db.DateTimeProperty(default=None) @db.ComputedProperty def has_challenge(self): return self.challenge is not None
{ "language": "en", "url": "https://stackoverflow.com/questions/7541059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dragging and dropping a button in iphone I need to drag and drop UIButtons(image) on bigger UIImageView. I want to implement following functionality - * *While dragging if the button is inside UIImageView then only it should drop,else it should not drop *When touching down and dragging it should immediately create a new UIButton at original position. *After the UIButton is dropped it should not move from its new position. Thanking in advance. A: I'm not quite sure if this is what you're looking for but what you can do is start a timer on the touchDown action that will trigger a method that makes the button update to the current CGPoint touch location. Then add if statements to control whether it's inside an image or not. To make the button stop, use the touchUpInside method and invalidate the timer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP 301 redirect giving a 302 instead On Sept 1st, I did a 301 on my web page: http://www.gameaudio101.com/toolbox.php and it redirects to http://www.gameaudio101.com/jobs.php The problem is that over time, the new page was never indexed. The original still shows up in google search. Both pages are identical but the old one has this at the top: <? Header( "http://www.gameaudio101.com/toolbox.php 301 Moved Permanently" ); Header( "Location: http://www.gameaudio101.com/jobs.php" ); ?> Should that be the ONLY code on the page? Please help a non-coder! A: Your first header is incorrect. It should be header("HTTP/1.1 301 Moved Permanently"); header("Location: http://www.gameaudio101.com/jobs.php"); exit; Or this header("Location: http://www.gameaudio101.com/jobs.php", true, 301); exit;
{ "language": "en", "url": "https://stackoverflow.com/questions/7541062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I rollback a transaction using Unit of Work and Repository patterns? I have a user repository, which does all the user data access. I also have a unit of work class that manages the connection and transaction for my repositories. How do I effectively rollback a transaction on my unit of work class, if an error happens within my repository? Create method on my UserRepository. I'm using Dapper for DataAccess. try { this.Connection.Execute("User_Create", parameters, this.Transaction, commandType: CommandType.StoredProcedure); } catch (Exception) { //Need to tell my unit of work to rollback the transaction. } I pass both the connection and transaction that were created in my unit of work constructor to my repositories. Below is a property on my unit of work class. public UserRepository UserRepository { get { if (this._userRepository == null) this._userRepository = new UserRepository(this._connection, this._transaction); return this._userRepository; } } I'm hoping to figure out the best approach. * Update * After doing more research into the unit of work pattern I think I am using it completely wrong in my example. A: Dapper supports TransactionScope, which provides a Complete() method to commit the transaction, if you don't call Complete() the transaction is aborted. using (TransactionScope scope = new TransactionScope()) { //open connection, do your thing scope.Complete(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7541063", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can i call method from .net console application under custom user? I have a console application and i would like to call method from it under another user. Can i specify this user and password in attribute to method? A: No, this is not possible. You can't have a single method run under a different user context.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Asp.net profile property not serializing properly in Silverlight app lately I have been messing around with the Silverlight Business Application template to get me used to silverlight / wcf ria services. I have encountered a wierd issue that I don't know how to solve. So far all I've done was created a new profile property called "AvatarURL", the basic concept is from this Avatar tutorial, and removed the FriendlyName property. The difference is that I'm just setting the AvatarURL property to default (~/Images/Default.jpg) when the user registers instead of writing a byte array to file. So I'm not browsing for files or pulling from webcam or anything like that during the registration phase. I've made the necessary changes to LoginStatus.xaml etc, and after logging in the image wouldn't display in it's placeholder. I stepped through the 'Authentication_LoggedIn' eventhandler in LoginStatus.xaml and for some reason the user's AvatarURL property is only a partial value. If the value in the database is: "http://localhost:52878/Images/Default.jpg". The value I get when I do the stepthrough is: "http://localhost:528". I have double checked the database values and ensured they are correct. If I input the XAML Image's Source value manually (http://localhost:52878/Images/Default.jpg) it displays the image no problem. It appears to be a problem between the communication between the silverlight app and the asp.net website project. Due to the fact I've only made miniscule changes to the solution, and written none of the code that wires the 2 projects together, I have no idea where to look to solve this problem, anyone have any ideas? I can post some code if necessary but it's not much different than the default business template. Thanks in advance. A: As the saved entry (http://localhost:528) is exactly 20 characters long and a common default length for text values in databases is 20 characters, I am guessing the size limit is actually in your database table and the values entered are being truncated. Please check the database schema and let me know of that is not the case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Global Objects when using Mono with MonoMac How do I declare global instances of objects? When using C# and .NET I would do something like this: public static program { public static Foo MyFoo = new Foo(); static void main() { MainForm = new MainForm(MyFoo); } } however with Mono/MonoMac the main function calls NSApplication.Main and doesn't directly create any windows. How would I pass an instance of MyFoo to the main window? Note: I am trying to avoid any references to MainClass in my windows/window controllers as that creates a tight coupling. I want to reuse the window classes in other situations hence the desire for loose coupling. Is what I want possible with MonoMac? thanks, Andy A: Use a singleton ? Your code would then look like: public class Foo { public static Foo Global = new Foo (); public Foo () { } // rest of Foo logic } public class Program { static void Main () { MainForm = new MainForm (Foo.Global); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7541074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Use EF entity classes in WCF I'm creating an app based on SOA, I've created WCF Service Project using Framework 4.0, in that I'm using Entity framework, in WCF operation Contract method I'm using the class generated by the EF, but the WCF can't recognize these objects, when I checked those classes in designer mode, they are like [EdmEntityTypeAttribute(NamespaceName="quizTestDBModel", Name="tbl_adminUser")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class tbl_adminUser : EntityObject { #region Factory Method /// <summary> /// Create a new tbl_adminUser object. /// </summary> /// <param name="adminUserId">Initial value of the adminUserId property.</param> public static tbl_adminUser Createtbl_adminUser(global::System.Int32 adminUserId, global::System.String name, global::System.String userid, global::System.String password) { tbl_adminUser tbl_adminUser = new tbl_adminUser(); tbl_adminUser.adminUserId = adminUserId; return tbl_adminUser; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 adminUserId { get { return _adminUserId; } set { if (_adminUserId != value) { OnadminUserIdChanging(value); ReportPropertyChanging("adminUserId"); _adminUserId = StructuralObject.SetValidValue(value); ReportPropertyChanged("adminUserId"); OnadminUserIdChanged(); } } } private global::System.Int32 _adminUserId; partial void OnadminUserIdChanging(global::System.Int32 value); partial void OnadminUserIdChanged(); #endregion } When I use this class in my operation contract as int adminRegister(tbl_adminUser _adminUser); It give error on that method, "The operation is not supported in WCF Test Client, because it uses type tbl_adminUser" Thanks A: If you are passing platform-specific data across a service boundary, then you are not using SOA. Entity Framework classes are specific to .NET and to Entity Framework. Do not pass them across a service boundary. I also note that you want to subject your clients to your naming conventions (tbl_adminUser), as well as the fact that there are tables involved. Why do the callers of your service need to know anything about the fact that you've implemented the concept of an "admin user" by using a table named tbl_adminUser? You should create yourself a Data Transfer Object class named, for instance, AdminUser. It should have properties for all of the interesting public aspects of an admin user (apparently, just AdminUserId). It should have no behavior at all - just data. This is the class that should be sent by and received from your service. And, yes, you'll have to implement mapping code. A: The error just says that WCF Test client doesn't support your contract but it doesn't mean that WCF itself doesn't. WCF Test client is for testing the most common scenarios and it doesn't support all WCF features. Write test application or use more powerful test tool like SoapUI to validate that your service works. Also follow @John's advices because your current design has awful naming convention, it exposes EntityObject based entities and it is far from SOA. By your description it is simple CRUD exposed as a service. You will achieve similar result with WCD Data Services much faster.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Moose - coercing from Num to ArrayRef[Num]? Ok, what am I doing wrong - Moose is ignoring my coercion: package moo; use Moose; use Moose::Util::TypeConstraints; subtype Bar => as 'ArrayRef[Num]'; coerce 'Bar' => from 'Num' => via { [ 10 ] }; # this doesn't seem to be getting called has x => ( is => 'rw', isa => 'Bar', ); package main; my $m1 = moo->new(x => [ 3 ]); # works my $m2 = moo->new(x => 5); # doesn't work A: Maybe you forgot coerce => 1 while defining x attribute. has x => ( is => 'rw', isa => 'Bar', coerce => 1 ); `
{ "language": "en", "url": "https://stackoverflow.com/questions/7541082", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: disable click on certain area with a transparency picture or javascript better? I have one of the area that I don't want to be click at all on my site but just can see let say its a video so I will only allow them to use the control player but not using the play/pause by clicking on the video like what youtube or any other website does. I have an idea of using transparent photo to overlap the area that I wish not to be click but fail because the css I use I can never succeed to get it exact place. so I wish to know if there is a way either by css or javascript to stop the user to click on the area I want? Thanks A: The only way I can think of doing this cross-browser is using an iframe shim. Iframes can sit on top of flash content unlike other elements. <iframe width="70%" height="500px" name="about" src="about.html" frameborder=0 ALLOWTRANSPARENCY="true"></iframe> src: http://www.tech-recipes.com/rx/1253/htmlcss-transparent-iframes-in-all-browsers/ You might need to use filters in ie to make it transparent iframe.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)'; src: http://www.macridesweb.com/oltest/IframeShim.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7541084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ruby: unexpected results for multidimensional array initialization I know this is probably not good Ruby style, but i'm learning... what's going on here? Specifically, why is the first row of my array a duplicate of the second row, when I think I'm initializing (copying) the values of the array parameter testa into @test, keeping all the indices the same? class Test def initialize (size, testa) @test = Array.new(size, Array.new(size)); (1..size).each { |r| (1..size).each { |c| @test[r-1][c-1] = testa[r-1][c-1]; puts("#{r}, #{c}: #{@test[r-1][c-1]}"); } } end end t= Test.new(2,[[1,2],[3,4]]) #=> @test=[[3, 4], [3, 4]] A: The cause of the problem you're seeing is how you're initializing the Array. You're passing along a single newly initialized array in the method call, which is used as the value for each row. # Your initialization @test = Array.new(size, Array.new(size)); # The following is equivalent, and perhaps more illustrative of what's happening @a = Array.new(size) @test = Array.new(size, @a) # effective result => [@a, @a, @a, @a, @a] So in your method, as you iterate over the rows, you're repeatedly changing the values of the same array. To fix it, create a new array for each row, rather than 1 array which is referenced 5 times. This can be accomplished using the block initialization variant of Array. Something like: @test = Array.new(size) { Array.new(size) } Check out the docs for more explanation on the different methods of Array initialization. A: See: http://www.ruby-doc.org/core/classes/Array.html to Array.new(size, obj) is created with size copies of obj (that is, size references to the same obj) The object 'Array.new(size)' it's the same object to each line. Try: @test = Array.new(size) { Array.new(size) }; Or other implementation to your code: class Test def initialize(array) @test = array.map{|ar| Array.new(ar) } end end t = Test.new([[1,2],[3,4]])
{ "language": "en", "url": "https://stackoverflow.com/questions/7541085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: submitting different ajax loaded with the same custom submit button So it's kind of complicated what I'm trying to do. So let me give an example of code i got working first: {im using jquery rotate plugin} $("#img").rotate({ bind: { click: function(){ postlogic(); $(this).rotate({ angle:0,animateTo:-360,easing: $.easing.easeInOutExpo }); } } }); function submitlogic(){ // ---------------- post cache ----------------// var firstpost = $("#form_1").serialize(); var secondpost = $("#form_2").serialize(); // ------------ post logic -----------------// if(pagetrack = 1){ $.post('query1.php',firstpost,function(data) { $("#new_content_here").html(data); }); var pagetrack = 2; } else if(pagetrack = 2){ $.post('query2.php',secondpost,function(data) { $("#new_content_here").html(data); }); var pagetrack = 3; } } Basically I want this image to be my submit button. This image-button will always be on the page and have the same behavior. I have some options to post, the user hits my rotating button, the options are submit to the database, and new options are displayed and the user then proceeds to select from these. "Pagetrack" tracks which form I'm on. My problem is that after I submit the first time, I can't get the submit to work again. There's probably some big concept I'm missing, but I don't know what it is. Can anyone help me out? A: you need to declare your pagetrack variable outside submitlogic function so the state will stay between function calls. var pagetrack = 1; function submitlogic(){ // ---------------- post cache ----------------// var firstpost = $("#form_1").serialize(); var secondpost = $("#form_2").serialize(); // ------------ post logic -----------------// if(pagetrack = 1){ $.post('query1.php',firstpost,function(data) { $("#new_content_here").html(data); }); pagetrack = 2; } else if(pagetrack = 2){ $.post('query2.php',secondpost,function(data) { $("#new_content_here").html(data); }); // if you have only two elements you should use pagetrack = 1; here pagetrack = 3; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7541087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What's the simplest database implemented on the iPhone? For each row in a database1 , compare the data in the cell at index 1 to each row in an existing database2 at cell index 1, and if there is a match, then change the value of the cell at index2 of database2 from 1 to 0 2 NSDictionaries? A: If the data is generated and consumed in app then CoreData. Otherwise sqlite. A: Sqlite. Among other options like CoreData, sqlite databases are portable and could then without any modifications be used on Android, Mac OS, Windows and many other platforms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error with nested_form gem: wrong number of arguments (4 for 3) I have been struggling with this one for days and can't seem to figure out what's wrong. I'm attempting to allow polymorphic file attachments to a model Item, which belongs to model Location. My routes are defined as: resources :locations do resources :items post :sort end resources :items do resources :assets #model for attachments end I followed a tutorial about doing exactly this with carrierwave and nested_form. After setting everything up, however, I get the following error when requesting the New action for the Item model: wrong number of arguments (4 for 3). It tells me the error is occurring at line 7 of this view: <%= nested_form_for [@location, @item], :html => { :multipart => true } do |f| %> <p> <%= f.label :name %><br /> <%= f.text_field :name %> </p> <%= f.fields_for :assets do |a_form| %> ### LINE 7 #### <p> <%= a_form.label :file %><br /> <%= a_form.file_field :file %> <%= a_form.hidden_field :file_cache %> </p> <%= a_form.link_to_remove "Remove this attachment" %> <% end %> <%= f.link_to_add "Add attachment", :assets %> <p><%= f.submit %></p> <% end %> If I don't use the nested_form gem and start out the view with a normal form_for, I get no errors and am able to successfully attach a single file to the Item. I can try and proceed without the gem, but (as far as I understand) nested_form will automate some of the functionality like removing the files and generating ajax to add new attachments. I was just wondering if anyone has run into this error or knows what mistake I'm making that's causing problems with nested_form? I understand what the error means, just not sure where/why the extra argument is being thrown in. I greatly appreciate any insight you can provide! FYI my dev setup: rails (3.1.0, 3.0.10), nested_form (0.1.1), carrierwave (0.5.7) A: In order to get nested_form working with rails 3.1, I had to pull the latest from github rather than using what's in the gem. In my Gemfile: gem "nested_form", :git => "git://github.com/ryanb/nested_form.git"
{ "language": "en", "url": "https://stackoverflow.com/questions/7541096", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Haskell - Find the longest word in a text I've got a problem about to write a function to find the longest word in a text. Input: A string with a lot of word. Ex: "I am a young man, and I have a big house." The result will be 5 because the longest words in the text have 5 letters (young and house). I've just started to learn Haskell. I've tried: import Char import List maxord' (str:strs) m n = if isAlpha str == True then maxord'(strs m+1 n) else if m >= n then maxord'(strs 0 m) else maxord'(strs 0 n) maxord (str:strs) = maxord' (str:strs) 0 0 I want to return n as the result but I don't know how to do it, and it seems there is also something wrong with the code. Any help? Thanks A: There are several issues here. Let's start with the syntax. Your else parts should be indented the same or more as the if they belong to, for example like this: if ... then ... else if ... then ... else ... Next, your function applications. Unlike many other languages, in Haskell, parentheses are only used for grouping and tuples. Since function application is so common in Haskell, we use the most lightweight syntax possible for it, namely whitespace. So to apply the function maxord' to the arguments strs, m+1 and n, we write maxord' strs (m+1) n. Note that since function application has the highest precedence, we have to add parentheses around m+1, otherwise it would be interpreted as (maxord' strs m) + (1 n). That's it for the syntax. The next problem is a semantic one, namely that you have recursion without a base case. Using the pattern (str:strs), you have specified what to do when you have some characters left, but you've not specified what to do when you reach the end of the string. In this case, we want to return n, so we add a case for that. maxord' [] m n = n The fixed maxord' is thus maxord' [] m n = n maxord' (str:strs) m n = if isAlpha str == True then maxord' strs (m+1) n else if m >= n then maxord' strs 0 m else maxord' strs 0 n However, note that this solution is not very idiomatic. It uses explicit recursion, if expressions instead of guards, comparing booleans to True and has a very imperative feel to it. A more idiomatic solution would be something like this. maxord = maximum . map length . words This is a simple function chain where words splits up the input into a list of words, map length replaces each word with its length, and maximum returns the maximum of those lengths. Although, note that it's not the exact same as your code, since the words function uses slightly different criteria when splitting the input. A: There are a couple of problems There is no termination for you recursion. You want to return n when you processed the whole input. maxord' [] _ n = n Syntax: maxord'(strs 0 m) this means that call apply strs with parameters 0 and m, and then use that as an argument to maxord. What you wan't to do is this: maxord' strs 0 m m+1 should be (m+1). You might want to process empty strings, but maxord doesn't allow it. maxord s = maxord' s 0 0 That should do it. There are a couple of subtleties. maxord' shoudln't leak out to the namespace, use where. (max m n) is a lot more concise than the if-then-else you use. And check the other answers to see how you can build your solution by wiring builtin things together. Recursions are a lot harder to read. A: Try to split your task into several subtasks. I would suggest splitting it like this: * *Turn the string into a list of words. For instance, your example string becomes ["I","am","a","young","man","and","I","have","a","big","house"] *map length over the list. This calculates the word lengths. For example, the list in step 1 becomes [1,2,1,5,3,3,1,4,1,3,5] *Find the word with the highest number of characters. You could use maximum for this. You can compose those steps using the operator (.) which pipes two functions together. For instance, if the function to perform step 1 is called toWords, you can perform the whole task in one line: maxord = maximum . map length . toWords The implementation of toWords is left as an excercise to the reader. If you need help, feel free to write a comment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Writing a javascript library I want to write a JS library and handle it like this: var c1 = Module.Class(); c1.init(); var c1 = Module.Class(); c2.init(); And of course, c1 and c2 can not share the same variables. I think I know how to do this with objects, it would be: var Module = { Class = { init = function(){ ... } } } But the problem is I can't have multiple instances of Class if I write in this way. So I'm trying to achieve the same with function, but I don't think I'm doing it right. (function() { var Module; window.Module = Module = {}; function Class( i ) { //How can "this" refer to Class instead of Module? this.initial = i; } Class.prototype.execute = function() { ... } //Public Module.Class = Class; })(); I don't have a clue if it's even possible, but I accept suggestions of other way to create this module. I don't know if it's relevant also, but I'm using jQuery inside this library. A: Usage: var c1 = Module.Class("c"); var c2 = Module.Class("a"); var n = c1.initial(); // equals 'c' c1.initial("s"); n = c1.initial(); // equals 's' Module Code: (function(window) { var Module = window.Module = {}; var Class = Module.Class = function(initial) { return new Module.Class.fn.init(initial); }; Class.fn = Class.prototype = { init: function(initial) { this._initial = initial; }, initial: function(v){ if (v !== undefined) { this._initial = v; return this; } return this._initial; } }; Class.fn.init.prototype = Class.fn; })(window || this); This is using the JavaScript "Module" Design Pattern; which is the same design pattern used by JavaScript libraries such as jQuery. Here's a nice tutorial on the "Module" pattern: JavaScript Module Pattern: In-Depth
{ "language": "en", "url": "https://stackoverflow.com/questions/7541099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Logic of installation location of R packages under Linux What's the logic behind the different installation locations of various R packages? I seem to have packages installed in several different locations on my linux machine. Is this typical behavior and if so what is the rational for installing a package in /usr/lib/R/library vs /usr/lib/R/site-library? I don't really care where the package is installed but it does seem kind of silly to have the installations spread out in different locations across my system. Renviron has the comment below, which seems to suggest that /usr/lib/R/site-library is for Debian packaged packages, but doesn't really explain the purpose of the other two directories. Also, by setting /usr/lib/R/library last in the list doesn't that make it not the default dir for install.packages()? # edd Apr 2003 Allow local install in /usr/local, also add a directory for # Debian packaged CRAN packages, and finally the default dir > .libPaths() [1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library" [3] "/usr/lib/R/library" A: Matt, You generalize the wrong way from the specific (Debian/Ubuntu) to the generic (all Linux distros). This particular setup was suggested to me by two Debian-using R Core members (and this was before the dawn of Ubuntu). This is not an R-wide recommendation which is why you will not find it in the manuals, but rather a specific recommendation by R power users to be implemented on Debian and Debian-alike systems. The basic idea is * *to remain totally faithful to the separation of /usr/, /var/, .... to be handled by the package management system (eg apt-get, dpkg, ...) on the one hand, and /usr/local/... etc by the user on the other hand: these two shall never mix *so that /usr/local/lib/R/site-library gets the first spot in the list emitted by .libPaths() and thus becomes the default, thus ensuring that user-installed package end up below /usr/local/ as per the previous point *so that below /usr we get a separation between R's recommended packaged (included in the basic R sources too: boot, grid, lattice, ...) inside /usr/lib/R/library, and then all other package management controlled r-cran-* packages below /usr/lib/R/site-library. So e.g. r-cran-xml ends up there, or r-cran-zoo, or ... I still think the split is terrific, and that is why I maintain this setup in the Debian R packages. Having the local packages site-wide for all users is a good idea on a multi-user operating system.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How to check if font-face feature is available via javascript There is a way to check whether font-face feature is available or not through javascript? A: Sounds like a job for Modernizr.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541102", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: what is the cause of this error "Uncaught ReferenceError: Invalid left-hand side in assignment" Possible Duplicate: Uncaught ReferenceError: Invalid left-hand side in assignment I cannot provide any code because I feel it will take the thread away from the root question and lead to suggestions for hacks, jquery, or workarounds. I need to learn what is implied or causes the error Uncaught ReferenceError: Invalid left-hand side in assignment Thanks in advance for any information as I cannot find it in any ref pages, tutorials, or documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541110", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PHP Image Libraries I'm working on a PHP application that needs to obtain data from a topographical map (different elevations denoted by different colors). I need to do two things: * *Using this map (800x600), find a way to determine the exact pixel location of a particular city. For example, San Francisco is located at precisely 121x585. *Using the location from (1) above, I need to read the exact color at that location. Note: The map provider does not provide location-based data, only a colored map. I suspect multiple libraries would be needed to map coordinates to locations on the map (via a ratio?) and then use OCR to read the color. Are there any PHP libraries/tools that do this? How would you pull this off? A: I may not have understood the problem entirely, but you should map the locations you want into an array (of objects?) $city_mapping = array(new City("San Francisco", 121, 585), new City....); //Map your cities to an array. Where City should be defined as a class to contain those variables. Then use imagecolorat() to check for the color. A: Once you know the pixel-coordinates, you can use PHP's built-in GD library to sample the color of an arbitrary pixel quite easily. The tricky bit will be determining the pixel to sample, which can get pretty darned tricky. The earth being sphere-like, maps use various projections to produce a 2-d representation. If you know how the colored map image is projected, and you know the latitude/longitude of the pixel at (0,0), you should be able to write a function to convert lat/long to a pixel coordinate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Canceling onkeypress event after changing focus My users want this form to advance focus to the next field when enter is press instead of submitting the form. I've added an onkeypress handler to the test input to change the focus when enter is press. In the code below, when keydown function changes focus, I see the cursor jump to the new textbox but then the form gets submitted as if I pressed the enter key again. I thought that by returning false in my event handler the event would not be passed on but that does not seem to be the case. I've seen this behavior in both Chrome and Firefox. Could someone tell me what I am missing? <form action="" name="confirmation" method="post"> <fieldset> <div class="clearfix"> <label for="id_event_fuel_amount">Quantity:</label> <div class="input"> <input type="text" id="event_fuel_amount_id" name="event_fuel_amount" onkeypress="keydown(event, &#39;event_purchase_amount_id&#39;)" /> </div> </div> <div class="clearfix"> <label for="id_event_purchase_amount">Sale:</label> <div class="input"> <input type="text" id="event_purchase_amount_id" name="event_purchase_amount" /> </div> </div> <input type="hidden" name="state" value="3" id="id_state" /> <input type="hidden" name="time_stamp" value="2011-09-24 14:34:06" id="id_time_stamp" /> <input type="hidden" name="purchase" value="66" id="id_purchase" /> <input type="submit" value="Save"/> </fieldset> </form> <script> function keydown(e,s){ if (!e) var e = window.event; if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; if (code==13){ document.getElementById(s).focus(); return false; } } </script> A: Try e.preventDefault(); That should prevent the event from firing the form submit. A: I think this might help: <script type="text/javascript"> document.getElementById('hello').onkeydown=function(e){ var e=window.event || e; if (e.keyCode == 13) return false; } </script> <input type="text" id="hello" /> Here is a demo: jsFiddle demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7541120", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Defining variables in control structures According to the standard, what is the difference in behavior between declaring variables in control structures versus declaring variables elsewhere? I can't seem to find any mention of it. If what I'm referring to isn't clear, here's an example: if (std::shared_ptr<Object> obj = objWeakPtr.lock()) As you can see, I'm declaring and initializing a local variable, obj, in the if block. Also, is there any technical reason as to why this syntax isn't given any special behavior when used in place of a conditional? For example, adding an additional set of brackets results in a compiler error; this also prevents the variable from being chained with other conditions. // Extra brackets, won't compile. if ((std::shared_ptr<Object> obj = objWeakPtr.lock())) // If the above were valid, something like this could be desirable. if ((std::shared_ptr<Object> obj = objWeakPtr.lock()) && obj->someCondition()) A: According to the standard, what is the difference in behavior between declaring variables in control structures versus declaring variables elsewhere? I can't seem to find any mention of it. Declarations inside control structure introductions are no different that declarations elsewhere. That's why you can't find any differences. 6.4/3 does describe some specific semantics for this, but there are no surprises: [n3290: 6.4/3]: A name introduced by a declaration in a condition (either introduced by the type-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition. If the name is re-declared in the outermost block of a substatement controlled by the condition, the declaration that re-declares the name is ill-formed. [..] Also, is there any technical reason as to why this syntax isn't given any special behavior when used in place of a conditional? For example, adding an additional set of brackets results in a compiler error; this also prevents the variable from being chained with other conditions. An if condition can contain either a declarative statement or an expression. No expression may contain a declarative statement, so you can't mix them either. [n3290: 6.4/1]: Selection statements choose one of several flows of control. selection-statement: if ( condition ) statement if ( condition ) statement else statement switch ( condition ) statement condition: expression attribute-specifier-seq[opt] decl-specifier-seq declarator = initializer-clause attribute-specifier-seq[opt] decl-specifier-seq declarator braced-init-list It all just follows from the grammar productions. A: The difference from declaring and initializing a variable in the condition and declaring it elsewhere is that the variable is used as the condition, and is in scope inside the if's conditional statement, but out of scope outside that condition. Also, it's not legal to re-declare the variable inside the if condition. So bool x=something(); if(x) { bool y=x; // legal, x in scope int x=3; // legal ... } while (x=something_else()) // legal, x still in scope ... but: if(bool x=something()) bool y=x; // still legal int x=3; // not legal to redeclare ... } while (x=something_else()) // x declared in condition not in scope any more
{ "language": "en", "url": "https://stackoverflow.com/questions/7541123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: domain aliases and Google App Engine I have a Google Apps domain at www.openstv.org that I use for email and a website. I recently created a Google App Engine app at stv.appspot.com and it can also be accessed at opal.openstv.org. I would like to: * *Use www.opavote.org for my Google App Engine app instead of opal.openstv.org, and *Have opavote.org be a domain alias of openstv.org so that I don't have to maintain two Google Apps domains. Two stackoverflow questions suggest that this is possible: * *Google App Engine on Google Apps Domain *Google App Engine and domain name But other reputable information suggests that it is not possible: Issue 638 I've tried to do this, but I can't get it to work. Is there an explanation for this apparent contradiction? EDIT: Adding what I tried in response to Nick's comment. From App Engine Dashboard: * *Go to Application Settings *Click Domain Setup *Enter opavote.org -> "Sorry, you've reached a login page for a domain that isn't using Google Apps. Please check the web address and try again." *Click back and enter openstv.org -> Takes me to Google Apps for Openstv.org *From Google Apps Dashboard for OpenSTV.org -> stv settings (my GAE app) -> Click add new URL *I'm allowed to enter a subdomain of openstv.org (e.g., opal.openstv.org) but I am not allowed to use the opavote.org domain (there is no dropdown menu for the domain). *Go to Google Apps -> Domain Settings -> Domain Names and see that opavote.org is listed as a domain alias and is verified in two ways (DNS record and uploading file). No other options here. A: If you've added 'opavote.org' as an alias, it should be showing up in the list - this sounds like a bug with Apps. Have you tried removing it and re-adding it? If that doesn't work, you may need to file an issue with the Apps team. It's definitely possible to do this - I'm running apps off alias domains myself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Display contents of a Directory Android I am trying to display the contents of /data/dalvik-cache through the following program but it returns a NULL pointer exception. After a bit googling i found out that i don't have permissions to read the contents of /data folder.My phone is rooted and is there a way to display the contents of all such folders whose permissions are limited? public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); File listfiles[] = null; final String s = "/data/dalvik-cache"; File aDirectory = new File("/mnt"); if(aDirectory.isDirectory()) listfiles = aDirectory.listFiles(); for(int i=0;i<listfiles.length;i++) Log.i("FileName", listfiles[i].getName()); } A: I work on directory picker code. To list a dir content use: File f = new File("/cashe"); String[] d = f.list(); Result is null. Other dir it work fine. A: You have to run shell or other program via su command (e.g. with root privileges). You can see an example here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is the creation of multi-dimensional arrays so slow in Scala? Consider this code: Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array(Array()))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) I aborted the REPL after several minutes. Should I expect such long compilation times or is this a problem/bug of the compiler? A: Misleading title, I think, at least with respect to the actual code you're trying. Let's help the type inferencer... object A extends App { val x = Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[Nothing]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]() println(x) } That compiles just fine and runs just fine (I don't even have to modify JVM options): $ time scalac -d classes A.scala real 0m5.179s $ time scala -cp classes A [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[Ljava.lang.Object;@872380 real 0m2.461s So it's more about compilation and type inference including in the REPL (which rewrites the code and recompiles). The REPL seems to struggle somewhere after the explicitrouter phase (tried using scala -Xprint:all). A: On Scala 2.9.0.1 this compiles (and runs) just fine as long as you give scalac enough stack space: export JAVA_OPTS="-ss128M" scalac arrays.scala It doesn't seem to work in the REPL though, but that doesn't really surprise me anymore...
{ "language": "en", "url": "https://stackoverflow.com/questions/7541128", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Define a macro off of the content of a macro Is it possible to define a macro off of the content of a macro? For example: #define SET(key,value) #define key value SET(myKey,"value") int main(){ char str[] = myKey; printf("%s",str); } would result in int main(){ char str[] = "value"; printf("%s",str); } after being preprocessed. Why would I do this? Because I'm curious ;) A: No, its not possible to define a macro within another macro. A: The preprocessor only iterates once before the compiler. What you're suggesting would require an undetermined amount of iterations. A: No you can't - # in a replacment list of a macro means QUOTE NEXT TOKEN. It's more of a spelling issue, than any logical puzzle :) (If you require this kind of solution in your code, than there are ways and tricks of using macro's, but you need to be specific about the use cases you need - as your example can be achieved by defining: #define mykey "value") Here it is from the ansi C99 standard 6.10.3.2 The # operator Constraints 1 Each # preprocessing token in the replacement list for a function-like macro shall be followed by a parameter as the next preprocessing token in the replacement list. Semantics 2 If, in the replacement list, a parameter is immediately preceded by a # preprocessing token, both are replaced by a single character string literal preprocessing token that contains the spelling of the preprocessing token sequence for the corresponding argument. Each occurrence of white space between the argument’s preprocessing tokens becomes a single space character in the character string literal. White space before the first preprocessing token and after the last preprocessing token composing the argument is deleted. Otherwise, the original spelling of each preprocessing token in the argument is retained in the character string literal, except for special handling for producing the spelling of string literals and character constants: a \ character is inserted before each " and \ character of a character constant or string literal (including the delimiting " characters), except that it is implementation-defined whether a \ character is inserted before the \ character beginning a universal character name. If the replacement that results is not a valid character string literal, the behavior is undefined. The character string literal corresponding to an empty argument is "". The order of evaluation of # and ## operators is unspecified. A: Macros are a simple text substitution. Generating new preprocessor directives from a macro would require the preprocessor to continue preprocessing from the beginning of the substitution. However, the standard defined preprocessing to continue behind the substitution. This makes sense from a streaming point of view, viewing the unprocessed code as the input stream and the processed (and substituted) code as the output stream. Macro substitutions can have an arbitrary length, which means for the preprocessing from the beginning that an arbitrary number of characters must be inserted at the beginning of the input stream to be processed again. When the processing continues behind the substitution, then the input simply is handled in one single run without any insertion or buffering, because everything directly goes to the output. A: whilst it is not possible to use a macro to define another macro, depending on what you are seeking to achieve, you can use macros to effectively achieve the same thing by having them define constants. for example, i have an extensive library of c macros i use to define objective C constant strings and key values. here are some snippets of code from some of my headers. // use defineStringsIn_X_File to define a NSString constant to a literal value. // usage (direct) : defineStringsIn_X_File(constname,value); #define defineStringsIn_h_File(constname,value) extern NSString * const constname; #define defineStringsIn_m_File(constname,value) NSString * const constname = value; // use defineKeysIn_X_File when the value is the same as the key. // eg myKeyname has the value @"myKeyname" // usage (direct) : defineKeysIn_X_File(keyname); // usage (indirect) : myKeyDefiner(defineKeysIn_X_File); #define defineKeysIn_h_File(key) defineStringsIn_h_File(key,key) #define defineKeysIn_m_File(key) defineStringsIn_m_File(key,@#key) // use defineKeyValuesIn_X_File when the value is completely unrelated to the key - ie you supply a quoted value. // eg myKeyname has the value @"keyvalue" // usage: defineKeyValuesIn_X_File(keyname,@"keyvalue"); // usage (indirect) : myKeyDefiner(defineKeyValuesIn_X_File); #define defineKeyValuesIn_h_File(key,value) defineStringsIn_h_File(key,value) #define defineKeyValuesIn_m_File(key,value) defineStringsIn_m_File(key,value) // use definePrefixedKeys_in_X_File when the last part of the keyname is the same as the value. // eg myPrefixed_keyname has the value @"keyname" // usage (direct) : definePrefixedKeys_in_X_File(prefix_,keyname); // usage (indirect) : myKeyDefiner(definePrefixedKeys_in_X_File); #define definePrefixedKeys_in_h_File_2(prefix,key) defineKeyValuesIn_h_File(prefix##key,@#key) #define definePrefixedKeys_in_m_File_2(prefix,key) defineKeyValuesIn_m_File(prefix##key,@#key) #define definePrefixedKeys_in_h_File_3(prefix,key,NSObject) definePrefixedKeys_in_h_File_2(prefix,key) #define definePrefixedKeys_in_m_File_3(prefix,key,NSObject) definePrefixedKeys_in_m_File_2(prefix,key) #define definePrefixedKeys_in_h_File(...) VARARG(definePrefixedKeys_in_h_File_, __VA_ARGS__) #define definePrefixedKeys_in_m_File(...) VARARG(definePrefixedKeys_in_m_File_, __VA_ARGS__) // use definePrefixedKeyValues_in_X_File when the value has no relation to the keyname, but the keyname has a common prefixe // eg myPrefixed_keyname has the value @"bollocks" // usage: definePrefixedKeyValues_in_X_File(prefix_,keyname,@"bollocks"); // usage (indirect) : myKeyDefiner(definePrefixedKeyValues_in_X_File); #define definePrefixedKeyValues_in_h_File(prefix,key,value) defineKeyValuesIn_h_File(prefix##key,value) #define definePrefixedKeyValues_in_m_File(prefix,key,value) defineKeyValuesIn_m_File(prefix##key,value) #define VA_NARGS_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, N, ...) N #define VA_NARGS(...) VA_NARGS_IMPL(X,##__VA_ARGS__, 11, 10,9, 8, 7, 6, 5, 4, 3, 2, 1, 0) #define VARARG_IMPL2(base, count, ...) base##count(__VA_ARGS__) #define VARARG_IMPL(base, count, ...) VARARG_IMPL2(base, count, __VA_ARGS__) #define VARARG(base, ...) VARARG_IMPL(base, VA_NARGS(__VA_ARGS__), __VA_ARGS__) and a usage example that invokes it: #define sw_Logging_defineKeys(defineKeyValue) \ /** start of key list for sw_Logging_ **/\ /**/defineKeyValue(sw_Logging_,log)\ /**/defineKeyValue(sw_Logging_,time)\ /**/defineKeyValue(sw_Logging_,message)\ /**/defineKeyValue(sw_Logging_,object)\ /**/defineKeyValue(sw_Logging_,findCallStack)\ /**/defineKeyValue(sw_Logging_,debugging)\ /**/defineKeyValue(sw_Logging_,callStackSymbols)\ /**/defineKeyValue(sw_Logging_,callStackReturnAddresses)\ /** end of key list for sw_Logging_ **/ sw_Logging_defineKeys(definePrefixedKeys_in_h_File); the last part may be a little difficult to get your head around. the sw_Logging_defineKeys() macro defines a list that takes the name of a macro as it's parameter (defineKeyValue) this is then used to invoke the macro that does the actual definition process. ie, for each item in the list, the macro name passed in is used to define the context ( "header", or "implementation", eg either "h" or "m" file, if you understand the objective c file extensions) whilst this is used for objective c, it is simply plain old c macros, used for a "higher purpose" than possibly Kernighan and Richie ever envisaged. :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7541132", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to get access to system folders when enumerating directories? I am using this code: DirectoryInfo dir = new DirectoryInfo("D:\\"); foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories)) { MessageBox.Show(file.FullName); } I get this error: UnauthorizedAccessException was unhandled Access to the path 'D:\System Volume Information\' is denied. How might I solve this? A: There is no way in .NET to override privileges of the user you are running this code as. There's only 1 option really. Make sure only admin runs this code or you run it under admin account. It is advisable that you either put "try catch" block and handle this exception or before you run the code you check that the user is an administrator: WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); WindowsPrincipal currentPrincipal = new WindowsPrincipal(currentIdentity); if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator)) { DirectoryInfo dir = new DirectoryInfo("D:\\"); foreach (FileInfo file in dir.GetFiles("*.*",SearchOption.AllDirectories)) { MessageBox.Show(file.FullName); } } A: try calling this method putting one more try catch block before calling - this will mean top folder lacks required authorisation: static void RecursiveGetFiles(string path) { DirectoryInfo dir = new DirectoryInfo(path); try { foreach (FileInfo file in dir.GetFiles()) { MessageBox.Show(file.FullName); } } catch (UnauthorizedAccessException) { Console.WriteLine("Access denied to folder: " + path); } foreach (DirectoryInfo lowerDir in dir.GetDirectories()) { try { RecursiveGetFiles(lowerDir.FullName); } catch (UnauthorizedAccessException) { MessageBox.Show("Access denied to folder: " + path); } } } } A: You can manually search the file tree ignoring system directories. // Create a stack of the directories to be processed. Stack<DirectoryInfo> dirstack = new Stack<DirectoryInfo>(); // Add your initial directory to the stack. dirstack.Push(new DirectoryInfo(@"D:\"); // While there are directories on the stack to be processed... while (dirstack.Count > 0) { // Set the current directory and remove it from the stack. DirectoryInfo current = dirstack.Pop(); // Get all the directories in the current directory. foreach (DirectoryInfo d in current.GetDirectories()) { // Only add a directory to the stack if it is not a system directory. if ((d.Attributes & FileAttributes.System) != FileAttributes.System) { dirstack.Push(d); } } // Get all the files in the current directory. foreach (FileInfo f in current.GetFiles()) { // Do whatever you want with the files here. } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7541142", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to group any consecutive numbers or items of a given series I am trying to group any consecutive numbers or items of a given series. all consecutive number 1 is return as a sublist. (defun length1-to-atom (l) (loop for x in l collect (if (= (length x) 1) (car x) x))) (defun group-series (n list) (length1-to-atom (reduce (lambda (item result) (cond ((endp result) (list (list item))) ((and (eql (first (first result)) item) (= n item)) (cons (cons item (first result)) (rest result))) (t (cons (list item) result)))) list :from-end t :initial-value '()))) (group-series 1 '(1 1 2 3 1 1 1 2 2 1 5 6 1 1)) ;=> ((1 1) 2 3 (1 1 1) 2 1 5 6 (1 1)) (group-series 2 '(1 1 2 3 1 1 1 2 2 1 5 6 1 1)) ;=> (1 1 2 3 1 1 1 (2 2) 1 5 6 1 1) can't find any solution for the examples below (group-series '(1 2) '(1 1 2 3 1 1 1 2 1 5 6 1 1)) ;=> ((1 (1 2) 3 1 1 (1 2) 1 5 6 1 1)) or (group-series '(1 2 1) '(1 1 2 3 1 1 1 2 1 5 6 1 1)) ;=> ((1 1 2 3 1 1 (1 2 1) 5 6 1 1)) Any help much appreciated. A: The first case (finding repetitions of a single item) can be solved with the following function: (defun group-series-1 (x list) (let (prev rez) (dolist (elt list) (setf rez (if (and (equal elt x) (equal elt prev)) ;; found consecutive number (cons (cons elt (mklist (car rez))) (cdr rez))) (cons elt (if (and rez (listp (car rez))) ;; finished a series (cons (reverse (car rez)) (cdr rez)) ;; there was no series rez))) prev elt)) (reverse rez))) where: (defun mklist (x) (if (consp x) x (list x))) The second one can be solved with the similar approach, but there will be twice as much code. A: I agree with the comment, that group-series seems to be doing two separate things depending on if the input is a list or an item. If the input is a list (the second case), this seems to meet the spec: (defun group-series (sublst lst) (funcall (alambda (lst res) (if (null lst) res (if (equal (subseq lst 0 (min (length lst) (length sublst))) sublst) (self (nthcdr (length sublst) lst) (nconc res (list sublst))) (self (cdr lst) (nconc res (list (car lst))))))) lst '())) This makes use of Paul Graham's alambda macro (http://lib.store.yahoo.net/lib/paulgraham/onlisp.pdf). Also note that because the anonymous function is a closure (i.e., it has closed over sublst), it can reference sublst without having to pass it around as an additional input variable. A: A number of comments say that this looks like the function is doing two different things, but there's actually a way to unify what it's doing. The trick is to treat the first argument a list designator: list designator n. a designator for a list of objects; that is, an object that denotes a list and that is one of: a non-nil atom (denoting a singleton list whose element is that non-nil atom) or a proper list (denoting itself). With this understanding, we can see group-series as taking a designator for a sublist of list, and returning a list that's like list, except that all consecutive occurrences of the sublist have been collected into a new sublist. E.g., (group-series 1 '(1 2 1 1 2) == (group-series '(1) '(1 2 1 1 2) ;=> ((1) 2 (1 1) 2) (group-series '(1 2) '(1 2 3 4 1 2 1 2 3 4)) ;=> ((1 2) 3 4 (1 2 1 2) 3 4) With that understanding, the two cases become one, and we just need to convert the first argument to the designated list once, at the beginning. Then it's easy to implement group-series like this: (defun group-series (sublist list) (do* ((sublist (if (listp sublist) sublist (list sublist))) (len (length sublist)) (position (search sublist list)) (result '())) ((null position) (nreconc result list)) ;; consume any initial non-sublist prefix from list, and update ;; position to 0, since list then begins with the sublist. (dotimes (i position) (push (pop list) result)) (setf position 0) ;; consume sublists from list into group until the list does not ;; begin with sublist. add the group to the result. Position is ;; left pointing at the next occurrence of sublist. (do ((group '())) ((not (eql 0 position)) (push (nreverse group) result)) (dotimes (i len) (push (pop list) group)) (setf position (search sublist list))))) CL-USER> (group-series 1 '(1 1 2 3 1 1 1 2 2 1 5 6 1 1)) ((1 1) 2 3 (1 1 1) 2 2 (1) 5 6 (1 1)) CL-USER> (group-series 2 '(1 1 2 3 1 1 1 2 2 1 5 6 1 1)) (1 1 (2) 3 1 1 1 (2 2) 1 5 6 1 1) CL-USER> (group-series '(1 2) '(1 1 2 3 1 1 1 2 1 5 6 1 1)) (1 (1 2) 3 1 1 (1 2) 1 5 6 1 1) CL-USER> (group-series '(1 2 1) '(1 1 2 3 1 1 1 2 1 5 6 1 1)) (1 1 2 3 1 1 (1 2 1) 5 6 1 1) CL-USER> (group-series '(a b) '(c a b a b c d e f a b)) (C (A B A B) C D E F (A B))
{ "language": "en", "url": "https://stackoverflow.com/questions/7541144", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: write to specific position in .json file + serilaize size limit issue C# I have a method that retrieves data from a json serialized string and writes it to a .json file using: TextWriter writer = new StreamWriter("~/example.json"); writer2.Write("{\"Names\":" + new JavaScriptSerializer().Serialize(jsonData) + "}"); data(sample): {"People":{"Quantity":"4"}, ,"info" : [{"Name":"John","Age":"22"}, {"Name":"Jack","Age":"56"}, {"Name":"John","Age":"82"},{"Name":"Jack","Age":"95"}] } This works perfectly however the jsonData variable has content that is updated frequently. Instead of always deleting and creating a new example.json when the method is invoked, * *Is there a way to write data only to a specific location in the file? in the above example say to the info section by appending another {"Name":"x","Age":"y"}? My reasoning for this is I ran into an issue when trying to serialize a large amount of data using visual studio in C#. I got "The length of the string exceeds the value set on the maxJsonLength property” error. I tried to increase the max allowed size in the web.config using a few suggested methods in this forum but they never worked. As the file gets larger I feel I may run into the same issue again. Any other alternatives are always welcome. Thanks in advance. A: I am not aware of a JSON serializer that works with chunks of JSON only. You may try using Json.NET which should work with larger data: var data = JsonConvert.SerializeObject(new { Names = jsonData }); File.WriteAllText("example.json", data);
{ "language": "en", "url": "https://stackoverflow.com/questions/7541147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: openGL context in console I'd like to use certain functions of openGL, but nothing related to rendering visual content. Is there way to create it without ANY dependencies (not to windows, nor some package[SDL, SFML, GLUT])? Only libraries allowed are those without external libraries, just like GLEW which I use. A: What you want to do is known in general as off-screen rendering. In theory it is possible perfectly well, however the practical implementation has a lot of caveats. Most importantly on all major high performance implementations: Even if no rendering window is visible you still need the graphics system running and being active and your program run in the environment of this graphics system. On Windows the most straightforward way to go is creating invisible window, just a window you create with CreateWindowEx but not map with ShowWindow; you don't even need a event processing loop for that. In this window you create your OpenGL context as usual, but instead of rendering to the window framebuffer, you render to a Frame Buffer Object. On X11/GLX it's even more straightforward: X11/GLX offers PBuffers without extensions (Windows has PBuffers, too, but for creating one you need a regular OpenGL context first). So on X11 you can create a PBuffer without a proxy window. The PBuffer iteself can be rendered to as off-screen buffer; Frame Buffer Object work in a PBuffer, as well, if the implementation supports them. Using a invisible window with a Frame Buffer Object, just like with Windows, works as well. Either way, with current drivers X11 must be active and the bound console, so you can not start an additional X server in the background and have your off-screen rendering happen there, but this is just a limitation of the drivers and not of X11, GLX or OpenGL. Only libraries allowed are those without external libraries, just like GLEW which I use. You can link GLEW statically to your program. If you're hardcore you can do extension loading manually, but why would you want to do that? A: What is the lightest cross-platform library that can staticaly link and can create context. How do you define "lightest?" The two cross-platform libraries that do the least other than creating OpenGL windows are FreeGLUT and GLFW. FreeGLUT has about a 5.2MB distribution (after unzipping), while GLFW has a 2.6MB distro. Does that make it "lighter"? FreeGLUT's compiled static library, in release mode under VS2008, is around 500KB; the one for GLFW under similar compilation is 120KB. Does that make it "lighter"?
{ "language": "en", "url": "https://stackoverflow.com/questions/7541152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Shared memory in Unix I am creating a Daemon in Unix that will have exclusive access to a serial port "/dev/tty01". I am planning to create a Master - Slave process paradigm where there is one master (the daemon) and multiple slaves. I was thinking of having a structure in "Shared memory" where the slaves can access, and there is only one writer to the memory so I most likely wont need a semaphore. The data will be updated fairly slowly, once every minute for example. I was looking into what would be the best possible way to do this, also if I have a structure in shared memory, how can I guarantee that the structure will be contiguous in memory? It is a requirement I must have. thank you A: Shared memory will be hard in this case, because you'll need to lock out the readers when the master is writing, and keep the writer waiting when there still are readers. Easier would be to have the master to write to a temp file (in the same directory) and rename it to the final name once ready (rename is atomic). This assumes the client to periodically open() and fstat() the file to check if it was touched since the previous read. Yet another way would be to avoid files, and let the master just maintain its own internal data structures and have a (listen) socket open, which on open() just spits out all the data it currently has. No locking needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: rails rspec controller test ActionController::RoutingError My routes looks like this resources :stores, :except => [:destroy] do resources :toys, :member => {:destroy => :delete} end my objects controller spec look like this require 'spec_helper' describe ToysController do describe "GET index" do it "assigns all toys as @toys" do toy11 = Factory(:toy, :is_shiny => true) toy12 = Factory(:toy,:is_shiny => false) get :index assigns(:toys).should eq([toy12,toy11 ]) end end end end I got the following error Failure/Error: get :index ActionController::RoutingError: No route matches {:controller=>"toys"} Since the toys resource is nested under stores resources its not able to get toys_path route so i think so the spec is failing. How do i pass the spec? Thanks A: The error is due to not sending store_id to tyos index. Had i sent :store_id => @store.id in get :index it would have passed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541157", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Comparing datetime 24hs to AM/PM format with Entity Framework I am new with Entity Framework. I am having problems comparing datetime values since in my SQL Server database the datetime values are stored as 24hs format and the application is taking the time format as A.M./P.M. format. I tried to parse the fields but I get the error message: The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.> Here is what I tried: (this returns true or false if there are any record found) <pre><code> return !(DB.Eventos.Where( x => (x.Fecha_inicio_evento.Date >= eventos.Fecha_inicio_evento.Date && x.Fecha_inicio_evento.TimeOfDay >= eventos.Fecha_inicio_evento.TimeOfDay && x.Fecha_inicio_evento.Date <= eventos.Fecha_fin_evento.Date && x.Fecha_inicio_evento.TimeOfDay <= eventos.Fecha_fin_evento.TimeOfDay) || (x.Fecha_fin_evento.Date >= eventos.Fecha_inicio_evento.Date && x.Fecha_fin_evento.TimeOfDay >= eventos.Fecha_fin_evento.TimeOfDay && x.Fecha_fin_evento.Date <= eventos.Fecha_fin_evento.Date && x.Fecha_fin_evento.TimeOfDay <= eventos.Fecha_fin_evento.TimeOfDay )).Any()); </code></pre> Do you know any way to perform that? A: Database or .Net does not store date in format. Format is only description for methods like ToString how to do the task. So comparison can be done standard way with operator. Error you're getting is connected with translation Linq query to sql by entity framework, simply Date isn't upported. If by splitting comparison to 2 parts you wanted to compare the dates its not correct. Id .Date is higher comparison of the .TimeofDay shouldn't change result but it does. Chech result with Fecha_inicio_evento = 2011-01-02 01:01:01 and Fecha_inicio_evento = 2011-01-01 02:01:01
{ "language": "en", "url": "https://stackoverflow.com/questions/7541158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to remove the delay of UIButton's highlighted state inside a UIScrollView? I have noticed a slight delay on the highlighted state of a UIButton when touched down if it is inside a UIScrollView (or a table view). Otherwise, the highlighted state is pretty much instantaneous. I surmise this must be by-design to provide a chance for user to scroll. But it just seems like the button is unresponsive to me. Is there a way to fix this? A: Indeed, it's a design choice. It needs this small time to differentiate a scroll (panGesture) from a tap. If you eliminate this delay, then the user won't be able to scroll if he places the finger on top of the button, which is not good user experience. Because a scroll view has no scroll bars, it must know whether a touch signals an intent to scroll versus an intent to track a subview in the content. To make this determination, it temporarily intercepts a touch-down event by starting a timer and, before the timer fires, seeing if the touching finger makes any movement. If the timer fires without a significant change in position, the scroll view sends tracking events to the touched subview of the content view. from the UIScrollView Documentation I wouldn't recommend disabling the delay, but if you insist, you can set it in interface builder (select the Scroll View, and on the right panel, right under "Bounces Zoom"), or using this code: scrollView.delaysContentTouches = false
{ "language": "en", "url": "https://stackoverflow.com/questions/7541159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: JQuery SVG and font coloring How do I change the color of text using JQuery SVG? I currently have the following code: <html> <!-- jquery imports here --> <script type="text/javascript" charset="utf-8"> $(function() { $('#myContainer').svg({}); var svg = $('#myContainer').svg('get'); svg.text(200, 200, "SomeText", {'font-family':"Verdana", 'font-size':20, 'text-anchor':"middle"}); }); window.onload = function () { // more code } </script> <body> <div id="myContainer" style="width: 640px; height: 480px;"></div> </body> </html> A: Try to change fill. {'text-anchor':"middle", 'fill':"#00ff00"}
{ "language": "en", "url": "https://stackoverflow.com/questions/7541167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem about common class first of all, sorry for title, but is very hard explain good in few words. Then il problem is this. I have two class(object): Tclass1 and Tclass2. These are indipendent from them and both classes(objects) call a third class(object): for example Tclass3. As i can share info of Tclass3 between Tclass1 and Tclass2? Try to explain better with a example: Tclass1 = class private class3: Tclass3; public property err: Tclass3 read class3 write class3; ... end; Tclass2 = class private class3: Tclass3; public property err: Tclass3 read class3 write class3; ... end; Tclass3 = class private icode: word; public property code: word read icode; ... end; and main program is: var class1: Tclass1; class2: Tclass2; begin class1 := Tclass1.create; try class2 := Tclass2.create; try class2.err := class1.err; // <--- problem is here ... ... // processing... ... class1.err := class2.err; // <--- problem is here writeln (class1.err.code) finally class2.free; end; finally class1.free; end; end; of course, in Tclass1 and Tclass2 i call create method of Tclass3 and instance it. Now when i run it, make a exception, but i can't read it becouse console is closed fastly. I have applied to a class(object) same rules of a variable; infact if i use a variable to place of it, all work fine. Not is possible solve same with class(object)? Thanks again very much. A: Your question is a bit vague. But let me try to understand. * *You have two classes, that own an instance of a third class. (They are responsible for creating and deleting the class). *You want to share information (but not the class itself) between the two classes. In that case, you could create an Assign method that copys the fields of one object to another object: Tclass3 = class private icode: word; public procedure Assign(const AValue: TClass3); virtual; property code: word read icode; ... end; procedure TClass3.Assign(const AValue: TClass3); begin Assert(AValue<>nil); icode := AValue.icode; end; If you want to share the same object between the two, you need to decide which of the classes owns the object. (Or you could even create a separate owner). But a better solution would be to use an interface to TClass3, so you could take advantage of reference counting. A: "Now when i run it, make a exception, but i can't read it becouse console is closed fastly." You can solve that problem as follows: In the .dpr file of your console application you probably have something like this: begin try // do stuff except on e:Exception do writeln(e.message); end; end. Just change it into this: begin try // do stuff except on e:Exception do begin // show error, and wait for user to press a key writeln(e.message); readln; end; end; end. That should make debugging a bit easier.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Trouble Setting Up SSH Keys for Git in Mac OS X Lion I'm following the instructions on Github for installing the SSH Keys, but after I enter the passphrase twice, I keep getting this message in the terminal, "open .../.ssh/id_rsa failed: No such file or directory." Is this a permissions thing or something? I'm trying to do this from my company user account and not my admin account. A: I did an ssh-add after step 3 to store the key locally, it is required before pushing anything to git. Solved it for Mac OSX 10.7 Lion. A: I had the same problem, to resolve I just took the default suggestion for the .ssh folder and i changed my passphrase to a one word passphrase (no spaces). This worked for me, I didn;t have to mess with permissions or anything. Hope you get it sorted.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: image servlet in the spring setup I have a application set up with Spring and Struts. I am trying to display an image in the jsp using the servlet. In the servlet i need to fetch the image to be displayed from the db for which dao is required. To create the dao bean defined in the application context i used springContext. But i am not able to get the concrete instance of the DAO, instead proxy object gets returned. I am using the following code to get the DAO instance WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); Dao dao = (Dao)springContext.getBean("dao"); applicationContext file <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd"> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> <bean id="dao" class="org.dao.impl.DaoImpl" /> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="database" value="MYSQL" /> <property name="showSql" value="true" /> </bean> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost/xyz" /> <property name="username" value="abc" /> <property name="password" value="abc" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" /> </beans>
{ "language": "en", "url": "https://stackoverflow.com/questions/7541182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting the background color of an NSView I want to set a custom view (not the main one) with a custom NSColor background ([NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]). I've tried making a custom view class: .h #import <AppKit/AppKit.h> @interface CustomBackground : NSView { NSColor *background; } @property(retain) NSColor *background; @end .m #import "CustomBackground.h" @implementation CustomBackground @synthesize background; - (void)drawRect:(NSRect)rect { [background set]; NSRectFill([self bounds]); } - (void)changeColor:(NSColor*) aColor { background = aColor; [aColor retain]; } @end And then in the AppDelegate: [self.homeView changeColor:[NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]]; But nothing happens, the color remains the same. What's wrong? Or is there an easier way? NSView doesn't have a backgroundColor property :( A: Try [self.homeView setWantsLayer:YES]; self.homeView.layer.backgroundColor = [NSColor redColor].CGColor; A: It's best to use the already-made setBackground: method that you get from the background property. So replace your changeColor: method with: -(void)setBackground:(NSColor *)aColor { if([background isEqual:aColor]) return; [background release]; background = [aColor retain]; //This is the most crucial thing you're missing: make the view redraw itself [self setNeedsDisplay:YES]; } To change the color of your view, you can simply do: self.homeView.background = [NSColor colorWithPatternImage:[NSImage imageNamed:@"pattern.png"]]
{ "language": "en", "url": "https://stackoverflow.com/questions/7541183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Two-way beautifier integration with Mercurial We have a very diverse team of developers. Each developer prefers a very different source code indentation and formatting style. Beautifier/pretty printer tools exist that can output in each of these developers' preferred styles. Our code is stored in a Mercurial repository in a standard formatting style, using a commit hook. However, I would like to go a bit further. Is it possible to beautify the source code into the developer's preferred style when he clones/pulls/updates his workspace? That way, he would see all code in his preferred style. When he/she commits the code gets beautified back into the standard formatting style of the central repository. Is there a hook I can use to beautify files before being updated/checked out? How would that work during merging? Can the others files we are merging against also be beautified using a chosen style (as to minimize the amount of conflicts)? A: One possible way (in theory) to implement that would be through encode/decode filters, but I don't think it is worth it, because of all the potential side-effects. It is best to have some kind of format reinforcement in a centralized place, reject any push to a centralized repo if said centralized repo detects code incorrectly formatted. That reminds the coder to use the "official" (and unique) code format in place for the current project.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Transformations seem to work improperly Ok, so I have a weird problem with OpenGL in landscape mode on iOS. From what I've read on the internet I have to rotate the scene myself, so I did that like this: void GameViewController::onSurfaceChanged(int width, int height) { float aspect = (float)width / (float)height; float fovy = 90.0f; glMatrixMode(GL_PROJECTION); float xmin, xmax, ymin, ymax; ymax = 0.01f * Math::tan(fovy * 3.1415f / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glViewport(0, 0, width, height); glLoadIdentity(); glRotatef(-90.0f, 0.0f, 0.0f, 1.0f); glFrustumf(xmin, xmax, ymin, ymax, 0.01f, 320.0f); } My center of my camera isn't the center of the screen now though. So I reset all matrices (projection, modelview) so they are all identity, and then I drew a unit circle on the screen. Now I see what's going wrong, not all coordinates from -1 to 1 are actually on my screen! Here is a screenshot to show what I mean: Now my question: what could possibly cause this? EDIT: after some more investigation i found that in this obj-c method: -(void)setupView:(GLView*)view { CGRect rect = view.bounds; glViewport(0, 0, rect.size.width, rect.size.height); gameView->onSurfaceCreated(); gameView->onSurfaceChanged(rect.size.width, rect.size.height); view.multipleTouchEnabled = YES; } the view's size suddenly turned out to be 1216*1568. The problem is probably there. Manually passing 768 * 1024 to onSurfaceChanged gives me even weirder results. A: Seems like there was an error in the template I was using. Using the default Open GL ES template way of creating a context gives me the proper 1024*768 screen size. Problem fixed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: just can add limited dynamically user control in updatepanel Sorry for my language problem :D I've written below code and I have no problem with that but I can add more than 6 user control(DriverInfo.ascx) dynamically. I've tried a simpler code with a single textbox instead of user control but it does not work for more than 30 textbox. I don't know whats the problem and got confused. what is the problem? AddDynamicDriver.ascx: <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddDynamicDirver.ascx.cs" Inherits="Terminal.UI.TransportCo.WebControls.AddDynamicDirver" %> <div dir="rtl"> <asp:UpdatePanel ID="UpdatePanel" runat="server" UpdateMode="Conditional"> <ContentTemplate> <asp:Panel ID="Panelmain" runat="server"> </asp:Panel> <asp:Button ID="AddDriver" runat="server" Text="adddriver" onclick="AddDriver_Click" /> </ContentTemplate> </asp:UpdatePanel> </div> addDynamicDriver.ascx.cs: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["DynamicDriverNumber"] = 1; LoadCreatedControl(); } } private void LoadCreatedControl() { var number = (int)Session["DynamicDriverNumber"]; for (int i = 1; i <= number; i++) { var driver = new Control(); driver = LoadControl("DriverInfo.ascx"); driver.ID = "Driver" + i; Panelmain.Controls.Add(driver); Panelmain.Controls.Add(new LiteralControl("<hr/>")); } public void AddDriver_Click(object sender, EventArgs e) { var number = (int)Session["DynamicDriverNumber"]; number++; Session["DynamicDriverNumber"] = number; LoadCreatedControl(); } It's a Firefox problem as it works in IE. Why?! A: You need to invoke Update() method after the content of UpdatePanel is modified by the postback event handlers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: is it possible to make a div width auto BUT now more than x pixels/inches? in CSS I was just wondering if it's possible to give a div a width of auto (expandable) but also not allow it to expand more then x amount of pixels? A: Yep, you can use the style, max-width div { width: auto; max-width: 100px; } A: You can use max-width: http://jsfiddle.net/CssJJ/ Be aware that certain version of IE don't support this (would have to look up which) and some I believe require a strict doctype. A: max-width: %/px/em/vh/vw,etc... Also if you put max-width: 100% on an image element, the image scales to fit its parent container. Ie. Responsive images
{ "language": "en", "url": "https://stackoverflow.com/questions/7541196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to read information from shared memory in Java? Is it possible (and if yes - how) to read information from a Shared Memory on Widows system? I would like to get details from a Shared Memory block, created by Core Temp program, as described here A: You will need to create a JNI module. There is no standard Java means of accessing Windows shared memory.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Escape HTML in markdown in HAML Is it possible, in Rails 3.1, to escape HTML in markdown in HAML to avoid XSS? I mean when you do something like: :markdown Hello #{@user.name} Thanks. A: For now I created this: module Haml::Filters::SafeMarkdown include Haml::Filters::Base lazy_require "rdiscount", "peg_markdown", "maruku", "bluecloth" def render(text) engine = case @required when "rdiscount" ::RDiscount when "peg_markdown" ::PEGMarkdown when "maruku" ::Maruku when "bluecloth" ::BlueCloth end engine.new(Haml::Helpers.html_escape(text)).to_html end end and to make it easy to use it directly: module SafeMarkdown def self.render(text) Haml::Filters.defined["safemarkdown"].render(text).html_safe end end It seems to work for now. Does anybody have a comment?
{ "language": "en", "url": "https://stackoverflow.com/questions/7541208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Knowing the genre for a certain artist using freebase I am new at freebase , I just need to get the genre for a certain artist using MQL Thanks A: This will give you the first 100 musical artists with their name, genres, and Freebase IDs. [{ "type":"/music/artist", "id":null, "name":null "genre":[], }]​ To get the genres for a given artist, just specify the ID instead of leaving it blank. Note that an artist can have multiple genres, so you need to query it using array syntax. The default return property is the name. If you'd prefer the ID or ID and name, just specify that in the query using this syntax: 'genre':[{'id':null,'name':null}] you could even get fancy and fetch the parent genres too using 'genre':[{'id':null,'name':null,'parent_genre':[]}] although the genre hierarchy is pretty noisy and not too well curated. A: [{ "type":"/music/artist", "id":null, "name":null "genre":[], }]​ this should give you what you want.You should substitute the name of the artist or the id to get the result. Since you are new ,you can look at the following as a start https://github.com/narphorium/freebase-java-api
{ "language": "en", "url": "https://stackoverflow.com/questions/7541210", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Writing jquery static util methods I understand the concept of extending the jquery.fn to place your custom functions on the prototype chain of a jquery object, but in my case some of my utils don't need to be attached to a selector. I'm basically looking for a static method. So I wanted to know of any pitfalls of writing static methods directly on the jquery object as util methods. Example: jquery.myMethod = function(arg){ ...... } $.myMethod("blabla"); Thanks A: You shouldn't add static methods to jQuery. You don't gain anything by trying to. The point of extending jQuery is so that jQuery objects found with query strings will have methods on them. You're simply creating a global function, so just create a new top-level object to hold your functions. A: As you seem to realize, it is a good idea to not dump all your utility functions into the global namespace. The less you can impact the global namespace, the better. If you already have jQuery, then your choices for where to put them are: * *As new methods on the jQuery object as: jQuery.myUtil1(), jQuery.myUtil2(). *As new methods under one object on the jQuery object as: jQuery.jfUtils.myUtil1(), jQuery.jfUtils.myUtil2(). *As new methods on one new global object (nothing to do with jQuery) as: jfUtils.myUtil1(), jfUtils.myUtil2(). Option 2) seems better to me than option 1) because you lessen the chance of colliding with other jQuery functions though you do add an extra lookup for each function call. Option 3) seems perfectly acceptable to me as it only adds one new item to the global namespace so as long as you make the name reasonably unique, you should be OK. So, I'd think you could go with either option 2) or option 3). Option 2) might be a little safer because you know the general extent of what is in that namespace, but either can work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: HTML within JSON HTML within JSON I know its not the done thing and should be avoided so hopefully someone can give me some tips here. I am running server side checks which return JSON. The server returns a code to determine what type of MessageBox to show (0: YESNO, 1:OK etc.,). Dependent on the server query, I want to prompt the user within msg.show to display data which can be formatted in different ways, it could be a simple line of text or it could be more complex, I don't know up front. The way I had done this in the past was simply to use an AJAX call and render the response which was formatted with HTML (allowing me to construct complex tables and master/detail tables) and render the HTML within a div with overflow:auto. I want to use JSON which provides a good construct for other aspects like success/fail, my problem is that the data is returned but the overflow is not working, the messagebox increases in height beyond the screen and screws up the whole screen layout. I know I am not using this correctly and wondered if there was either: a) a preferred method for structuring data returned to display b) a way of encoding the HTML to allow it to be passed within the JSON I am really looking for any pointers to the most suitable method of approaching this. Sample JSON (could be hundreds of rows): ({ 'success': 'true', 'msgType': '1', 'msg': '<b>The following will be deleted if you continue: </B><table class="x-grid3-body"><tr class="x-grid3-header"><th class="x-grid3-hd-inner" style="width:60px;">Site</Th><th class="x-grid3-hd-inner">Site Name</th></tr><tr><td colspan="2"><div style="overflow:auto; height: 300;"><table><tr class="x-grid3-locked"><td class="x-grid3-hd-inner" style="width:30px;"><b>1936</b></td><td class="x-grid3-hd-inner"><b>Entity Name</b></td></tr><tr><td></td><td><table><tr class="x-grid3-header"><td class="x-grid3-hd-inner">ID</td><td class="x-grid3-hd-inner">First Name</td><td class="x-grid3-hd-inner">Last Name</td><td class="x-grid3-hd-inner">DOB</td></tr><tr class="x-grid3-locked"><td class="x-grid3-hd-inner">15145</td><td class="x-grid3-hd-inner">John</td><td class="x-grid3-hd-inner">Smith</td><td class="x-grid3-hd-inner">01\u002F06\u002F1931</td><td class="x-grid3-hd-inner" align="right"></td></tr></table></td></tr></table></div></td></tr></table>' }) A: It is wrong conceptually (but not technically) to return markup in JSON responses. By having markup defined in two different places - client code and server code - is just asking for maintenance problems in future. Instead I would suggest to use one of template engines available and so your message box will be defined by template <script id="confirm-msg" type="text/template"> <b>The following will be deleted if you continue:</b> <table> {{records}} ... {{/records}} </table> </script> And your JSON will look like: { "success": true, "msgType": 1, "msgTemplate": "confirm-msg", "records": [....] } In this case person who will style all this will have clear vision of what styles to apply and where. A: Passing a string of HTML in a JSON object should work fine, provided that you're careful about quotation marks and special characters. Your overflow problem sounds like it's more a CSS or layout issue than a data transfer question, and without seeing that code it's tough to help. Generally speaking, it's usually a good idea to keep all layout-specific markup IN your html file (or php template, or whatever), and pass as little data as possible through your net requests. That said, another approach would be to keep the HTML for your table in your DOM (hidden) before you make the request, complete with css and styles and all that, and simply populate it with data coming from your ajax request. You could extend the schema of your msg object to include whatever fields you need to populate like msg_header, and then have subsequent row objects that you iterate through and create trs and tds accordingly. Also, make sure to use .html() instead of .text(), for example: $("#container").html(jsonObject.msg) If you run into encoding issues, you can look into escape and unescape, but it's difficult to recommend specifics without seeing a specific encoding problem first. Good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Best Practice: Multiple Forms Is it considered best practice to have multiple forms in an HTML document when each of those forms performs a different action? Here's what I'm doing: I am making a search page that will query my database with several differently formulated SQL queries. This page has three types of search, and each type of search has a simple and an advanced mode. At present, I use javascript to hide all of the forms except the one that is active, and I keep each mode of a search separate from each other in their own forms because I handle them differently. When the search button is clicked, the results of the search will be posted on the same page below the search forms. So, is it generally considered to be best practice that one would do this with multiple forms (which makes it easier and more modular in it's structure) or should I simply hide and un-hide elements inside of one complex form? A: Is it considered best practice to have multiple forms in an HTML document when each of those forms performs a different action? answer: Only if those forms go to separate URLs. Here's what I'm doing: I am making a search page that will query my database with several differently formulated SQL queries. This page has three types of search, and each type of search has a simple and an advanced mode. At present, I use javascript to hide all of the forms except the one that is active, and I keep each mode of a search separate from each other in their own forms because I handle them differently. When the search button is clicked, the results of the search will be posted on the same page below the search forms. Possible example of repeated code, from your vague description: <form id="search-type-1" action="/search-engine" method="post"> <input type="checkbox" name="advanced-mode" /> - Advanced <input type="text" name="query" /> <div class="options"> Put advanced options here. </div> </form> <button id="submit-button">Search</button> <div id="search-ouput"></div> So, is it generally considered to be best practice that one would do this with multiple forms (which makes it easier and more modular in it's structure) or should I simply hide and un-hide elements inside of one complex form? Answer: This seems overly complex. I would say this is NOT best practice. With more info, I'm sure someone could show you a much better way. A: It is considered best practice to present forms on the page such that their purpose is intuitively obvious, they are easy for the visitor to use, they have good affordance, and (imo) they look well on the page. This question invites lots of contradictory opinions, but it could be (yeah, surrrrrre!) that everyone can agree on those four points at least. Lots of folks can say "well, it's better to float this left" or "use a <ul> here" or "why position:fixed;?" IMO, these concerns are all way, way less important than the visitor's reaction to the finished page.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Storing Javascript objects in Java I have a Java object, and in it exists a spatial shape defined by a String of "well-known text". On mouseover of this object in my GWT UI, my code passes this String to Javascript through JSNI, which in turn does a bunch of parsing and creates appropriate Bing Maps API shapes. A simplified example of this would be a map application where each state exists as an object containing the states name and a string defining its perimeter. On mouseover of the states name in my UI, the perimeter string is parsed and a representative shape drawn on the map. So right now, my code does the passing, parsing, and creating every time the user mouses-over my object. I'm looking for a way to parse the strings and create the objects only once each, hopefully storing the full, already created Javascript objects (Bing Maps shapes) in the original Java objects themselves. This, I think, should surely speed things up - the UI starts to look laggy when it has to parse and create several very detailed map objects every time the user moves the mouse to a different item. Is it possible to store Javascript objects of this nature in my Java objects, and then bring them back to Javascript whenever I need them? In my Java code (GWT), I can create a JavascriptObject, but is this sufficient for holding something like a Microsoft.Maps.Polygon object? Thanks! A: Why not just cache them in javascript? Once you've created an object in the Javascript, store it in a cache object with the string as the key. Then, whenever you get a request for a new object, you check the cache and use the pre-created one if there is one. If there isn't a pre-created one, you create it and add it to the cache. If you want to pre-create a number of objects, you could have the java just call the javascript with a bunch of strings for which it would pre-populate the cache with. This keeps all the Javascript objects on the Javascript side of the fence and all the Java objects on their site of the fence, yet should still help with the performance. This is the general idea in pseudo-code: var cache = {}; function createJSObject(stringArgument) { if (stringArgument in cache) { return(cache[stringArgument]); } var obj; // create the object here // ... // cache the object we created cache[stringArgument] = obj; return(obj); } A: You can very well have a field in your class, or a variable of type JavaScriptObject to store any object coming from JS. GWT does just that in a few places already: for instance in com.google.gwt.xml.client.impl.DOMItem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541227", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Web Application Error: Sequence contains more than one element I have a web application that was working fine but does not work anymore. It even works on my development computer (hooked up to a local database), but not on production. So on my development computer, I change the connection string to hit the production database and I get the Error: Sequence contains more than one element. I believe it has to have something to do with the database, but I don't know how to figure out what it is, there are almost a thousand rows of data in it. Below is the linq statement that gets the data. Any ideas on how I can fix this? Thanks in advance protected void lnqItems_Selecting(object sender, LinqDataSourceSelectEventArgs e) { DocksideValidationDataContext db = new DocksideValidationDataContext(); DateTime startDate = (radStartDate.SelectedDate.HasValue) ? radStartDate.SelectedDate.Value : DateTime.Parse("1/1/1900"); DateTime endDate = (radEndDate.SelectedDate.HasValue) ? radEndDate.SelectedDate.Value : DateTime.Parse("1/1/2500"); int prevalNum = (txtSummaryFormNumber.Text.Trim() == "") ? -1 : Convert.ToInt32(txtSummaryFormNumber.Text.Trim()); e.Result = (from x in db.SummaryForms where (x.SummaryFormId == prevalNum || (prevalNum == -1) && (x.SampleDate >= startDate.Date) && (x.SampleDate <= endDate.Date) && (x.StateId == Convert.ToInt32(ddlState.SelectedValue))) orderby (x.SampleDate) descending select x).AsEnumerable() .Select(x => new { x.SummaryFormId, x.SampleDate, DockName = x.Dock.Code + " " + x.Dock.Name, Status = GetStatus(x), Color = GetStatusColor(GetStatus(x)) }) .Where(x => ((prevalNum != -1 || cboFilter.Text == "All") || (x.Status == cboFilter.Text))); } No it occurred to me, but I didn't think it would be usefully. Here is it: System.InvalidOperationException: Sequence contains more than one element Generated: Sat, 24 Sep 2011 15:57:41 GMT System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: Sequence contains more than one element at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source) at System.Data.Linq.EntityRef`1.get_Entity() at Secure_SummaryForms.<GetStatus>b__4(SummaryFormVessel z) at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext() at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source) at Secure_SummaryForms.GetStatus(SummaryForm x) at Secure_SummaryForms.<lnqItems_Selecting>b__0(SummaryForm x) at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext() at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) --- End of inner exception stack trace --- at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.Web.UI.WebControls.QueryableDataSourceHelper.ToList(IQueryable query, Type dataObjectType) at System.Web.UI.WebControls.LinqDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) at System.Web.UI.WebControls.DataBoundControl.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at System.Web.UI.WebControls.GridView.DataBind() at System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound() at System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() at System.Web.UI.Control.EnsureChildControls() at System.Web.UI.WebControls.GridView.get_Rows() at Secure_SummaryForms.Page_Load(Object sender, EventArgs e) at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.secure_summaryforms_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Server Variables Name Value ALL_HTTP HTTP_CONNECTION:keep-alive HTTP_ACCEPT:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 HTTP_ACCEPT_CHARSET:ISO-8859-1,utf-8;q=0.7,*;q=0.7 HTTP_ACCEPT_ENCODING:gzip, deflate HTTP_ACCEPT_LANGUAGE:en-us,en;q=0.5 HTTP_COOKIE:ASP.NET_SessionId=yka231rdr1r3yqv0nmbhz1nh; .POWERBASECOOKIE=5FC2CF98E578B444ACA6B75A382EAEF31EFC781DA11AF7884B360A82E544539BEC5E5BB62DD012A1D6E7005869FFF8A205D632FB724AB01EFDBED78A9A035C76B22250F8FF0BCC3AD9AB56C4EEC44C05159110DF95A6344888CB3300B642E312F3B152475CD4FA631C0000699763AE173978375D598154CE85AEF83C81E1FAF82842DF48F1D9AC97872F09FFCA33B22B; .ASPXROLES=IS-YIxYt7iXk72HXdLNE18SBwgsEd2wo3D4GfRI72jYdSmmLhUxfzBMMpFYXg5CjiowldcwSKolBjaP8jrMUgh5-rQWjQhUTY02VS3IhD5Xcav_B-d-MiaumYD-0JMWFR9-1xcP2eHQXLpnZlXzcZXhwh6G2mEDVoNZGls8MNK8bAVlo2WuTqReMmk1GTyu5duoZzh_fCs1S6AZuhWY9bwdi28kA_lfoyp4SCm2zLgNddjhbsLmgN5oopdPo9-oONS7Z5br51qYu5sS9vq-hm_TbHhHL_W7XbIKo3pJccZ1-VXkLbtIAiS_hSccjFmk1f3ttWhUnmULJVQaNNepOHofbivSEQvhQQxX-f5hpGI4K-9FqcJ-kFAjw93CrnZ2rtu6n8i3tblPEDQeAbd1JkSJjmKGpSH_4PVh1MsXNDZwSSnbBHqTaO9iKiVAvUWvANLbBxmOc3w0SfP4DUbLtl3YZVCbG_JWr5s0f5Is8scr7Nc-AxK2HEzjNVber1EofJK48eLaVJPyvm-858Yhtp5XgqMeJQUwh5l9LYeZNbc8kqxPG7kOl0Zq7q8407I230 HTTP_HOST:docksidevalidation.org HTTP_REFERER:http://docksidevalidation.org/secure/default.aspx HTTP_USER_AGENT:Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 ALL_RAW Connection: keep-alive Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Accept-Encoding: gzip, deflate Accept-Language: en-us,en;q=0.5 Cookie: ASP.NET_SessionId=yka231rdr1r3yqv0nmbhz1nh; .POWERBASECOOKIE=5FC2CF98E578B444ACA6B75A382EAEF31EFC781DA11AF7884B360A82E544539BEC5E5BB62DD012A1D6E7005869FFF8A205D632FB724AB01EFDBED78A9A035C76B22250F8FF0BCC3AD9AB56C4EEC44C05159110DF95A6344888CB3300B642E312F3B152475CD4FA631C0000699763AE173978375D598154CE85AEF83C81E1FAF82842DF48F1D9AC97872F09FFCA33B22B; .ASPXROLES=IS-YIxYt7iXk72HXdLNE18SBwgsEd2wo3D4GfRI72jYdSmmLhUxfzBMMpFYXg5CjiowldcwSKolBjaP8jrMUgh5-rQWjQhUTY02VS3IhD5Xcav_B-d-MiaumYD-0JMWFR9-1xcP2eHQXLpnZlXzcZXhwh6G2mEDVoNZGls8MNK8bAVlo2WuTqReMmk1GTyu5duoZzh_fCs1S6AZuhWY9bwdi28kA_lfoyp4SCm2zLgNddjhbsLmgN5oopdPo9-oONS7Z5br51qYu5sS9vq-hm_TbHhHL_W7XbIKo3pJccZ1-VXkLbtIAiS_hSccjFmk1f3ttWhUnmULJVQaNNepOHofbivSEQvhQQxX-f5hpGI4K-9FqcJ-kFAjw93CrnZ2rtu6n8i3tblPEDQeAbd1JkSJjmKGpSH_4PVh1MsXNDZwSSnbBHqTaO9iKiVAvUWvANLbBxmOc3w0SfP4DUbLtl3YZVCbG_JWr5s0f5Is8scr7Nc-AxK2HEzjNVber1EofJK48eLaVJPyvm-858Yhtp5XgqMeJQUwh5l9LYeZNbc8kqxPG7kOl0Zq7q8407I230 Host: docksidevalidation.org Referer: http://docksidevalidation.org/secure/default.aspx User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 APPL_MD_PATH /LM/W3SVC/1154673598/Root APPL_PHYSICAL_PATH C:\Inetpub\Websites\DocksideValidation\Website\ AUTH_TYPE Forms AUTH_USER admin AUTH_PASSWORD LOGON_USER REMOTE_USER admin CERT_COOKIE CERT_FLAGS CERT_ISSUER CERT_KEYSIZE CERT_SECRETKEYSIZE CERT_SERIALNUMBER CERT_SERVER_ISSUER CERT_SERVER_SUBJECT CERT_SUBJECT CONTENT_LENGTH 0 CONTENT_TYPE GATEWAY_INTERFACE CGI/1.1 HTTPS off HTTPS_KEYSIZE HTTPS_SECRETKEYSIZE HTTPS_SERVER_ISSUER HTTPS_SERVER_SUBJECT INSTANCE_ID 1154673598 INSTANCE_META_PATH /LM/W3SVC/1154673598 LOCAL_ADDR 192.168.1.131 PATH_INFO /secure/SummaryForms.aspx PATH_TRANSLATED C:\Inetpub\Websites\DocksideValidation\Website\secure\SummaryForms.aspx QUERY_STRING REMOTE_ADDR 66.186.243.74 REMOTE_HOST 66.186.243.74 REMOTE_PORT 50339 REQUEST_METHOD GET SCRIPT_NAME /secure/SummaryForms.aspx SERVER_NAME docksidevalidation.org SERVER_PORT 80 SERVER_PORT_SECURE 0 SERVER_PROTOCOL HTTP/1.1 SERVER_SOFTWARE Microsoft-IIS/6.0 URL /secure/SummaryForms.aspx HTTP_CONNECTION keep-alive HTTP_ACCEPT text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 HTTP_ACCEPT_CHARSET ISO-8859-1,utf-8;q=0.7,*;q=0.7 HTTP_ACCEPT_ENCODING gzip, deflate HTTP_ACCEPT_LANGUAGE en-us,en;q=0.5 HTTP_COOKIE ASP.NET_SessionId=yka231rdr1r3yqv0nmbhz1nh; .POWERBASECOOKIE=5FC2CF98E578B444ACA6B75A382EAEF31EFC781DA11AF7884B360A82E544539BEC5E5BB62DD012A1D6E7005869FFF8A205D632FB724AB01EFDBED78A9A035C76B22250F8FF0BCC3AD9AB56C4EEC44C05159110DF95A6344888CB3300B642E312F3B152475CD4FA631C0000699763AE173978375D598154CE85AEF83C81E1FAF82842DF48F1D9AC97872F09FFCA33B22B; .ASPXROLES=IS-YIxYt7iXk72HXdLNE18SBwgsEd2wo3D4GfRI72jYdSmmLhUxfzBMMpFYXg5CjiowldcwSKolBjaP8jrMUgh5-rQWjQhUTY02VS3IhD5Xcav_B-d-MiaumYD-0JMWFR9-1xcP2eHQXLpnZlXzcZXhwh6G2mEDVoNZGls8MNK8bAVlo2WuTqReMmk1GTyu5duoZzh_fCs1S6AZuhWY9bwdi28kA_lfoyp4SCm2zLgNddjhbsLmgN5oopdPo9-oONS7Z5br51qYu5sS9vq-hm_TbHhHL_W7XbIKo3pJccZ1-VXkLbtIAiS_hSccjFmk1f3ttWhUnmULJVQaNNepOHofbivSEQvhQQxX-f5hpGI4K-9FqcJ-kFAjw93CrnZ2rtu6n8i3tblPEDQeAbd1JkSJjmKGpSH_4PVh1MsXNDZwSSnbBHqTaO9iKiVAvUWvANLbBxmOc3w0SfP4DUbLtl3YZVCbG_JWr5s0f5Is8scr7Nc-AxK2HEzjNVber1EofJK48eLaVJPyvm-858Yhtp5XgqMeJQUwh5l9LYeZNbc8kqxPG7kOl0Zq7q8407I230 HTTP_HOST docksidevalidation.org HTTP_REFERER http://docksidevalidation.org/secure/default.aspx HTTP_USER_AGENT Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2 Powered by ELMAH, version 1.1.11517.2009. Copyright (c) 2004-9, Atif Aziz. All rights reserved. Licensed under Apache License, Version 2.0. A: I have solved the problem! Thanks for your imput. The issue was a duplicate record in the database was inserted and when the program was pulling the data back it was only suppose to pull one record back and it was getting 2. Thanks! A: The exception suggests that the set you are querying with Linq contains multiple items that match your query, and you are calling SingleOrDefault which throws an exception in such a situation. You might be looking to use FirstOrDefault instead which takes the first match of the query. Though it's hard to tell because I don't see a call to SingleOrDefault in your pasted code sample.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Is it possible to get the assets used in iOS built-in controls? Is it possible to get the assets (the PNGs) used in some iOS built-in controls like the slider, switch or stepper? A: You can do this with the UIKit Artwork Extractor which runs in the iOS Simulator and produces a directory with the files on your desktop. A: You may get them with a jailbreaked iPhone, or using an app that lets you access the iPhone filesystem from you Mac/PC, like DiskAid. But you can also find PSD files with all the iOS GUI elements on the web, like: * *http://www.teehanlax.com/blog/iphone-4-gui-psd-retina-display/ *http://www.teehanlax.com/blog/ipad-gui-psd/ Guess this will be easier...
{ "language": "en", "url": "https://stackoverflow.com/questions/7541230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Spotify + Facebook integration - Hitting the pause button on Facebook pauses my native mac client almost instantaneously. How is this done? Just as the question reads. If I goto my FB Activity, it shows the track that's being played and a pause button. If I hit "Pause" it pauses my native spotify app instantaneously. How is this implemented? A: The JavaScript on Facebook's site submits a request to a web service hosted by Spotify. I do believe that Spotify's client-side application maintains a connection with Spotify's servers. Spotify is able to push content to the user without the client making a request for it, so this web service seems to do this. From my research, I can't find that developing similar functionality is feasible via any API method, whether from Spotify or Facebook. A: Spotify embeds a web server with a remote control API that Facebook uses directly. A: Facebook and Spotify have a special partnership. This type of integration is not currently available to other developers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does running a cronjob in shared webhosting (in CPanel) support mod_rewrite'd URLs? I'm currently developing a PHP application where I have SEO friendly URLs, I'm planning on once finished production stage (off localhost) to purchase some shared webhosting and schedule a cronjob for one of the files. Now I'm wondering does the shared webhosting CPanel cronjob scheduler support mod_rewrite'd URLs or will I need to pass the direct file path? A: If you want to run the php script via command line, then You will need to pass the full file path. But if the script can be run via web request then you can use wget to use the URL of the file which will be the SEO friendly one
{ "language": "en", "url": "https://stackoverflow.com/questions/7541241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a "appears in all" (set division?) operation built into MySQL? Sorry for the simple question, but I didn't know the proper way to word it to get useful results. I was wondering if there was a function in MySQL that supports a "has all" relationship. The term that I think I'm referring to is set division (when I look up division in the manual pages, I only see precision mathematical division in MySQL). So, for example, if I had a relation of students and courses, I might want to retrieve a list of courses in which ALL of the students are taking (perhaps, the course ID number appears under each student, or something similar). Does my question make sense? I can come up with a different query to get the job done, but it would be really nice if I could simplify it all with a simple built in function, you know? A: No there isn't. See Divided We Stand: The SQL of Relational Division for a good round up of approaches. The article is SQL Server centric but the same 2 approaches of GROUP BY ... HAVING COUNT or double NOT EXISTS still work. For exact relational division (with no remainder) GROUP_CONCAT could come in handy though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Add route after Application_Start I am working on a site where the user is going to add pages to the site, and I was trying to use routing to immediately have the page available after creation. For example, the user may create an About page, and right now I put some logic in the controller when the page is added. if (ModelState.IsValid) { context.Pages.Add(page); context.SaveChanges(); RouteTable.Routes.MapRoute(page.Name, page.Url, new { controller = "Home", action = "Index", id = UrlParameter.Optional }); return RedirectToAction("Index"); } But when I create the About page with About as the url and then try to go to /About, I get a 404 error. Is it possible to add routes outside of the Application_Start? A: You should avoid defining any routes in controller actions. For your scenario you could define the following route: routes.MapRoute( "Default", "{id}", new { controller = "Home", action = "Index" } ); Now a request of the form /About will be routed to the Index action of the Home controller and passed id=About as argument: public ActionResult Index(string id) { // if the request was /About, id will equal to About here ... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7541245", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mongoose and field types - Number returns object, String returns string? Say you define a Mongoose schema like so aSchema = new Schema count: Number text: String A = mongoose.model "A", aSchema db = mongoose.connect "mongodb://localhost/test" a = new A a.count = 99 a.text = "foo" a.save (err) -> A.findById a, (err, a) -> console.log typeof a.text, typeof a.count #prints string, object Fields of type String behave as expected. But Number fields come back as objects, which means they need to be typecast before being used in comparisons etc. Why do fields of type Number need casting but not fields of type String? A: From one of the authors: https://github.com/LearnBoost/mongoose/issues/338#issuecomment-1092330
{ "language": "en", "url": "https://stackoverflow.com/questions/7541246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: deleteObject deletes but leaves empty rows in the sqlite3 database? I need to delete the selected row of the database shown in updatePick, but can't seem to get the managedObject that's supposed to be in the [context deleteObject:managedObject]; line correct. Here's the deleteUpdate method: -(void)deleteUpdate { NSLog(@"35-Delete pressed."); NSManagedObjectContext *context = [self managedObjectContext]; NSEntityDescription *updateEntity = [NSEntityDescription entityForName:@"Updates" inManagedObjectContext:context]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:updateEntity]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(dateGains = %@)", [arrayNSDateGains objectAtIndex:updatePick]]; [fetchRequest setPredicate:predicate]; NSArray *gains = [context executeFetchRequest:fetchRequest error:nil]; for (updateGains in gains) { [context deleteObject:updateGains]; } [self saveContext]; } This manages to delete the contents of the row in the database (YEAH), except, it leaves an empty row and three residual elements: primary key (Z_PK), and two integers (Z_ENT) & (Z_OPT). The empty row causes errors elsewhere. What am I missing here? A: Core Data often leaves empty rows in sqlite stores after deletes. The documentation explicitly states that the store file will not grow smaller after deletes until at some arbitrary point the persistent store object decides to condense the store. In general looking at the sqlite store itself is a waste of time. Core Data is not SQL. Entities are not tables. Objects are not rows. Attributes are not columns. Relationships are not joins. Core Data is an object graph management system that may or may not persist the object graph and may or may not use SQL far behind the scenes to do so. Trying to think of Core Data in SQL terms will cause you to completely misunderstand Core Data and result in much grief and wasted time. Core Data merely has the option of serializing (freeze drying) object into an sqlite store. However, how it does that is not documented so looking at the sqlite store directly won't tell you much. The only way to confirm that an object has been deleted is to get and save its permenent managedObjectID. After the delete, ask the persistentStoreCoordinator to fetch the object for the id with objectWithID:. If the object has been deleted, it won't find it. There are only a couple of ways in which an object can remain after deletion. The undo manager can roll back apparent deletions but that isn't the case here. If you retain a managed object elsewhere, then the object in memory will remain after the deletion (although it won't show up in Core Data operations like a fetch.) I doubt any problems you are having is caused by an issue with the store. Such issues are very rare. Update: After the save, I do a [self setNeedsDisplay]; which triggers a redrawing of the bar chart based on the data in the database. The first mutable array tries to insertObject:atIndex: a nil object which causes crash… I've inserted a if(dateGained==nil) continue; at the point where the next error had occurred and it works great. Your problem here is that your UI controller is not updating its count of the managed objects after the context deletes some of them. For example: You have a table that displays one Update object per row. At the start the UI controller fetches all the existing Update objects. It tells the table that it has [fetchObjects count]. Then you delete some of the Update objects but then you don't tell the table it has fewer rows now. The table will attempt to access objects in the array past the last element which causes a crash. The solution here is to register your controller for the context's notification: NSManagedObjectContextObjectsDidChangeNotification … and then update the array and the tables row count before you call [self setNeedsDisplay].The table will then understand how many rows it should have. Any UI element that depends on a count of the fetched objects needs to keep in sync with changes in object graph, especially deletes. A: You forgot to fetch the entity. Do this: NSArray *results = [context executeFetchRequest:request error:nil]; if (results) { for (NSManagedObject *updateGains in results) { [context deleteObject:updateGains]; } [context save:nil]; } [self saveContext];
{ "language": "en", "url": "https://stackoverflow.com/questions/7541247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Perforce doesn't know that I have changes to submit I'm new to Perforce. I'm much more comfortable with Git and some Subversion. Anyway, this is what happened: * *I created a branch for myself in p4v located in location A on my machine. *I created a Java project in location B, and copied it into location A on my computer. *I created and submitted a changelist for the Java project. *I realized that I needed to make another change, so I went back to Eclipse and edited the project. But, I forgot that the project in Eclipse is pointing to the one in location B. *So, I copied the project from location B to location A, where the branch is. But now I can't create a changelist for the edits because Perforce thinks that there are no changes to commit. What did I do wrong, how do I fix it, and what are some Perforce best practices to avoid this craziness in the future? A: You need to do p4 edit on the files before you edit them. Normally files are marked as read-only to strongly discourage you from modifying the files without first marking them for edit. The best practice would be not to fight the read-only permissions. A: There is an Eclipse plugin for Perforce. If you install this then you will be able work with the project in Eclipse at location A. If you make an edit to any file or setting Perforce will check the file out automatically and place it in the default changelist. You can then either check it back in from there or use P4V to manage your changelists. As @jamesdlin points out Perforce effectively "owns" the files and you shouldn't make any edits without "asking permission" first by either an explicit p4 edit command or via the IDE plugin. If you've made a change without first checking out the file you can simply make the p4 edit call. This doesn't overwrite the local file, just marks the file as writeable as far as Perforce is concerned. Perforce should then recognise that there's an edit pending and let you check it in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Eclipse OSGi run configuration Is there any way to add OSGi Run configuration to Eclipse Indigo if there's no such section in a templates panel on the left of "Run Configurations" dialog box? A: Download the Eclipse IDE for Java EE Developers package. It looks to me that PDE is required for the OSGi Framework launch configuration which is missing from the Eclipse IDE for Java Developers package. PDE UI also provides comprehensive OSGi tooling, which makes it an ideal environment for component programming, not just Eclipse plug-in development. ... Launchers - test and debug Eclipse applications and OSGi bundles. (From http://www.eclipse.org/pde/pde-ui/) Take a look at this answer too. Installing the PDE plugin through Install New Software also could be a solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541250", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why my CSS does not position my div to the right side of the page? I have a div element which contains the language selection links like below: <head> ... <link rel="stylesheet" type="text/css" href="css/page.css"> </head> <body> <div id="#language"> <a href="#french">French</a> | <a href="#english">English</a> </div> ... ... </body> I try to CSS the position of #language div to the right side of the page by (css/page.css): #language { text-decoration: none; position:absolute; right:0px; } But it does not work, why? A: Remove the # from <div id="#language"> and it should work. Example: http://jsfiddle.net/jasongennaro/83naR/
{ "language": "en", "url": "https://stackoverflow.com/questions/7541251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove default focus from textbox in asp.net using css and javascript I have a login form where the user cicks on the "txtUsername" which is a simple text box then it is highlighted with yellow border by default but I want to remove that. How to do that? As If I manually add some css styles I can change the focus elements of the textbox but it is adding to the previous border which is "yellow".So I need to remove that Any help will be appreciated! Here is my Css code: .onfocus { border: thin groove #3366CC; } .onblur { border:; } Here is the script code: <script type="text/javascript"> function Change(obj, evt) { if (evt.type == "focus") obj.className = "onfocus"; else if (evt.type == "blur") obj.className = "onblur"; } </script> Form Code: <asp:TextBox ID="txtUsername" runat="server" Style="position: absolute; top: 76px; left: 24px; width: 189px; height: 24px;" onfocus="Change(this, event)" onblur="Change(this, event)" BackColor="#FAFFBD"></asp:TextBox> A: Try the following: <style type="text/css"> #element:focus { border: 1px solid red; } </style> <input type="text" id="element" /> Here is a demo: jsFiddle demo
{ "language": "en", "url": "https://stackoverflow.com/questions/7541252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling Multiple Strings And Ints In An Array I am trying to create an app in which I have an array(?) that holds the name and other information(2 strings, 3 ints) of the user. I also want the user to specify how many names the app can hold. I was wondering exactly how would I do this? I was wondering if I can use a multidimensional array. Thanks A: Sounds like what you'd want is a User class, with the properties each user has, and an array of those. A: You can use an NSMutableArray that contains NSDictionaries of the items. NSMutableArray *array = [NSMutableArray array]; NSString *name = @"Name "; NSString *value1 = @"Value 1"; int value2 = 2; NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: name, @"name", value1, @"value1Name", [NSNumber numberWithInt:value2], @"value2Name", nil]; [array addObject: dict]; // Create more dictioaries as there are more items and add them to the array A: As stated previously, your best bet would be to add a class to hold the information and then add each object into an NSArray (Here is an example): @interface User : NSObject { NSString *string1; NSString *string2; int int1; int int2; int int3; } @property (nonatomic, retain) NSString *string1; @property (nonatomic, retain) NSString *string2; @property (nonatomic) int int1; @property (nonatomic) int int2; @property (nonatomic) int int3; @end @implementation User @synthesize string1, string2, int1, int2, int3; // Add init and dealloc methods here @end // creating objects somewhere else in the code User *userObj1 = [[User alloc] init]; User *userObj2 = [[User alloc] init]; userObj1.string1 = @"User1"; userObj1.int1 = 7; NSArray *arrayOfUserObjects = [[NSArray alloc] initWithObjects: userObj1, userObj2, nil]; [userObj1 release]; [userObj2 release]; // do stuff with array with User Objects A: Yeah, either a custom class or a dictionary. Or instead of a dictionary you can have another array, if you prefer. With NSArray you can have any other Objective-C object as elements, including other NSArrays, NSDictionarys, or objects of your own custom class. (You could do the same with an array of NSObject pointers, but NSArray nicely handles retains for you.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7541262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Populating a calendar based on RSS feeds I am trying to build a calendar in php which will display events on my website. My requirement is to populate the calendar with events from different websites, which publish an RSS feeds of their events. In my initial attempt I parsed the events based on the <pubDate> tag and aggregated those in my calendar. However, I soon realized that this doesn't work the way I want it to. The problem lies in the fact that the RSS feeds from different websites are not consistent with each other. For eg. One of the sites published the date for the event in the <pubDate> tag as <pubDate>Mon, 25 Jul 2011 21:11:40 GMT</pubDate>. Another one has it in the <title> tag - as <title>26 Sep 2011 19:00 : The Life of a Lily</title>. One other site has the event date in the <Description> tag as free floating text. I am really in a fix as to how to consolidate these into a single calendar. Can someone please suggest a way I can do this? Or am I left with just cursing how non-standard the feeds are, in-spite of being technically standard? Thanks a lot! A: First you would need to locate and parse out the date portion of the posts. You could do this using regex or with PHP's string functions. Then you could use PHP's strtotime(..) and date(..) to normalize the dates, like this: $date = '26 Sep 2011 19:00'; print date("Y-m-d", strtotime($date)); // prints: 2011-09-26
{ "language": "en", "url": "https://stackoverflow.com/questions/7541266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Serializing XML from Browser DOM doesn't create an XML declaration Okay, so we have a webapp that's communicating with a web-service via XML. As of now we're assembling those XMLs by just hacking Strings together (and sending that via XMLHttpRequest/POST). I'm of a mind to re-factor that into using the facilities for building and serialising an XML DOM tree that are built into the browser, i.e. document.implementation & XMLSerializer().serializeToString(doc) (see Mozilla docs here and here). It's been working fine so far, except the resulting string doesn't contain an XML declaration. So, how's that supposed to work? Any good advice and/or reading? Oh, yeah, I've found this mozilla bug describing the problem and a hacky workaround (the linked thread is available via archive.org). A: Different browsers have different behavior around outputting the xml declarations. Here's been my experience: * *Opera 12.15 on Mac -- XML declaration *Safari 6.0 on Mac -- No declaration *Chrome 26.0 on Mac -- No declaration *Firefox 21.0 on Mac -- No declaration Not sure what IE does. Another noteworthy observation is that there is seemingly no API (that i have found) to turn off the declaration in Opera. As a result, I'd find a better 'hack' than the one that you point to that is aware of if the XML declaration is already there or not. Perhaps a quick string based check if the serialized form contains the declaration would be adequate (e.g if (serialized.slice(0, 21) == "<?xml version=\"1.0\"?>") ... though this isn't a great way to check/ I'd consider alternatives).
{ "language": "en", "url": "https://stackoverflow.com/questions/7541267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to make usercontrol on topmost in wpf? I have a grid which contains three rows. First row contains which show toolbar. Second row contains which shows status bar. Third row contains the Listbox which is data bound to observable collection. When some conditions are met I need to show popup. I thought to use popup, the problem with popup is it will not move with the parent control when I move the window. So I decided to create a user control(say mypopup) which is added in second row with higher ZIndex programmatically, the problem is even if I set the higher index it is going behind the ListboxItems. a) Any solution for this? As a solution I thought to use Adorner for that user control(mypopup), the problem is my user control(mypopup) contains Button and Checkbox, after applying adorner these controls are not accessible. b) Any idea to make my user control interactive with adorner? A: Adorners wont give you interactivity. They are simply drawing based. So they will not react like a user control does unless you "simulate" it. So lets keep them aside for now. Use popups only. Set their placement target and placement orientation. The popup below is placed to the top left corner of a Button. popup.PlacementTarget = MyButton; popup.Placement = PlacementMode.Relative; It moves along the placement target i.e. MyButton. For that I change the margin of the button and accordingly popup moves. For this effect to take place you need to hide the popup and reset its placement target. popup.IsOpen = false; popup.PlacementTarget = null; MyButtonMargin = new Thickness(MyButton.Margin.Left + 10); popup.PlacementTarget = MyButton; popup.IsOpen = true; Let me know if this helps. A: <Window...> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Toolbar Grid.Row="0" ... /> <Statusbar Grid.Row="1" ... /> <ListBox Grid.Row="2" ... /> <OverlayControl Grid.Row="0" Grid.RowSpan="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" /> </Grid> </Window> OverlayControl: <UserControl ...> <Grid Background="#30000000"> <Border HorizontalAlignment="Center" VerticalAlignment="Center" ...> Content, e.g. TextBlock with a message </Border> </Grid> </UserControl> Don't set width on the usercontrol as it should stretch out, use d:DesignWidth/Height if you need to. Order matters, the last one is over others within the same row. Change row and rowspan if you want it only to occupy the 3rd row.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I parse emails in realtime as they are recieved I need to build an email parsing script which would parse emails that would come into an inbox and dump the contents into a database, while at the same time make a curl request with details parsed from the email. At this moment I'm quite stuck on implementing the part on how to parse emails in realtime as they are recieved in the inbox. Is there a way to set triggers to do something like this? I've extensive experience with working with php based webmail clients but this seems different though. How can this be accomplished - I am assuming a cron job but if theres another way to do so I'm all ears. A: Yes, there is. You can pipe emails to your scripts. Assuming you are using cPanel, follow this steps: * *Log in to your cPanel. *Click on the Forwarders icon, under the Mail tab. *Click on the Add Forwarder button. *Fill in Address to Forward and put the mail address you would like to pipe the messages from. *Select Pipe to a Program and fill in the full path to the script which will handle the messages. And here is a mail catcher example that sends received email to your other mail (just for demonstration): #!/usr/bin/php -q <?php // read from stdin $fd = fopen("php://stdin", "r"); $email = ""; while (!feof($fd)) { $email .= fread($fd, 1024); } fclose($fd); mail('you@yoursite.com','From my email pipe!','"' . $email . '"'); ?> A: You would use a cron job if you wanted to do something at specific times. If you want to do something whenever an email arrives you need to tie your code into your email system. The usual way to do this is with Procmail (there is a recipe you can use (just read PHP for Perl/shell)). A: I've been using the PECL extension mailparse on a website for a number of years now and it has been great. I have all mail for a particular host get piped to a php script that uses mailparse to parse the message and insert it into the database, as well as process the attachments or multiple recipients. They have an example file try.php in the download that was able to get me started. Depending on what mail server you have the easiest thing to do would be to pipe incoming messages to your script like Quentin said. I use exim, and all I had to do was create a valiases file for my domain that looks like this: *: "|/home/site/process_mail.php" and from there mailparse does most of the hard work and I deal with the message and add it to the database.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: UIWindows class subviews method missing Im just going through a video tutorial on swaping views. see code below please: NSArray *subs = [window subviews]; The "window subviews" code simply returns the views into the array subs. But I checked the UIWindow class and I cannot find the property "subviews". Please help, no point my watching video tutorials if I dont understand the code. many thanks A: UIWindow inherits from UIView. UIView has the subviews property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541279", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What is Dalvik and dalvik-cache? I know this may be a basic question in Android. But what is Dalvik and dalvik-cache? A: Dalvik is the java based Virtual Machine that runs Android Apps on Android. Dalvik-cache is the cache area for Dalvik VM, it is created when the Dalvik VM optimizes your app for running. You can look up more on the internet about the differences between Dalvik VM op-codes and a "normal" Java VM Op-codes if you want. A: Dalvik is the virtual machine that is used by Android. It is generally thought of as a Java virtual machine, although this is not precisely correct. It uses an object model that is identical to Java, and its memory model is also nearly equivalent. But the dalvik VM is a register based VM, as opposed to Java VMs, which are stack based. Accordingly, it uses a completely different bytecode than Java. However, the Android SDK includes the dx tool to translate Java bytecode to dalvik bytecode, which is why you are able to write Android applications in Java. When you say "dalvik-cache", I assume you mean the /data/dalvik-cache directory that can be found on typical Android devices. When you install an application on Android, it performs some modifications and optimizations on that application's dex file (the file that contains all the dalvik bytecode for the application). It then caches the resulting odex (optimized dex) file in the /data/dalvik-cache directory, so that it doesn't have to perform the optimization process every time it loads an application. A: Dalvik Caches are nothing but the temporary compilation of application code being stored as executables. As these can be compiled dynamically from the original application code sitting outside the Dalvik Cache, you can clear the Dalvik Cache without any real penalty. A: The Dalvik cache is no part of modern Android versions anymore; Android 4.4 KitKat was the last to make use of this construction. See https://en.wikipedia.org/wiki/Dalvik_(software) for more details.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541281", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "82" }
Q: Bingo Board: Generating unique values I'm having trouble generating unique values which do NOT repeat for this bingo board. My code is relatively simple: I use a nested for loop to generate the values with some print statements; upon each nested iteration, I check to see if the value generated exists within the array. If it exists, it returns true, and the generated value selects a new random number. I thought that by initiating srand() upon each iteration, and using the count in the loop as its seed, I would be able to achieve this. Unfortunately, It doesn't seem very possible. How is this achieved? My code: #define MAX 100 #define MIN 1 using std::vector; bool Board::checkValues(unsigned int array[], unsigned int valueToCheck) { int len = sizeof(array) / sizeof(int); bool numberExists = false; static int repeatCount = 0; for(int i = 1; i < len; i++) { if (valueToCheck == array[i]) { numberExists = true; repeatCount++; break; } } return numberExists; } Board::Board(unsigned int numberOfRows, unsigned int numberOfColumns) { this->numRows = numberOfRows; this->numColumns = numberOfColumns; for (int i = 0; i < this->numRows; i++) { this->board.push_back(vector<unsigned int>(this->numColumns, 0)); } this->valuesVisited[numberOfRows * numberOfColumns]; } void Board::generate() { int repeatCount = 0; for(int i = 0; i < this->numRows; i++) { bool atMid = false; if (i == this->numRows / 2 - 1) { atMid = true; } for(int j = 0; j < this->numColumns; j++) { if (atMid && j == this->numColumns / 2 - 1) { printf(" Free "); continue; } int seed = (i + 1) * (j + 1); unsigned int randNumber = generateRand(MIN, MAX, seed); bool numberExists = checkValues(this->valuesVisited, randNumber); if (numberExists) { //int equation = (randNumber % 10) + (i * j) / (randNumber + randNumber); randNumber = generateRand(MIN, MAX, seed) - (i * j); repeatCount++; } this->valuesVisited[(i + 1) * (j + 1)] = randNumber; this->board[i][j] = randNumber; printf(" %d ", board[i][j]); } std::cout << "\n\n"; } printf("You have %d repeats", repeatCount); } A: Consider filling a std::vector with the candidate numbers, then perform a std::random_shuffle on it and take the first N. A: The usual approach I use for this "generate n unique random numbers" is to fill a vector with the total range of numbers (for you here, MIN -> MAX), random_shuffle() that and then just pull as many values as I need from the front that. I think there are probably slightly more efficient ways if performance is ultra-critical, but it seems to do pretty well in all the situations I've needed so far. Something like std::vector<int> numbers; int index = MIN; std::generate_n(back_inserter(numbers), MAX - MIN + 1, [&](){return index++;}); std::random_shuffle(numbers.begin(), numbers.end()); for(int i = 0; i < this->numRows; i++) { for(int j = 0; j < this->numColumns; j++) { this->board[i][j] = numbers.back(); numbers.pop_back(); } } A: This is some code I came up with for my little project Nothing fancy but it generates unique numbers and for me it filled a need. for (int a = 0; a <= 89; a++) //populate the array with numbers 1-90 { bNumbers[a].Number = a + 1; } for (int a = 0; a < bNumbers.Length; a++) //swap positions of the generated numbers { int rBingo = bMain.rndNum.Next(a, bNumbers.Length); //generate random number // swap numbers round in the array int tmpNum = bNumbers.Number; bNumbers.Number = bNumbers[rBingo].Number; bNumbers[rBingo].Number = tmpNum; //end of swap }
{ "language": "en", "url": "https://stackoverflow.com/questions/7541282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to implement glob.glob currently my os.walk code list's all the files in all directories under the specified directory. top = /home/bludiescript/tv-shows for dirpath, dirnames, filenames in os.walk(top): for filename in filenames: print os.path.join([dirname, filename]) so how could i add glob.glob(search) search = self.search.get_text to search for the pattern that i type in the gtk.Entry or is this something that would not work with my current code A: You don't want glob, you want fnmatch. for dirpath, dirnames, filenames in os.walk(top): for filename in filenames: if fnmatch.fnmatch(filename, my_pattern): print os.path.join([dirname, filename]) glob does part of the work that os.walk has already done: examine the disk to find files. fnmatch is a pure string operation: does this filename match this pattern? A: You don't want glob.glob for this; it checks against names in the directory, which you've already retrieved. Instead, use fnmatch.fnmatch to match your pattern against the list of pathnames you got from os.walk (probably before you add the path). for filename in filenames: if fnmatch.fnmatch(filename, search): print os.path.join([dirname, filename])
{ "language": "en", "url": "https://stackoverflow.com/questions/7541283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Regular Expression to show files with 15 characters QUESTION 1 (13 marks) On gaul, change your working directory to /bin/ (a)What will you get when executing pwd command? Explain why did you get that output? (b) Use a Unix command to display the file names (do not display any of the directory contents, if any) in the current working directory whose names: I. (2 marks) are of length exactly 15 characters This is the only one I can not get done on my assignment, i wrote two regular expressions but i can not tell which one is correct ls /bin/ | grep -c '([0-9])([a-z])*{1,15}' 8 ls /bin/ | grep -c '[0-9][a-z]*{1,15}' 45 it has to only be characters A-Z, 0-9 and _ A: You're making it more complicated than it needs to be. It doesn't say to use regex, nor does it restrict it to those characters (actual filenames are not limited to those). Look at this documentation. Hint: You want to match 15 single characters using a string of one or more of the characters given (?, *, or [). A: I think the following ls command is enough for your problem: ls -d ??????????????? from ls man page: -d, --directory list directory entries instead of contents, and do not dereference symbolic links and 15 "?" means, the name of dir/file should be exactly length of 15. A: Awk is a handy tool for this job: ls /bin | grep -ve "[^A-Za-z_]" | awk '{if (length == 15) print $0}'
{ "language": "en", "url": "https://stackoverflow.com/questions/7541285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I plot a gradient line in HTML canvas? I am trying to draw a line which is a gradient. How is that possible in canvas? A: Yes. Example: // linear gradient from start to end of line var grad= ctx.createLinearGradient(50, 50, 150, 150); grad.addColorStop(0, "red"); grad.addColorStop(1, "green"); ctx.strokeStyle = grad; ctx.beginPath(); ctx.moveTo(50,50); ctx.lineTo(150,150); ctx.stroke(); See it in action here: http://jsfiddle.net/9bMPD/
{ "language": "en", "url": "https://stackoverflow.com/questions/7541286", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "29" }
Q: Mysql concatenation fields update `users` set `email` = 'web+'.`id`.'@gmail.com' Can i achieve this. Basically all that i am trying to do is updating email id in a special faction i.e insert the row's primary key between PLUS(+) and AT(@) in web+@gmail.com A: Use CONCAT: UPDATE `users` SET `email` = CONCAT('web+', `id`, '@gmail.com' ) A: You should use CONCAT function like this: UPDATE `users` SET `email` = CONCAT('web+', CAST(id as CHAR), '@gmail.com') Note you need to CAST the id to CHAR for CONCAT to work
{ "language": "en", "url": "https://stackoverflow.com/questions/7541288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to show comments on nodes that are on the Drupal 7 default home page (promoted)? I have a Drupal 7 installation with a default front page and a few article nodes "promoted to the front page". These are displayed as teasers and in node--article.tpl.php I have a template for my teasers and this all works fine. The node teasers display as expected. On each teaser there is a link that says "View full story". I want to use Ajax to expand the teaser into the full story in place on the home page (I have some fancy animations etc but that's besides the point) So I have a custom module that accepts a nid parameter, loads the node, and returns it to my javascript/jQuery. I am using the jQuery.load() function to make this request. This again all works fine, the teaser is replaced by the full node version which uses the same node--article.tpl.php to define it's appearance. The trouble is, I have comments enabled on articles and on an individual articles page the form and comments show up fine, but when loaded via ajax as described above, the comments don't appear along with the rest of the full node. Is this due to it being the front page? I have print_r'd the $content array and I don't see the comments there at all. Is there a simple workaround for this or am I going to have to write a little module to manually grab the comments and comment form and append them to my nodes after loading? A: The problem is that node_load (which I assume your module uses) does not load the comments. You'll need to modify the module so that it grabs them, something like: $comments = db_select('comment','c') ->condition('nid', $nid, '=') ->execute() ->fetchAssoc();
{ "language": "en", "url": "https://stackoverflow.com/questions/7541291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysql grant all privileges is not getting applied I issue the following command to allow root login from any host GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'xxxx' WITH GRANT OPTION; FLUSH PRIVILEGES; but it does not update? mysql> show grants; +----------------------------------------------------------------------------------------------------------------------------------------+ | Grants for root@localhost | +----------------------------------------------------------------------------------------------------------------------------------------+ | GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*xxxxxxxxxxxxxxxxx33487256' WITH GRANT OPTION | | GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION | +----------------------------------------------------------------------------------------------------------------------------------------+ 2 rows in set (0.00 sec) A: I suspect it's because you're issuing the "show grants" command when connected as root to localhost. Try this and see what is returned: SHOW GRANTS FOR 'root'@'%'; And if that doesn't show up anything, have a look in the mysql.user table, there might be a clue in there: SELECT user, host FROM mysql.user; A: create user 'user'@'%' identified by 'pass'; Query OK, 0 rows affected (0.00 sec) what i did was to add with grant option :) grant all on . to 'user'@'%' with grant option; then it began to work it should be... best regards, emrah benligil
{ "language": "en", "url": "https://stackoverflow.com/questions/7541296", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: ListView and BeginEdit method I have a ListView. When I call listview.SelectedItems[0].BeginEdit(), it is able to correct the selected item. What event needs to be called, when I end edit my item, for example, press such button as "Enter"? At first, when the user selects ToolStripMenuItem it is occurs so event: private void renameLocalUserToolStripMenuItem_Click(object sender, EventArgs e) { if (listView_ad.SelectedItems.Count > 0) { listView_ad.SelectedItems[0].BeginEdit(); } } When the user ends changing his item, he presses "enter". And then I need to take the changed text. A: Use the 'AfterLabelEdit' event. MSDN AfterLabelEdit A: Your question is not quite clear, but I think what you need is to handle the AfterLabelEdit event. A: You may be looking for the AfterLabelEdit event.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Split words with JavaScript, but skips some words before "\" I have a string: "a","b","c" and I can split those words to: a b c using Javascript, but how about: "a,","b\"","c\,\"" How do I get: a, b" c," A: Still not sure if this is one string? But if it is... and this is the only instance of it that you want manipulated, you could use this super convoluted way.... var a = '"a,","b\"","c\,\""'; var b = a.replace(/"/,''); //get rid of the first " var c = b.lastIndexOf('"'); //find the last " var d = b.substring(0,c); //cut the string to remove the last " var e = d.split('","'); //split the string at the "," for(var i="0"; i<e.length; i++){ document.write(e[i] + '<br />'); } Example: http://jsfiddle.net/jasongennaro/ceVG7/1/ A: * *Split as you were *Replace any \ in each resultant string, after the split (using replace()) A: You cannot define "a","b","c" as one string. If you have a string then, The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring. string.replace(regexp/substr,newstring) The split() method is used to split a string into an array of substrings, and returns the new array. string.split(separator, limit) or var myString = "abc,efg"; var mySplitResult = myString.split(","); mySplitResult[0] will be abc mySplitResult[0] will be efg A: What about this: '"a,","b\"","c\,\""'.replace(/^"|"$/g,'').split(/"\s*,\s*"/).join('<br/>') that gives: a,<br/>b"<br/>c," <br/> can be replaced by \n if the output is not HTML
{ "language": "en", "url": "https://stackoverflow.com/questions/7541308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I make my BlackBerry java program wait till a core app is opened before proceeding? My BlackBerry Java program opens the calender app. After that is opened I want it to do something but I currently just use a 250 millisecond delay before that happens. Sometimes the calender take longer or shorter to open. Is there a simple way to use like a Javascript type "While" action in Java for this? Like this English: Open Calendar While "calendar is not open" wait (then the rest of the program after this) A: The method getVisibleApplications() in the ApplicationManager class will return all applications that are currently running and that can come to the foreground. I would repeatedly search through the array that gives you until the Calendar application shows up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can't access special key in array in php when I use following code foreach($admin_info as $key => $val) { echo $key." ".$val."\n"; } I will get true result: id 1 username Moein7tl password 0937afa17f4dc08f3c0e5dc908158370ce64df86 mail moein7tl@gmail.com added_time super_admin last_time last_ip see_user_per 1 change_user_per 1 see_people_per 1 change_people_per 1 add_people_per 1 remove_people_per 1 see_album_per 1 add_album_per 1 change_album_per 1 remove_album_per 1 see_music_per 1 add_music_per 1 change_music_per 1 remove_music_per 1 admin_per 1 yahoo_per 1 status_per 1 pm_per 1 ip_blocking_per 1 but when I use echo ($admin_info['id']); or with other keys, it will make an error and no result will be shown. where is problem? --edit var_dump($admin_info); will returnobject(stdClass)#21 (27) { ["id"]=> string(1) "1" ["username"]=> string(8) "Moein7tl" ["password"]=> string(40) "0937afa17f4dc08f3c0e5dc908158370ce64df86" ["mail"]=> string(18) "moein7tl@gmail.com" ["added_time"]=> NULL ["super_admin"]=> string(0) "" ["last_time"]=> NULL ["last_ip"]=> NULL ["see_user_per"]=> string(1) "1" ["change_user_per"]=> string(1) "1" ["see_people_per"]=> string(1) "1" ["change_people_per"]=> string(1) "1" ["add_people_per"]=> string(1) "1" ["remove_people_per"]=> string(1) "1" ["see_album_per"]=> string(1) "1" ["add_album_per"]=> string(1) "1" ["change_album_per"]=> string(1) "1" ["remove_album_per"]=> string(1) "1" ["see_music_per"]=> string(1) "1" ["add_music_per"]=> string(1) "1" ["change_music_per"]=> string(1) "1" ["remove_music_per"]=> string(1) "1" ["admin_per"]=> string(1) "1" ["yahoo_per"]=> string(1) "1" ["status_per"]=> string(1) "1" ["pm_per"]=> string(1) "1" ["ip_blocking_per"]=> string(1) "1" } A: I found problem,CodeIgniter will return database result as Object. So I should do it like that $admin_info->id and it solves problem. A: Try $admin_info->password, this should work as $admin_info seems to be an object of stdClass. A: Your logic is correct, but you may try using echo $admin_info['id']; without the Parenthesis.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: CRM 2011 GROUP and COUNT I am trying to GROUP the CRM records that have the same "Owner" name and also get a count of the records for each GROUP. So I have a DLL that runs on a schedule and pulls the info down from CRM 2011. But I can't seem to get it to group and do a count of the records for each group. For example all the records with the Owner of "Bob" will say Bob you have X records. And any records with the Owner of "Ted" would say Ted you have X records, etc. For every owner there is. Any idea how to do this? This is what I have so far: var linqQuery = (from r in orgServiceContext.CreateQuery("opportunity") join c in orgServiceContext.CreateQuery("systemuser") on ((EntityReference)r["ownerid"]).Id equals c["systemuserid"] into opp from o in opp.DefaultIfEmpty() //where ((OptionSetValue)r["new_leadstatus"]).Equals("100000002") select new { OpportunityId = !r.Contains("opportunityid") ? string.Empty : r["opportunityid"], CustomerId = !r.Contains("customerid") ? string.Empty : ((EntityReference)r["customerid"]).Name, Priority = !r.Contains("opportunityratingcode") ? string.Empty : r.FormattedValues["opportunityratingcode"], ContactName = !r.Contains("new_contact") ? string.Empty : ((EntityReference)r["new_contact"]).Name, Source = !r.Contains("new_source") ? string.Empty : ((String)r["new_source"]), CreatedOn = !r.Contains("createdon") ? string.Empty : ((DateTime)r["createdon"]).ToShortDateString(), Eval = !r.Contains("new_distributorevaluation") || ((OptionSetValue)r["new_distributorevaluation"]).Value.ToString() == "100000000" ? "NA" : r.FormattedValues["new_distributorevaluation"].Substring(0, 2), EvalVal = !r.Contains("new_distributorevaluation") ? "100000000" : ((OptionSetValue)r["new_distributorevaluation"]).Value.ToString(), DistributorName = !r.Contains("new_channelpartner") ? string.Empty : ((EntityReference)r["new_channelpartner"]).Name, Notes = !r.Contains("new_distributornotes") ? string.Empty : r["new_distributornotes"], EstimatedCloseDate = !r.Contains("estimatedclosedate") ? string.Empty : r["estimatedclosedate"], MaturityValue = !r.Contains("estimatedvalue") ? string.Empty : ((Money)r["estimatedvalue"]).Value.ToString(), SentToDistributorOn = !r.Contains("new_senttodistributoron") ? DateTime.MinValue.ToShortDateString() : ((DateTime)r["new_senttodistributoron"]).ToShortDateString(), LeadStatus = !r.Contains("new_leadstatus") ? string.Empty : ((OptionSetValue)r["new_leadstatus"]).Value.ToString(), EmailedToRSM = !r.Contains("new_emailedtorsm") ? string.Empty : r.FormattedValues["new_emailedtorsm"], EmailedToDistributor = !r.Contains("new_emailedtodistributor") ? string.Empty : r.FormattedValues["new_emailedtodistributor"], Owner = !r.Contains("ownerid") ? string.Empty : ((EntityReference)r["ownerid"]).Name, OwnerEmail = !o.Contains("internalemailaddress") ? string.Empty : ((String)o["internalemailaddress"]), }).ToArray(); foreach (var distributor in linqQuery) { DateTime dtCreatedOn = Convert.ToDateTime(distributor.CreatedOn); DateTime dtSentOn = Convert.ToDateTime(distributor.SentToDistributorOn); // New Lead Notification if (((distributor.Owner.ToString() == distributor.Owner.ToString()) && (DateTime.Now - dtCreatedOn).Days <= 1) && (distributor.LeadStatus == "100000000") && ((distributor.EmailedToRSM == "No") || (distributor.EmailedToRSM == null)) && (String.IsNullOrEmpty(distributor.Owner.ToString()) == false)) { int count = 0; count = count + 1; string lBodyHTML = ""; lBodyHTML = "You have " + distributor.CustomerId.ToString() + " " + distributor.CreatedOn.ToString() + " " + count.ToString() + " new leads. Please review them for follow up or assignment."; string smtpServer = Convert.ToString(Globals.HostSettings["SMTPServer"]); string smtpAuthentication = Convert.ToString(Globals.HostSettings["SMTPAuthentication"]); string smtpUsername = Convert.ToString(Globals.HostSettings["SMTPUsername"]); string smtpPassword = Convert.ToString(Globals.HostSettings["SMTPPassword"]); string xResult = Mail.SendMail("email@email.com", "email@email.com", "", "", MailPriority.High, "You have X new leads", MailFormat.Html, System.Text.Encoding.UTF8, lBodyHTML, "", smtpServer, smtpAuthentication, smtpUsername, smtpPassword); } Any help would be awesome. I'm stuck right now. Thanks! A: This topic has come up before, but the basic answer is that you can't do this via LINQ, but you can via Microsoft's FetchXML. In fact, the first example on GROUP BY in the SDK addresses the requirements of your example about as perfectly as any SDK can. A: Try this: var linqQuery = from r in orgServiceContext.CreateQuery("opportunity") join c in orgServiceContext.CreateQuery("systemuser") on ((EntityReference)r["ownerid"]).Id equals c["systemuserid"] group r by ((EntityReference)r["ownerid"]).Id into oop select new { Key = oop.Key, Count = oop.Count(), Opportunities = oop //contains the list of opportunities grouped by OwnerId }; Opportunities contains a collection of IGrouping You must iterate through the collection IEnumerable<Microsoft.Xrm.Sdk.Entity> to create the list of opportunities with the members you are interested. (the projection you made by using the new operator) var outputOpportunities = new ArrayList(); foreach (IGrouping<Guid, Microsoft.Xrm.Sdk.Entity> group in linqQuery) { foreach (Microsoft.Xrm.Sdk.Entity opportunity in group) outputOpportunities.Add (new { OpportunityId = !opportunity.Contains("opportunityid") ? string.Empty : opportunity["opportunityid"], CustomerId = !opportunity.Contains("customerid") ? string.Empty : ((EntityReference)opportunity["customerid"]).Name, Priority = !opportunity.Contains("opportunityratingcode") ? string.Empty : opportunity.FormattedValues["opportunityratingcode"], ContactName = !opportunity.Contains("new_contact") ? string.Empty : ((EntityReference)opportunity["new_contact"]).Name, Source = !opportunity.Contains("new_source") ? string.Empty : ((String)opportunity["new_source"]), CreatedOn = !opportunity.Contains("createdon") ? string.Empty : ((DateTime)opportunity["createdon"]).ToShortDateString(), Eval = !opportunity.Contains("new_distributorevaluation") || ((OptionSetValue)opportunity["new_distributorevaluation"]).Value.ToString() == "100000000" ? "NA" : opportunity.FormattedValues["new_distributorevaluation"].Substring(0, 2), EvalVal = !opportunity.Contains("new_distributorevaluation") ? "100000000" : ((OptionSetValue)opportunity["new_distributorevaluation"]).Value.ToString(), DistributorName = !opportunity.Contains("new_channelpartner") ? string.Empty : ((EntityReference)opportunity["new_channelpartner"]).Name, Notes = !opportunity.Contains("new_distributornotes") ? string.Empty : opportunity["new_distributornotes"], EstimatedCloseDate = !opportunity.Contains("estimatedclosedate") ? string.Empty : opportunity["estimatedclosedate"], MaturityValue = !opportunity.Contains("estimatedvalue") ? string.Empty : ((Money)opportunity["estimatedvalue"]).Value.ToString(), SentToDistributorOn = !opportunity.Contains("new_senttodistributoron") ? DateTime.MinValue.ToShortDateString() : ((DateTime)opportunity["new_senttodistributoron"]).ToShortDateString(), LeadStatus = !opportunity.Contains("new_leadstatus") ? string.Empty : ((OptionSetValue)opportunity["new_leadstatus"]).Value.ToString(), EmailedToRSM = !opportunity.Contains("new_emailedtorsm") ? string.Empty : opportunity.FormattedValues["new_emailedtorsm"], EmailedToDistributor = !opportunity.Contains("new_emailedtodistributor") ? string.Empty : opportunity.FormattedValues["new_emailedtodistributor"], Owner = !opportunity.Contains("ownerid") ? string.Empty : ((EntityReference)opportunity["ownerid"]).Name, OwnerEmail = !opportunity.Contains("internalemailaddress") ? string.Empty : ((String)opportunity["internalemailaddress"]) } ); } Basically i took your query and added the group by operator and in the projection statement i put the count by ownerid.
{ "language": "en", "url": "https://stackoverflow.com/questions/7541313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How does a commit disappear from the log of one file? So I made a change to a file, pushed it to our main repo, saw it there. David pulled from that repo and did -- well, something -- and couldn't see my change. Since David is a typical Microsoft victim, I asked him to push what he had back to the repo and I'd look at it there. git log --name-only produces commit 194b7f5dbb59d29ace340a376f10906752978db5 Merge: 484df79 afc2dec Author: David Good <david@company.com> Date: Sat Sep 24 11:47:14 2011 -0700 [ David's merge ] commit afc2dec4a828de05350c39526eeecf9d3a15e465 Author: Michael <info@company.com> Date: Sat Sep 24 10:58:54 2011 -0700 [ my changes ] backend/theimportantfile.js commit e4e2f9ce9df3adf5ed0547ed16521eb742cc2ac1 Author: Michael <info@company.com> Date: Sat Sep 24 10:47:09 2011 -0700 [ some other thing ] but git log backend/theimportantfile.js produces commit eb470fe1792220779b14e90337f74fb216fc9f7f Author: David Good <david@company.com> Date: Mon Sep 12 17:20:25 2011 -0700 [ comment ] commit 63ddd2be020092a4bf65d1eac106ece5fd7fbbd3 Author: David Good <david@company.com> Date: Fri Sep 9 16:23:53 2011 -0700 [ comment ] So according to git, backend/theimportantfile.js hasn't been touched in weeks but it was also changed two hours ago with the afc2dec commit. How can I track down what happened? A: It appears David's merge is what did you in. I say this because that the merge appears to have 'reverted' your changes. #this command will show you if anything 'strange' happened during the merge" git show 194b7f If that command gives no interesting output then David perhaps merged with an 'ours' strategy or did the clever 'cp my files to a temp location; git merge; overwrite conflicting files; git commit' workflow. Regardless of how this state was arrived at the merge needs to be discarded and redone as it is obviously faulty. You may also consider changing your workflow such that David doesn't need to do merging anymore but rather submites informal (or formal) "pull requests" and you take care of the merging. A: I'm not sure if this is the nature of your problem, but by default, git log will sometimes filter out commits that it thinks aren't "useful" or "interesting" in order to understand the final state of a commit tree. From the git log docs: Sometimes you are only interested in parts of the history, for example the commits modifying a particular <path>. But there are two parts of History Simplification, one part is selecting the commits and the other is how to do it, as there are various strategies to simplify the history. The following options affect the way the simplification is performed: Default mode Simplifies the history to the simplest history explaining the final state of the tree. Simplest because it prunes some side branches if the end result is the same (i.e. merging branches with the same content). Instead of using the default mode, you can pass in the --full-history flag on your file and see if the "missing" commit shows up that way: git log --full-history -- backend/theimportantfile.js From the git log docs: --full-history Same as the default mode, but does not prune some history. Edit I know this works sometimes because I experienced a situation where I had a commit X in master that contained a change to a file theFile. Commit X was then cherry-picked into anotherBranch by a coworker, so let's call the new commit Y. Then anotherBranch was merged into master. When we did git log -- theFile we would not see Y in the list of commits, just X, but when we used git log --full-history -- theFile only then would both X and Y show up. I guess Git didn't show Y by default because it introduced an identical change to the final state of the commit tree, since it was cherry-picked from X. A: It looks like he may have had a merge conflict and resolved it by accepting his version (which was probably a non-existant file) instead of yours. You can bring the file back. See how to resurrect a file or folder
{ "language": "en", "url": "https://stackoverflow.com/questions/7541321", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Window operations with JQuery? I want to open a new window with width 600 and height 300 Does jquery have a function to do it ? A: No, jQuery doesn't have any method for that. You just use plain Javascript. Example: var handle = window.open('NewPage.html', '_blank', 'width=600,height=300');
{ "language": "en", "url": "https://stackoverflow.com/questions/7541327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-8" }
Q: MVC3, Razor view, EditorFor, query string value overrides model value I have a controller action that takes a DateTime? via the query string as part of a post-redirect-get. The controller looks like e.g. public class HomeController : Controller { [HttpGet] public ActionResult Index(DateTime? date) { IndexModel model = new IndexModel(); if (date.HasValue) { model.Date = (DateTime)date; } else { model.Date = DateTime.Now; } return View(model); } [HttpPost] public ActionResult Index(IndexModel model) { if (ModelState.IsValid) { return RedirectToAction("Index", new { date = model.Date.ToString("yyyy-MM-dd hh:mm:ss") }); } else { return View(model); } } } My model is: public class IndexModel { [DataType(DataType.Date)] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")] public DateTime Date { get; set; } } And the Razor view is: @model Mvc3Playground.Models.Home.IndexModel @using (Html.BeginForm()) { @Html.EditorFor(m => m.Date); <input type="submit" /> } My problem is two fold: (1) The date formatting applied on the model using the [DisplayFormat] attribute does not work if the query string contains a value for date. (2) The value held in the model appears to be overwritten with whatever the query string value contains. E.g. if I set a break point inside my Index GET action method, and manually set the date equal to today say, if the query string contains e.g. ?date=1/1/1, then "1/1/1" is displayed in the textbox (the plan is to validate the date and default it if the query string one isn't valid). Any ideas? A: Html helpers first use ModelState when binding so if you ever intend to modify some value which is present in the model state inside a controller action make sure that you remove it from the ModelState first: [HttpGet] public ActionResult Index(DateTime? date) { IndexModel model = new IndexModel(); if (date.HasValue) { // Remove the date variable present in the modelstate which has a wrong format // and which will be used by the html helpers such as TextBoxFor ModelState.Remove("date"); model.Date = (DateTime)date; } else { model.Date = DateTime.Now; } return View(model); } I must agree that this behavior is not very intuitive but it is by design so people should really get used to it. Here's what happens: * *When you request /Home/Index there is nothing inside ModelState so the Html.EditorFor(x => x.Date) helper uses the value of your view model (which you have set to DateTime.Now) and of course it applies proper formatting *When you request /Home/Index?date=1/1/1, the Html.EditorFor(x => x.Date) helper detects that there is a date variable inside ModelState equal to 1/1/1 and it uses this value, completely ignoring the value stored inside your view model (which is pretty much the same in terms of DateTime value but no formatting is applied of course).
{ "language": "en", "url": "https://stackoverflow.com/questions/7541328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }