pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
34,675,556
0
<p>If you keep your branches relatively related you might be able to use some of the mergeinfo helpers of Subversion to do most of the heavy lifting of determining what is on one branch and not on the other.</p> <p>But if you use strict project policies doing things yourself might be much easier than that. Subversion tries to solve things in a 100% generic way, which may or may not match your requirements.</p>
13,850,085
0
How to check in Perl if symbolic link error? <p>The following bit errors out:</p> <pre><code># Only Execute on Prod Stagesif ($stage eq 'Prod') { if ($stage eq "Prod") { # If /mysql symlink exists, exit0 immediately if ( -l "/mysql" ) { exit(0); } elsif { die "Did not meet expected system disk configuration"; } } exit (0); </code></pre> <p>with:</p> <pre><code>syntax error at ./010MySQLDataDirectoryCheck.pl line 16, near "elsif {" syntax error at ./010MySQLDataDirectoryCheck.pl line 19, near "}" Execution of ./010MySQLDataDirectoryCheck.pl aborted due to compilation errors. </code></pre> <p>What exactly did I miss?</p>
6,963,888
0
android programming: Methods of Storing Forward(sending) user's location? <p>I am a total novice on android programming and is relying on threads/solutions by veteran android programmers to enhance my application. For now I have 2 problems regarding our android app:</p> <p>How and where could our users send their current location? What ways can we store the location of our users and use it on our application?</p>
4,484,149
0
<pre><code>PointerInfo a = MouseInfo.getPointerInfo(); Point b = a.getLocation(); int x = (int) b.getX(); int y = (int) b.getY(); System.out.print(y + "jjjjjjjjj"); System.out.print(x); Robot r = new Robot(); r.mouseMove(x, y - 50); </code></pre>
20,912,732
0
<p>Try this JSFiddle that seems to fit your needs <a href="http://jsfiddle.net/9nF5W/" rel="nofollow">http://jsfiddle.net/9nF5W/</a></p> <pre><code>function test(email, name) { if (email == "" || name == "") { alert("Enter mail or name"); return false; } if (email.indexOf("@") == -1) { alert("Bad email"); return false; } var a = email.length; var b = name.length; if (a &gt; 0 &amp;&amp; b &gt; 0) { alert("Message sent"); } return true; } test('tes@t', 'test'); </code></pre> <p>I think there is an other mistake than the returns statements in "<code>if(a==&gt;0, b==&gt;0){</code>" by the way.</p>
34,223,566
0
<p>Use the <code>SyntaxFactory.RegionDirectiveTrivia()</code>. You can always refer to the <a href="http://roslynquoter.azurewebsites.net/" rel="nofollow">Roslyn Quoter</a> site, when you don't know who to generate some part of a piece of code.</p>
10,850,079
0
<p>JavaScript knows <em>nothing</em> about the JSF code. Instead it knows everything about its generated HTML output. Look at the generated HTML output by rightclick page in browser and <em>View Source</em>. If you look closely, you'll see that the <code>&lt;p:selectOneMenu&gt;</code> doesn't generate a <code>&lt;select&gt;&lt;option&gt;</code>, it instead generates a <code>&lt;div&gt;&lt;ul&gt;&lt;li&gt;</code>. The <code>disabled</code> attribute is only supported on <code>&lt;select&gt;</code>. Hence you don't see any effect.</p> <p>I suggest you to disable the thing via JSF ajax instead of via JavaScript. It's a matter of adding a <code>&lt;f:ajax&gt;</code> or <code>&lt;p:ajax&gt;</code> inside the dropdown and specifying the IDs of components which needs to be updated wherein the <code>disabled</code> check is been done based on the currently selected item. No need for JavaScript boilerplate anymore. This way you'll also take advantage of the robustness of server side validation.</p> <pre><code>&lt;p:selectOneMenu binding="#{searchType}" ...&gt; &lt;f:selectItem itemLabel="Search By Skill" itemValue="1" /&gt; &lt;f:selectItem itemLabel="Search By Location" itemValue="2" /&gt; &lt;p:ajax update="search type1" /&gt; &lt;/p:selectOneMenu&gt; &lt;p:inputText id="search" ... disabled="#{searchType.value == 2}" /&gt; &lt;p:selectOneMenu id="type1" ... disabled="#{searchType.value == 1}"&gt; ... &lt;/p:selectOneMenu&gt; </code></pre> <hr> <p>By the way, the variable name "combo" is wrong. It's a dropdown, not a combobox. A combobox is an <strong>editable</strong> dropdown. The <code>&lt;p:selectOneMenu&gt;</code> doesn't render an editable dropdown, but just a dropdown.</p>
36,844,757
0
Rails Streamio FFMPEG taking a screenshot of the movie and upload with carrierwave <p>I have got a Form where I can upload a movie. Its uploaded with carrierwave.</p> <p>In this process I want to Make a screenshot of the movie while uploading. </p> <p>How can I do this with Streamio FFMPEG.</p> <p>My code Looks like this at the moment.</p> <pre><code>#Laedt ein Video hoch def uploadMovie @channels = Channel.all @vid = Movie.new(movies_params) @channel = Channel.find(params[:channel_id]) @vid.channel = @channel if @vid.save flash[:notice] = t("flash.saved") render :add else render :add end end </code></pre> <p>Do I have to do this in controller method or in the carrierwave uplaoder?</p> <p>Update: I tried it this way:</p> <pre><code>if @vid.save flash[:notice] = t("flash.saved") movieFile = FFMPEG::Movie.new(@vid.video.to_s) screenshot = movieFile.screenshot("uploads/screenshot", :seek_time =&gt; 10) render :add else </code></pre> <p>But then I got tis error: </p> <pre><code>s3.amazonaws.com/uploads/movie/video/6/2016-04-24_16.26.10.mp4' does not exist </code></pre>
23,284,238
0
iOS capture audio playback into a file <p>I'd like to know if it's possible to record an audio playback into a file in ios without using microphone. In another word, is it possible to capture the audio playback "raw data" into a file?</p> <p>I tried the AVAudioRecorder, but there is no option to record without using the microphone. Any idea? Thanks</p>
4,276,758
0
<p>Given that sqlite only supports UTF-8 and UTF-16 as the encodings, you would have noticed if Android would create databases in something other than UTF-8. <a href="http://www.sqlite.org/c3ref/open.html">sqlite3_open</a> defaults to create the database in UTF-8, and that is what Android is likely to use.</p>
19,503,112
0
PhantomJS is a headless (GUI-less) WebKit with JavaScript API. It has native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. This tag deals specifically with PhantomJS version 1.9.
39,304,358
0
<p>Yes, you can do it that way. If it's not a hard work, I'll include the database load on the Perl step. This probably avoids to handle an intermediate file, but I don't know if it's a viable task on your project.</p> <p>In order to use RabbitMQ, I'll recommend you the <a href="https://metacpan.org/pod/AnyEvent::RabbitMQ" rel="nofollow">AnyEvent::RabbitMQ</a> CPAN module. As the documentation establishes, You can use AnyEvent::RabbitMQ to:</p> <ul> <li>Declare and delete exchanges</li> <li>Declare, delete, bind and unbind queues</li> <li>Set QoS and confirm mode</li> <li>Publish, consume, get, ack, recover and reject messages</li> <li>Select, commit and rollback transactions</li> </ul>
12,510,031
0
No Exception In Apache James Server <p>I am using Apache James Server to send e-mails on my localhost. When an e-mail is not sent, no Exception is thrown through from the Java Spring code. I am using Apache James Server 3. Below is my code. Usually, when you have an online server an Exception is thrown. Do I need to configure something in Apache James Server? E-mails are sent to local users but I want to send to an external e-mail address. I know the e-mail won't be sent, but no Exception is thrown. However, the Apache James Server keeps on trying to resend the e-mail. Any ideas?</p> <p>Below is my code:</p> <pre><code>public class Email extends Message { private JavaMailSender javaMailSender; public Email() { } public JavaMailSender getJavaMailSender() { return javaMailSender; } public void setJavaMailSender(JavaMailSender javaMailSender) { this.javaMailSender = javaMailSender; } public boolean sendEmailMessage(String from, String to, String body, String subject) throws Exception { boolean isEmailSent = false; try { javaMailSender.send(new MessageBuilder(from, to , body, subject)); isEmailSent = true; } catch(Exception e) { System.out.println("Exception : " + " " + e.getMessage()); } } return isEmailSent; } } package com.JavaMailWithSpring; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import javax.mail.internet.MimeMessage; public class MessageBuilder implements MimeMessagePreparator { private String from; private String to; private String body; private String subject; public MessageBuilder(String from, String to, String subject, String body) { this.from = from; this.to = to; this.subject = subject; this.body = body; } public void prepare(MimeMessage msg) throws Exception { MimeMessageHelper helper = new MimeMessageHelper(msg, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(body); } } </code></pre> <p>beans.xml</p> <pre><code>&lt;bean id="mailSenderBean" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt; &lt;property name="host" value="localhost"&gt;&lt;/property&gt; &lt;property name="javaMailProperties"&gt; &lt;props&gt; &lt;prop key="mail.smtp.port"&gt;25&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre>
37,223,969
0
<p>If you mean, can how can you show the results of observable array in your view, then there's few ways to go on about that:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [{ Url: 's.Piece.Name', Id: 's.Id', IsLighted: 's.IsLighted', Class: 's.ColorType' }, { Url: 's.Piece.Name2', Id: 's.Id2', IsLighted: 's.IsLighted2', Class: 's.ColorType2' }]; var DemoPage = (function() { function DemoPage() { var self = this; self.CellList = ko.observableArray([]); self.updateBoard = function(cellList) { var _temp = []; for (var i = 0; i &lt; cellList.length; i++) { // I've created a temporary array here, so knockout won't // re-draw every time you push, then when we finally finish this loop // it's pushed to the right target _temp.push(cellList[i]); } self.CellList(_temp); } } return DemoPage; })(); var demo = new DemoPage(); ko.applyBindings(demo); demo.updateBoard(data);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.result p { color: teal } .result { margin-top: 11px; border-top: 1px solid #bbb; padding-top: 11px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"&gt;&lt;/script&gt; &lt;p&gt;Display individual item:&lt;/p&gt; &lt;!-- ko if: CellList().length &gt; 0 --&gt; &lt;p data-bind="text: CellList()[0].Url"&gt;&lt;/p&gt; &lt;!-- /ko --&gt; &lt;p&gt;Or just loop them:&lt;/p&gt; &lt;!-- ko if: CellList().length &gt; 0 --&gt; &lt;div data-bind="foreach: CellList"&gt; &lt;div class="result"&gt; &lt;p data-bind="text: Url"&gt;&lt;/p&gt; &lt;p data-bind="text: Id"&gt;&lt;/p&gt; &lt;p data-bind="text: IsLighted"&gt;&lt;/p&gt; &lt;p data-bind="text: Class"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- /ko --&gt;</code></pre> </div> </div> </p> <p>Notice that I've wrapped them with virtual if bindings - that's because on the initialization, the array is empty and there are no objects with those properties at that time. Only show them when there's at least 1 element in the array.</p> <p>You could also use mapping, and convert all object properties into observables, then they all could be changed dynamically later.</p>
24,038,304
0
<p>This makes it easier when defining method return types such as this:</p> <pre><code>class A&lt;B extends A&lt;B&gt;&gt; { public B getMe(){ return (B) this; } } </code></pre> <p>This tells Java compiler that you are in <code>getMe()</code> method returning a subclass of class <code>A</code>.</p> <pre><code>class C extends A&lt;C&gt; { } C c = new C(); c.getMe(); //returns C </code></pre>
22,237,309
0
Run js once an image has been lazy loaded <p>I'm using this lazy load jQuery script ( <a href="http://www.appelsiini.net/projects/lazyload" rel="nofollow">http://www.appelsiini.net/projects/lazyload</a> ) to lazy load images when they appear in the viewport, but I want to run some javascript / styling to style the new, full image that is loaded.</p> <p>How can I run javascript once the image has been loaded?</p>
9,115,696
0
Android and playing SVG animation <p>I'm writing an Android application and I'd like to play a simple SVG animation. I'm aware that Android does not offer SVG support; what are my options here?</p>
14,562,363
0
Selenium web driver not able to close firefox instance if a Test cases is failed <p>i folks, i am using junit with selenium web driver 2.28. the problem is if i run a successful test case the web drives is able to close the firefox instance, but when a test case fails the selenium web driver is not able to close the firefox. i am using FF 15.0.1 with selenium-server-standalone-2.28.0.jar. please respond thanks Sahil</p> <pre><code>private void startWebdriver() throws UIException{ //2) Prevent re-use. if(UIHandlerWD.this.profile == null) throw new UIException( UIException.Code.UI, "Webdriver instance cannot be instantiated." ); //3) Configure Selenium Webdriver. if (this.profile.browserType.equalsIgnoreCase("*firefox")){ FirefoxProfile fProfile = new FirefoxProfile(); // profile.SetPreference("network.http.phishy-userpass-length", 255); fProfile.setAcceptUntrustedCertificates(true); DesiredCapabilities dc = DesiredCapabilities.firefox(); dc.setJavascriptEnabled(true); dc.setCapability(FirefoxDriver.PROFILE, fProfile); //this.webdriver = new FirefoxDriver(dc); this.webdriver = new FirefoxDriver(dc); } else if (this.profile.browserType=="INTERNETEXPLORER") this.webdriver = new InternetExplorerDriver(); else throw new UIException( UIException.Code.UI, "Unknown browser type '" + this.profile.browserType +"'." ); //4) Start Webdriver. this.webdriver.get(this.profile.getURL().toString()); this.webdriver.manage().timeouts(). implicitlyWait(5, TimeUnit.SECONDS); this.webdriver.manage().timeouts(). pageLoadTimeout(this.profile.timeout, TimeUnit.SECONDS); } void stopWebdriver() { if(this.webdriver != null){ try{ Thread.sleep(5000); } catch (Exception e) { // TODO: handle exception } this.webdriver.close(); } this.webdriver = null; this.profile = null; } </code></pre>
33,625,750
0
<p>You maybe intrested in <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html" rel="nofollow">javap</a></p> <p>I have created A.java, B.java, C.java, D.java fiels:</p> <pre><code> public class A { public static void main(String[] args) { B b = new B(); b.getC().getD(); } } </code></pre> <p>and compile these classes.</p> <p>Now we can use javap to dissemble A.class:</p> <pre><code>javap -c A </code></pre> <p>and get bytecodes:</p> <p>public class A { public A(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."":() 4: return</p> <pre><code> public static void main(java.lang.String[]); Code: 0: new #2 // class B 3: dup 4: invokespecial #3 // Method B."&lt;init&gt;":()V 7: astore_1 8: aload_1 9: invokevirtual #4 // Method B.getC:()LC; 12: invokevirtual #5 // Method C.getD:()LD; 15: pop 16: return } </code></pre> <p>Now you can get A.class have used imported class, like:</p> <ul> <li>// Method B.getC:()LC; --> used class B </li> <li>// Method C.getD:()LD; --> used class C</li> </ul> <p>but I think the best way is use <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="nofollow">Abstract Syntax Tree</a> as @Kong, </p>
17,914,195
0
<p>Use classes instead of IDs as propper markup there should be only 1 ID of a given name per page.</p> <p>HTML</p> <pre><code>loop 1 &lt;p&gt;- user review-&lt;/p&gt; &lt;a href="#" class="upvote" data-review="1"&gt;Up Vote&lt;/a&gt; loop 2 &lt;p&gt;- user review-&lt;/p&gt; &lt;a href="#" class="upvote" data-review="2"&gt;Up Vote&lt;/a&gt; etc. </code></pre> <p>JS</p> <pre><code>// jQuery / AJAX - separate file linked to `HTML` $('.upvote').on('click', function(e) { e.preventDefault(); var review_id = this.data('review'); $.ajax({ url : "search_query.php", type : "POST", dataType: "json", data : { reviewId : review_id }, success : function(data) { // do stuff } }); </code></pre> <p>PHP</p> <pre><code>&lt;?php $review_id = $database-&gt;escape_value(trim($_POST['reviewId'])); // Upvote Method $result = Data::upVoteReview($review_id, $_SESSION['user_id']); $output["result"] = $result; print(json_encode($output)); ?&gt; </code></pre>
35,124,826
0
How to insert CheckBoxList Checked Item to Database <p>I have a check box list, and I want to insert its Checked items to Database; I used this code:</p> <pre><code>for (int i = 0; i &lt; checkBox_service.Items.Count; i++) { if (checkBox_service.Items[i].Selected == true) { strcheck += "" + checkBox_service.Items[i].ToString() + ","; } } </code></pre> <p>In Database it is displaying</p> <pre><code>System.Web.UI.WebControls.CheckBoxList </code></pre> <p>in CheckBox field instead of Selected item. All other fields are having correct data as per entered... I couldn't find any error, please guide me...</p>
35,424,427
0
<blockquote> <ol> <li>What is <code>mk</code> returning?</li> </ol> </blockquote> <p>Let's go through a much simpler example In the documentation of GHC.Generics first. To achieve a generic function <code>encode :: Generic a =&gt; a -&gt; [Bool]</code> that bit serialize every data type which has a Generic instance, they defined the type class below : </p> <pre><code>class Encode' rep where encode' :: rep p -&gt; [Bool] </code></pre> <p>By defining <code>Encode'</code> instances for every Rep type (M1, K1, etc.), they made the function work universally on every data types.</p> <p>In <a href="https://ocharles.org.uk/blog/posts/2014-04-26-constructing-generically.html" rel="nofollow">Building data constructors with GHC Generics</a>, the author's final goal is a generic function <code>make :: Generic a =&gt; TypeOfConstructor a</code>, so naively one may define:</p> <pre><code>class Mk rep where mk :: (? -&gt; p) -- what should '?' be? </code></pre> <p>And soon realize that it's impossible due to a few problems:</p> <ol> <li><code>-&gt;</code>, the function type in haskell only takes one argument at a time, so <code>mk</code> won't be able to return anything sensible if the constructor takes more than one argument.</li> <li>The number and type of the arguments are unclear: it's relative to the <code>rep</code> type in concern.</li> <li>It cannot be plain <code>p</code> as the result type. Without the <code>rep</code> context it's impossible to derive instances for <code>:*:</code> or <code>:+:</code>, and the function will no longer work on any nested data type.</li> </ol> <p>Issue 1 can be solved with Data.Functor.Compose. A function of type <code>a -&gt; b -&gt; c</code> can be encoded into <code>Compose ((-&gt;) a) ((-&gt;) b) c</code>, it can be further composed while keeps a whole lot of information about argument types. And by making it a type parameter of <code>Mk</code>, issue 2 is solved too:</p> <pre><code>class Functor f =&gt; Mk rep f | rep -&gt; f where mk :: f (rep p) </code></pre> <p>where <code>f</code> is generalization over <code>Compose f g</code> and <code>(-&gt;) a</code>, which contains type-level information to construct a <code>rep p</code>, i.e. everything before the final <code>-&gt;</code> in <code>a -&gt; b -&gt; c -&gt; ... -&gt; rep p</code>. </p> <blockquote> <ol start="2"> <li>I'm guessing <code>Compose</code> comes from <code>Data.Functor.Compose</code>, which means that when I do <code>fmap f x</code>, it does the <code>fmap</code> two levels deep into the composed functors. But I can't make sense of the nested <code>fmap</code>s inside the <code>Compose</code>. </li> </ol> </blockquote> <p>In the <code>Mk</code> instance of <code>:*:</code>:</p> <pre><code>instance (Mk l fl, Mk r fr) =&gt; Mk (l :*: r) (Compose fl fr) where mk = Compose (fmap (\l -&gt; fmap (\r -&gt; l :*: r) mk) mk) </code></pre> <p><code>fmap</code> changes only the inner-most type of a nested Compose, in this case changes the final result of a n-ary function. <code>mk</code> here is literally concatenating two argument lists <code>fl</code> and <code>fr</code>, putting their results into a product type, namely</p> <pre><code>f :: Compose ((-&gt;) a) ((-&gt;) b) (f r) g :: Compose ((-&gt;) c) ((-&gt;) d) (g r) mk f g :: Compose (Compose ((-&gt;) a) ((-&gt;) b)) (Compose ((-&gt;) c) ((-&gt;) d)) ((:*:) f g r) -- or unwrapped and simplified (a -&gt; b -&gt; r) -&gt; (c -&gt; d -&gt; r') -&gt; a -&gt; b -&gt; c -&gt; d -&gt; (r, r') </code></pre> <blockquote> <ol start="3"> <li>For the instance of <code>M1 i c f</code>, I thought it would just wrap the inner values in <code>M1</code>, so the need to <code>M1 &lt;$&gt; mk</code> or <code>fmap M1 mk</code> makes no sense to me.</li> </ol> </blockquote> <p>It does just wrap the inner values in <code>M1</code>, but it's unclear how long the argument list of the underlying <code>f</code> is. If it takes one argument then <code>mk</code> is a function, otherwise it's a Compose. <code>fmap</code> wraps the inner-most value of them both.</p>
41,004,464
1
how to obtain the name of the program active in this moment? <p>to be more specific, i need to obtain the title's name of the program that currently is working on my pc(windows), if for example i am using Excel,I want to put in a variable, the name of it, Excel in this case, thanks a lot and excusme for my terrible english.</p>
33,263,298
0
Winforms UI hang after DisplaySettingsChangingevent <p>I am working on an application that generally runs 24x7. It does so well for a period of time but I have noticed that after the DisplaySettingsChanging event fires (via an RDP connection) the application will continue to process in the background but the UI becomes completely unusable. It does not tell you in the task manager that the application is unresponsive like when the UI message pump is blocked. I know there is a bug with the SystemEvents class (still in .NET 4?). I have moved our splash screen into the form load event handler and do not create any controls on another thread other than the main UI thread. I have tried subscribing to the following events in the constructor of my main form (which has a valid SynchronizationContext)</p> <pre><code>SystemEvents.DisplaySettingsChanging SystemEvents.DisplaySettingsChanged SystemEvents.UserPreferencesChanged </code></pre> <p>but per <a href="http://stackoverflow.com/questions/4077822/net-4-0-and-the-dreaded-onuserpreferencechanged-hang">this related solution</a> but it doesn't seem to help.</p> <p>What else am I missing here?</p> <p>EDIT 1: Ok after running spy++ I see there are two threads that own windows other than the main UI thread. However when I examine the threads within my process in visual studio I don't see either one. Does that mean some referenced assembly is the culprit? Probably should be a separate question, but how do I find out?</p> <p><a href="https://i.stack.imgur.com/Czkqt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Czkqt.png" alt="enter image description here"></a></p> <p>EDIT 2: The second window is a button click event that opens an open file dialog box. I checked the apartment state for that thread and it is correct STA. I have not determined how or when that other thread is created. Seems like it must be the offender.</p>
12,918,670
0
<p>Yes, it's possible. You just need to specify some directives in your manifest.json:</p> <pre><code>"content_security_policy": "default-src 'none'; script-src 'self'" </code></pre>
30,509,910
0
<p>For most databases there is the option of batch insertions. Obviously even a small overhead will accumulate if you have to many connections over time. And performing single insertions will have a greater overhead than on batch. The only issue is how often?.... And you should test how often you wan't to insert and how much information you should store locally before doing a batch insertion.</p>
6,583,297
0
Unit test design question <p>I'd like to unit test this method</p> <pre><code>public string Edit(int id) { var item = _repository.Get(id); string json = _jsonConverotr.Convert(item); return json; } </code></pre> <p>The repository will by mocked. But the jsonConvertor is a simple class to convert an entity to json.</p> <p>So my question is,should I also mock the jsonConvertor class or is it Ok to use the original ? The jsonConvertor class is tested elsewhere.</p>
129,115
0
<p>You can use SQL Profiler to find that out.</p> <p>EDIT: If you can stop the app you are running, you can start SQL Profiler, run the app and look at what's running including stored procedures.</p>
185,993
0
MVP examples for Windows Forms <p>Is there good example code or a test project for explaining the <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="nofollow noreferrer">Model–view–presenter (MVP) pattern</a>. There are a lot of explanation links, but I want to have some good example code to show others without reinventing the wheel.</p>
31,255,620
0
<p>You can use <code>sprintf</code> and <code>\n</code> to get multiple lines. The additional <code>HorizontalAlignment</code>-property aligns the text horizontally. Then you just need to fine fine-tune the overall position.</p> <pre><code>f = figure('menu','none','toolbar','none'); txt = sprintf('Line 1\nA longer line 2\nLine 3'); uicontrol('Style','text','Position',[30 45 180 40],'String',txt,... 'HorizontalAlignment','left'); </code></pre> <p><em>This looks like this:</em></p> <p><img src="https://i.stack.imgur.com/hcIwa.png" alt="pic1"></p>
63,740
0
<p>Is it possible that we are in a panic and are getting confused between unit tests and performance tests? Is it that your application works fine with few users, but starts throwing errors when under heavier load? If so, unit tests are not the answer. Unit tests != Load tests.</p> <p>If unit tests are in fact the answer, retrofitting unit tests is a good idea as it will help clean up the code. Just be prepared to refactor a lot. Code written with TDD turns out looking a lot different than code written without TDD. In my case, I had a method HandleDisposition() which took care of a lot of cases. This kind of method would not have existed if we had written the code with TDD. When retrofitting unit tests, we refactored that function and now have methods like XDisposition(), YDisposition(), ZDisposition(), which are a lot easier to write unit tests against.</p>
20,647,178
0
Winston logging to multiple file logs without duplicating log messages <p>Here is my Winston config:</p> <pre><code>winston = require 'winston' logger = new winston.Logger transports: [ new winston.transports.File name: 'file#debug' level: 'debug' filename: '/tmp/debug.log' new winston.transports.File name: 'file#error' level: 'error' filename: '/tmp/error.log' ] </code></pre> <p>Currently when I log:</p> <pre><code>logger.error 'error' # both logs logger.debug 'debug' # on debug log </code></pre> <p>What I want is the errors to only go to error.log, and debug messages to only go to debug.log. How can i do that? Searched the File transport options but didnt find anything like that.</p>
4,995,806
0
Delay ajax request by x seconds and update only the last clicked request <p>Hi all I am delaying a AJAX request by 3 seconds and then updating a div with the response. But the problem what I face is, when the user clicks on all the three links simultaneously, the requested content keeps getting updated in the div. What i am trying to do is, serve only the last clicked ajax request content, but should not abort the previous requests too. Is there any way that i can achieve it ?? Thanks in advance </p> <h2>Script</h2> <pre><code> $('.links li a').click(function(event){ event.preventDefault(); var getUrl = $(this).attr("href"); var printCall = function() { $.ajax({ url: getUrl, type: "GET", beforeSend: function() { }, error: function(request){ alert(request) }, success: function(data) { $('#graphContent').html(data); } }); }; setTimeout(printCall, 3000); }); </code></pre> <h2>HTML</h2> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="http://localhost/test.php"&gt;Link 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Link 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
7,941,162
0
<p>Does your scheme target dropdown list show "iOS Device" or does it show the "name" of your iPod Touch (something like "jons ipod touch"):</p> <p><img src="https://i.stack.imgur.com/ia2hw.jpg" alt="Scheme Target"></p> <p>If it shows "iOS Device", that means your iPod isnt recognized by xcode and you may need to enable the device for developing by clicking "<em>Use For Development</em>" like so:</p> <p><img src="https://i.stack.imgur.com/TV3qE.jpg" alt="Enable For Development"></p>
17,434,119
0
How to get frequency of elements from List in c# <p>I am trying to get the frequency of elements stored in a list.</p> <p>I am storing the following ID's in my list</p> <pre><code>ID 1 2 1 3 3 4 4 4 </code></pre> <p>I want the following output:</p> <pre><code>ID| Count 1 | 2 2 | 1 3 | 2 4 | 3 </code></pre> <p>In java you can do the following way. </p> <pre><code>for (String temp : hashset) { System.out.println(temp + ": " + Collections.frequency(list, temp)); } </code></pre> <p>Source:<a href="http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/" rel="nofollow">http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/</a></p> <p>How to get the frequency count of a list in c#? </p> <p>Thanks.</p>
38,331,135
0
<p>For people coming here in 2016, you can find lots of useful colours here: </p> <pre><code>nameStyle.Color = NPOI.HSSF.Util.HSSFColor.BlueGrey.Index; </code></pre> <p>Whereby BlueGrey is the colour you are looking for.</p>
1,672,285
0
<p>The short answer:</p> <p>the .net platform can be used for transactional systems, but the question is really is the platform scalable enough and can it perform well enough under extremely high volumes?</p> <p>.Net like every other high level language has a place in this world, and I personally would not use .net managed code for core transactional systems. In the same way I simply would not use .net for writing mission critical device drivers. </p> <p>If you have a choice go for c++ for mission critical stuff. Don't throw .net out of the solution entirely, recognize it has its strengths, and use it accordingly.</p> <p>.net is very good for rapid, reusable development, I would even say if you use it correctly (perhaps even go unmanaged) and test / retest your apps, you'll get away with a lot more than you think. </p>
16,134,975
0
Reduce increasing time to push a subtree <p>I'm using git in my project, which consists of several sub-projects. Each sub-project is "linked" in the main project using the "git subtree" command. That's my way to realize "svn externals" in git. I'm using it since some weeks, but the time pushing my changes from the subtree to the remote location increases during every commit. It look like this, when I'm pusing the changes using the command "git subtree push -P platform/rtos rtos master"</p> <pre><code>git push using: rtos master 1/ 215 (0)2/ 215 (1)3/ 215 (2)4/ 215 (3)5/ 215 (4)6/ 215 (5)7/ 215 (6)8/ 215 (7)9/ 215 (8)10/ 215 (9)11/ 215 (9)12/ 215 (10)13/ 215 (11)14/ .... 20 more lines .... (204)209/ 215 (205)210/ 215 (206)211/ 215 (207)212/ 215 (208)213/ 215 (209)214/ 215 (210)215/ 215 (211)To https://github.com/rtos/rtos.git 64546f..9454ce 9a9d34c5656655656565676768887899898767667348590 -&gt; master </code></pre> <p>Is there any way to "clean up" the subtree and therefore reduce the time pushing the changes?</p>
25,720,054
0
<p>If _disable_f2 is being given two arguments, let it have what it wants.. try below... :)</p> <pre><code>from Tkinter import * class App: def _disable_f2(self, master): if self.filt.get() == 'bandpass': self.filter_menu.configure(state='normal') else: self.filter_menu.configure(state='disabled') def __init__(self, master): self.f2var = StringVar() self.f2var.set('5.0') self.f2_entry = Entry(master, textvariable=self.f2var, width=5) self.f2_entry.pack() self.filt = StringVar() self.filt.set('bandpass') self.filter_menu = OptionMenu(master, self.filt, 'bandpass', 'lowpass ', 'highpass', command=self._disable_f2) self.filter_menu.pack(ipadx=50) root = Tk() app = App(root) root.mainloop() </code></pre>
6,457,620
0
Convert a string to datetime <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/1009457/how-can-i-convert-a-string-into-datetime-in-net">How can I convert a string into datetime in .NET?</a> </p> </blockquote> <p>i have a string in the following format "15/03/2046". how can convert this string to a DateTime object? </p> <p>My problem is when i do Convert.ToDateTime("15/03/2046") i get an exception.<br> when i do Convert.ToDateTime("03/03/2046") every thing works fine.<br> so i guess that i have to specify the format somehow while converting....</p>
9,564,313
0
WCF REST - Myriad of ways to create - How to choose? <p>I am learning to create RESTful services using WCF. There are a myriad of options to choose from. I am confused as to what should i use. 1.)REST Starter kit - Seems to be obsolete 2.)WCF WEbhttp service 3.)WCF Web API 4.)ASP.NET web api</p> <p>I dont want to use ASP.NET MVC to build RESTFul services. I dont like the idea of services being in the same solution structure of a presentation layer. So what is it i should use?ASP.NET web api seems to be having going down the MVC route where the requests are handled by a controller which i feel does not fit into a "Service" terminology.</p>
6,937,472
0
I want background of my cocos2d game to be the view of the camera of iphone. How do i do that? <p>I am making a game with augmented reality in it. So, i want to have the camera view as the background of the game. However, I am finding some difficulties in doing this.</p> <p>I tried doing it using the UIImagePickerController but then when i do that, all i get is the camera view and the game elements disappear. </p> <p>I looked at some of the articles..</p> <p><a href="http://www.cocos2d-iphone.org/forum/topic/1752" rel="nofollow">http://www.cocos2d-iphone.org/forum/topic/1752</a></p> <p><a href="http://www.cocos2d-iphone.org/forum/topic/711" rel="nofollow">http://www.cocos2d-iphone.org/forum/topic/711</a></p> <p>but i didnt get any proper answer and it only confused me more.</p> <p>Can anyone help? Thanks.</p>
37,686,123
0
<p>'Key' in the <code>getCommand</code> array is the name/path to the file you want to generate a pre-signed URL for, not your AWS key :)</p> <pre><code>$cmd = $s3Client-&gt;getCommand('GetObject', [ 'Bucket' =&gt; 'my-bucket-name', 'Key' =&gt; 'path/to/file.txt', // or just file.txt if it's in the root of the bucket ]); </code></pre>
11,603,209
0
<p>Do you mean to return it as a 32-bit integer?</p> <pre><code>unsigned int get_color(cv::Mat img, float x, float y) { int i = x*img.cols; int j = y*img.rows; unsigned char R = img.ptr&lt;unsigned char&gt;(j)[3*i]; unsigned char G = img.ptr&lt;unsigned char&gt;(j)[3*i+1]; unsigned char B = img.ptr&lt;unsigned char&gt;(j)[3*i+2]; return (R &lt;&lt; 16) | (G &lt;&lt; 8) | B; } </code></pre> <p>Or perhaps you want to return it as floats in which case you need to do the following</p> <pre><code>struct FloatColour { float r; float g; float b; }; float get_color(cv::Mat img, float x, float y) { int i = x*img.cols; int j = y*img.rows; unsigned char R = img.ptr&lt;unsigned char&gt;(j)[3*i]; unsigned char G = img.ptr&lt;unsigned char&gt;(j)[3*i+1]; unsigned char B = img.ptr&lt;unsigned char&gt;(j)[3*i+2]; FloatColour retCol; retCol.r = R / 255.0f; retCol.g = G / 255.0f; retCol.b = B / 255.0f; return retCol; } </code></pre>
19,482,019
0
Not getting correct answers from very simple functions <p>Okay, so I'm a complete noob. I'm trying my hand at Project Euler to get better at C++. I'm doing problem #1, but I'm not getting the correct output. When I run it, I get that numTotalThree is -3, and numTotalFive is -5, and that numTotal is 0. There's something wrong with my functions, but I'm not sure what I've done wrong. How do I fix this?</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int amount = 1000; int numOfThree = amount / 3; int numOfFive = amount / 5; int numTotalThree = 0; int numTotalFive = 0; int numTotal = numTotalThree + numTotalFive; cout &lt;&lt; numOfThree &lt;&lt; endl; cout &lt;&lt; numOfFive &lt;&lt; endl; for(int i = 0; i &lt;= numOfThree; i++) { numTotalThree += numTotalThree + 3; } cout &lt;&lt; numTotalThree &lt;&lt; endl; for(int i = 0; i &lt;= numOfFive; i++) { numTotalFive += numTotalFive + 5; } cout &lt;&lt; numTotalFive &lt;&lt; endl; cout &lt;&lt; numTotal &lt;&lt; endl; system("PAUSE"); return 0; } </code></pre>
31,406,320
0
Modal window with Angular (UI-Router / Directive) <p>I have spent some time now looking into a generic way of controlling a modal window with <code>AngularJS</code> and none of the proposed options are anywhere near 'good' solution.</p> <h2>The Directive Solution</h2> <p>I found <a href="http://jsfiddle.net/alexsuch/RLQhh/">this</a> demo, however the downside of that is you have to manually manage and store the state of the modal and cross-scope update it:</p> <pre><code>scope.$parent[attrs.visible] = true; </code></pre> <p>Also if you had to add more functionality like actually adding an item with a popup that would involve even more ugly code on the parent page scope.</p> <h2>The UI-Router Solution</h2> <p><a href="https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-open-a-dialogmodal-at-a-certain-state">This is the official guide on how to use modals with ui router.</a></p> <p>This however is using <strong>ui.bootstrap.modal</strong> </p> <p>My question is, is there any simple and elegant solution to what is quite frankly a very simple problem...</p> <p><strong>Something like this for example:</strong></p> <pre><code>.state('popup', { url: '/item/add/', views: { 'popupView': { templateUrl: "/myPopup.html", controller: "myPopupController" } }, type: 'modal' }) </code></pre> <p>And things like close, redirect, submit, all are handled in the <code>myPopupController</code>.</p> <p>I am not seeking an explanation of why the examples are above are as they are, or how I should be using them. I am simply looking if anyone has come up with a better solution.</p>
15,229,132
0
<p>Try this regex.</p> <pre><code>url = url.replace(/^http:\/\//i, 'https://'); </code></pre>
39,911,362
0
<p>You can use the <code>format</code> option:</p> <pre><code>// Move formatting code into a function function toFormat ( v ) { return formatDate(new Date(v)); } // Add a formatter to the slider format: { to: toFormat, from: Number } // You can then directly use the value in the update function dateValues[handle].innerHTML = values[handle]; </code></pre> <p>Updated <a href="https://jsfiddle.net/leongersen/vvgr74v2/1/" rel="nofollow">fiddle</a>.</p>
3,331,463
0
JQuery wrap() problem <p>Why doesn't the following code wrap the image with <code>&lt;li&gt;</code> tags and what would be the best way to do this?</p> <pre><code>var i = new Image i.src = '/images/image.jpeg' $(i).wrap('&lt;li /&gt;') $('div').html(i) </code></pre> <p>produces:</p> <pre><code>&lt;div&gt;&lt;img src="/images/image.jpeg"&gt;&lt;/div&gt; </code></pre> <p>instead desired:</p> <pre><code>&lt;div&gt;&lt;li&gt;&lt;img src="/images/image.jpeg"&gt;&lt;/li&gt;&lt;/div&gt; </code></pre>
34,231,733
0
<p>The CoolEdit snapshot looks like its reading a file with a 44.1 kHz sample rate linear PCM format. You appear to be storing 16 kHz ALaw format data into that file, which may be the wrong format for either the data or the file.</p>
33,328,442
0
<p>I have done this job,I have just edited <code>jquery</code></p> <pre><code>$(".left-menu-button").click(function() { $(this).parent().children('.left-menu-content').toggle("slow", function() { }); }); </code></pre>
38,729,249
0
Is Scope of SharedPreferences Limited to One Time Use? <p>I am curious about sharedPreferences and my real question is <code>Variable stored using sharedPreferences in one activity can be fetched in second activity but can i get the value of variable again in third activity ? does it provide this usage? if not How can i achieve this task?</code> </p>
8,368,174
0
<p>It looks like you're using the same date object for both log statements. Add this before your "download complete" log statement:</p> <pre><code>dt = new Date(); </code></pre> <p>By the way, all those methods (getSeconds, getHours, etc) of Date are depricated. You can get the timing simply by doing a System.currentTimeMillis() at the beginning of the download and again at the end and subtracting. This is the total duration in milliseconds which you can convert into hours/min/seconds if you want.</p>
3,207,889
0
<p>Keep it simple. How about this?</p> <pre><code>while ( my $tag = $parser-&gt;get_tag('input') ) { my $name = $tag-&gt;get_attr('name'); next unless defined $name and $name eq 'hush_username'; print "Value: ", $tag-&gt;get_attr('value'), "\n"; } </code></pre>
14,250,872
0
IE7 css styles being applied inconsistently <p>I apologize if this question has been asked before. I am relatively new to CSS and web development. I am developing a web app that has to target IE7. For the life of me I cannot figure out why on the "assignments" page the unordered list is formatted one way and on the "Employee Data" page it is not being formatted at all. Both pages are using the same style sheet. I am only having this issue in IE7 and IE8, the newer versions work fine.</p> <p>Here is a link to the site </p> <p><a href="http://www.j-holmes.net/" rel="nofollow">http://www.j-holmes.net/</a></p> <p>Again, I apologize if this question has been asked before. I can't think of any more search criteria to google up an answer for this.</p>
33,877,521
0
<p>Use double brackets <code>[[]]</code> to create a list instead:</p> <pre><code>fit_ &lt;- list() for (i in 1:20){ fit_[[i]] &lt;- lm(y ~ x1 + x2 + x3, data=mydata) } </code></pre> <p>Or use Roman's solution in the comments if you want to have separate objects <code>fit_1</code>, <code>fit_2</code>, etc.</p>
11,705,138
0
<p><code>opa src/*.opa</code> should work ;)</p> <p>Otherwise, it's just basic Makefile manipulation i guess.</p>
31,890,607
0
<p>If you turn stop on errors on, then interrupting it, even with ctrl+c, brings you to the place where it was executing and you have the whole workspace available:</p> <pre><code>dbstop if error </code></pre>
21,332,719
0
Hide on-screen menu bar android from code <p>Is there a way to hide on-screen menu bar in an android app from code?</p> <p><a href="https://www.dropbox.com/s/cbs7rbac07rs5ks/Screenshot%202014-01-24%2014.24.48.png" rel="nofollow">https://www.dropbox.com/s/cbs7rbac07rs5ks/Screenshot%202014-01-24%2014.24.48.png</a></p>
14,931,398
0
<p>You can do this with few simple lines of code</p> <pre><code>NSString *documentDirectoryPath = // Initialize with Documents path BOOL isDir = NO; NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *files = [fileManager contentsOfDirectoryAtPath:documentDirectoryPath error:NULL]; NSMutableArray *directoriesPaths = [NSMutableArray array]; for (NSString *filePath in files) { if ([fileManager fileExistsAtPath:filePath isDirectory:&amp;isDir] &amp;&amp; isDir) { [directoriesPaths addObject:filePath]; } } NSLog(@"directories %@", directoriesPaths); </code></pre>
35,819,031
0
<p>A simple way to do this is to send a response back to the client in the form of html:</p> <pre><code>response.setContentType("text/html"); PrintWriter out = response.getWriter(); //Returns a PrintWriter object that can send character text to the client out.println("&lt;h1&gt;Registered successfully&lt;/h1&gt;"); </code></pre> <p>For more information, go through these <a href="http://www.tutorialspoint.com/servlets/index.htm" rel="nofollow">Tutorials</a></p> <p>If you dont want the page to reload then you should:</p> <ul> <li>send Ajax request to your servlet via Javascript </li> <li>check the values sent to your Servlet as you are doing right now and send the response as I mentioned in code above (you can send a boolean value for success or failure to later check in Javascript)</li> <li>you you will receive response data in Javascript as Ajax response</li> <li><p>now you can set the result of response accordingly in your specific div.</p> <p>See <a href="http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax">this</a> answer for more information on how to use Ajax with Servlets. </p></li> </ul>
8,352,852
0
<p>I guess you would be better off with <a href="http://office.microsoft.com/en-ca/web-apps/" rel="nofollow">Office Web Apps,</a> than. Refer for similar threads <a href="http://stackoverflow.com/questions/726293/can-you-do-complex-editing-of-word-documents-in-a-browser">here</a> and <a href="http://stackoverflow.com/questions/1053042/open-word-document-in-browser-with-inline-editing">here</a></p>
27,196,984
0
<p>HTML5 practices are all about semantics. If your bold text is bold because you want to place a strong emphasis on that text, you should use <a href="http://html5doctor.com/i-b-em-strong-element/" rel="nofollow"><code>&lt;strong&gt;</code></a>. If your highlighted text is highlighted because it's something you want to mark to draw attention to it, try the <a href="http://html5doctor.com/draw-attention-with-mark/" rel="nofollow"><code>&lt;mark&gt;</code></a> element. Style those elements as you wish.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>You will &lt;strong&gt;probably&lt;/strong&gt; find most browsers have quite sensible defaults for &lt;mark&gt;styling these elements&lt;/mark&gt;.</code></pre> </div> </div> </p>
22,799,804
0
<pre><code>' VS.net 2013. Use the "Shown" event. ' GotFocus isn't soon enough. Private Sub Form_Shown(sender As Object, e As EventArgs) Handles Me.Shown TB.SelectionLength = 0 End Sub </code></pre>
14,232,824
0
<p>Unless you convert the project with the <code>one:convert</code> goal, you won't be able to. You have to understand that Maven 1.x and 2.x are extremely different. Either just install 1.x and build the project with it, or convert it, if that is at all possible, as the conversion plugin will not solve everything for you for more complicated projects.</p>
12,834,338
0
<p>Since you are using jQuery you can use:</p> <pre><code>$(function(){ var myObject = $('#container'), offset = myObject.offset(); //then you can access offset.top and offset.left }); </code></pre>
10,334,307
0
<p><strong>disclaimer</strong> I dont' recommend you expose <code>object</code> on a WCF endpoint; altho this appears 'flexible' this is not a good idea as you have not specified what sort of information will be served by your service.</p> <p><em>and now for an answer</em></p> <p>If your WCF call is being consumed by an ajax call and as you put it <code>Javascript client just doesn't care.</code> then why not make your WCF call simply return a string? Then the internals of your WCF call can serialize the <code>Dictionary&lt;string, object&gt;</code> using the JavaScriptSerializer</p> <pre><code>public string MyServiceMethod() { var hash = new Dictionary&lt;string, object&gt;(); hash.Add("key1", "val1"); hash.Add("key2", new { Field1 = "field1", Field2 = 42}); var serialized = new JavaScriptSerializer().Serialize(hash); return serialized; } </code></pre> <p><strong>disclaimer2</strong> This is a means to the end (since you asked the question) - For a production quality application I would have a well defined interface so it was clear what was being requested and sent back over the wire.</p>
21,127,641
0
<p>You need to remove the <code>&amp;</code> operator when passing the <code>client</code> variable to the <code>lpParameter</code> param of <code>CreateThread()</code>:</p> <pre><code>//CreateThread(..., &amp;client, ...); CreateThread(..., client, ...); </code></pre> <p><code>SendToPeer()</code> is expecting to receive a <code>Peer*</code> pointer but you are actually sending it a <code>Peer**</code> pointer instead.</p>
2,245,372
0
<p>No. Newer matches overwrite older matches. Perhaps the <code>limit</code> argument of <code>explode()</code> would be helpful when exploding.</p>
6,484,689
0
<p>You can split on an empty string:</p> <pre><code>var chars = "overpopulation".split(''); </code></pre> <hr> <p>If you just want to access a string in an array-like fashion, you can do that without <code>split</code>:</p> <pre><code>var s = "overpopulation"; for (var i = 0; i &lt; s.length; i++) { console.log(s.charAt(i)); } </code></pre> <hr> <p>You can also access each character with its index in the normal fashion:</p> <pre><code>var s = "overpopulation"; console.log(s[3]); // logs 'r' </code></pre>
21,126,381
0
<pre><code>&lt;%= i.awards.sum(:points) %&gt; </code></pre> <p>For for the sum of all points from all recipes:</p> <pre><code>&lt;%= @user.recipes.map { |r| r.awards.sum(:points) }.sum %&gt; </code></pre> <p>Although it might be sensible to do this calculation within the model. You'll remove a lot of duplication that way if you use it in more than one view.</p> <p>UPDATE:</p> <p>As per the comments below, you could also ask the DB to calculate the sum for you:</p> <pre><code>&lt;%= @user.recipes.joins(:awards).sum('awards.points') %&gt; </code></pre>
2,369,874
0
<p>Setting the website's trust level to "full" has no bearing on how script runs on the client browser, it affects how the server runs your site.</p> <p>Generally, you are not allowed to muck around on a "client PC" in this way, for fairly obvious reasons, and depending on where (and how) this code is running (is it in a client script block or on the server?) will affect the permissions needed.</p>
3,344,788
0
<p>There are a lot of other conditions that I've been hearing about with non-relational systems vs relational. I prefer this terminology over sql/no-sql as I personally think it describes the differences better, and several of the "no-sql" servers have sql add-ons, so anyway.... what sort of concurrency pattern or tranaction isolation is required in your system. One of the purported differences between rel and non-rel dbs is the "consistent-always", "consistent-mostly" or "consistent-eventually". Relation dbs by default usually fall into the "consistent-mostly" category and with some work, and a whole lot of locking and race conditions, ;) can be "consistent-always" so everyone is always looking at the most correct representation of a given piece of data. Most of what I've read/heard about non-rel dbs is that they are mainly "consistent-eventually". By this it means that there may be many instances of our data floating around, so user "A" may see that we have 92 widgets in inventory, whereas user "B" may see 79, and they may not get reconciled until someone actually goes to pull stuff from the warehouse. Another issue is mutability of data, how often does it need to be updated? The particular non-rel db's I've been exposed to have more overhead for updates, some of them having to regenerate the entire dataset to incorporate any updates.</p> <p>Now mind, I think non-rel/nosql are great tools if they really match your use case. I've got several I'm looking into now for projects I've got. But you've got to look at all the trade offs when making the decision, otherwise it just turns into more resume driven development.</p>
17,998,503
0
Accessing variables across different scopes in Javascript & YUI 3 <p>I'm new to YUI 3 and YUI in general. I'm trying to pass data between classes and methods.</p> <p>In this example I'm using the <strong>gallery-sm-treeview</strong> plugin to build a file tree. There's a class named <strong>TreeView</strong> to initialize and render the tree. There's another class named <strong>MenuBar</strong> where I want to access some of the plugin-specific methods through <strong>TreeView</strong>'s getter method.</p> <p>However, the variable <strong>var treeview</strong> inside the YUI().use() scope is of course not accessible from outside. How to do it?</p> <pre><code>YUI.add('treetool.TreeView', function(Y) { Y.treetool.TreeView = Class.extend({ init : function(elementId) { YUI({ gallery: 'gallery-2013.06.20-02-07'}).use('gallery-sm-treeview', function (Y) { // Create a new TreeView with a few nodes. var treeview = new Y.TreeView({ // Tell the TreeView where to render itself. container: elementId, // Populate the treeview with some tree nodes. nodes: [ {label: 'Node 1'}, {label: 'Node 2', children: [ {label: 'Child 1'}, ] }); // Render the treeview inside the #treeview element. treeview.render(); }); }, getSomeData : function () { return treeview.getSelectedNodes(); } }); }, '0.0.1', { requires : [ 'jquery' ] }); </code></pre> <p>and</p> <pre><code>YUI.add('treetool.MenuBar', function(Y) { Y.treetool.MenuBar = Class.extend({ init : function(treeObj) { var someData = treeObj.getSomeData(); }, }); }, '0.0.1', { requires : [ 'jquery' ] }); </code></pre>
10,421,426
0
<p>Problem since solved. I was given the answer by Aaron Heckmann over on the <a href="https://groups.google.com/forum/#!topic/mongoose-orm/0p-rhtcJdng">mongoose Google Group</a>:</p> <blockquote> <p>Always declare your child schemas before passing them to you parent schemas otherwise you are passing undefined. </p> <p>SubCommentSchema should be first, then Comment followed by BlogPost.</p> </blockquote> <p>After reversing the schemas it worked.</p>
19,378,226
1
Check if a word is a palindrome <p>First of all, I have checked if this question relates to any old posts, but these haven't helped me. If it does relate to any old posts, I am terribly sorry.</p> <p>This relates to a practice python coding exercise that I have been working on.</p> <p>As the code is incomplete, I am going to explain what the program does below:</p> <p>The program asks the user for an input, any input. It then checks if the input is a palindrome, and prints different texts depending on the outcome (wether or not the user's input is a palindrome).</p> <p>I am completely unsure on how to solve this. Any help is appreciated.</p>
39,385,940
0
<pre class="lang-js prettyprint-override"><code>^[a-zA-Z0-9]+(?:\.?[\w!#$%&amp;'*+/=?^`{|}~\-]+)*@[a-zA-Z0-9](?:\.?[\w\-]+)+\.[A-Za-z0-9]+$ </code></pre> <p>No <code>..</code> and at least 1 <code>.</code> and 1 <code>@</code>.<br> Also starts/ends with letters/numbers.</p> <p>The <code>^</code> (start) and <code>$</code> (end) were just added to match a whole string, not just a substring. But you could replace those by a word boundary <code>\b</code>.</p> <p>An alternative where the special characters aren't hardcoded:</p> <pre><code>^(?!.*[.]{2})[a-zA-Z0-9][^@\s]*?@[a-zA-Z0-9][^@\s]*?\.[A-Za-z0-9]+$ </code></pre>
17,739,105
0
<p>You can use this code as well to fetch your twitter feeds to any webpage. Please try by putting it to server (because some times i saw problem of not fetching feeds on local machine, but don't worry it would work on server - say with .php file extension)</p> <pre><code> &lt;script&gt; var twitterFetcher=function(){function t(d){return d.replace(/&lt;b[^&gt;]*&gt;(.*?)&lt;\/b&gt;/gi,function(c,d){return d}).replace(/class=".*?"|data-query-source=".*?"|dir=".*?"|rel=".*?"/gi,"")}function m(d,c){for(var f=[],e=RegExp("(^| )"+c+"( |$)"),g=d.getElementsByTagName("*"),b=0,a=g.length;b&lt;a;b++)e.test(g[b].className)&amp;&amp;f.push(g[b]);return f}var u="",j=20,n=!0,h=[],p=!1,k=!0,l=!0,q=null,r=!0;return{fetch:function(d,c,f,e,g,b,a){void 0===f&amp;&amp;(f=20);void 0===e&amp;&amp;(n=!0);void 0===g&amp;&amp;(g=!0);void 0===b&amp;&amp;(b=!0); void 0===a&amp;&amp;(a="default");p?h.push({id:d,domId:c,maxTweets:f,enableLinks:e,showUser:g,showTime:b,dateFunction:a}):(p=!0,u=c,j=f,n=e,l=g,k=b,q=a,c=document.createElement("script"),c.type="text/javascript",c.src="//cdn.syndication.twimg.com/widgets/timelines/"+d+"?&amp;lang=en&amp;callback=twitterFetcher.callback&amp;suppress_response_codes=true&amp;rnd="+Math.random(),document.getElementsByTagName("head")[0].appendChild(c))},callback:function(d){var c=document.createElement("div");c.innerHTML=d.body;"undefined"=== typeof c.getElementsByClassName&amp;&amp;(r=!1);var f=d=null,e=null;r?(d=c.getElementsByClassName("e-entry-title"),f=c.getElementsByClassName("p-author"),e=c.getElementsByClassName("dt-updated")):(d=m(c,"e-entry-title"),f=m(c,"p-author"),e=m(c,"dt-updated"));for(var c=[],g=d.length,b=0;b&lt;g;){if("string"!==typeof q){var a=new Date(e[b].getAttribute("datetime").replace(/-/g,"/").replace("T"," ").split("+")[0]),a=q(a);e[b].setAttribute("aria-label",a);if(d[b].innerText)if(r)e[b].innerText=a;else{var s=document.createElement("p"), v=document.createTextNode(a);s.appendChild(v);s.setAttribute("aria-label",a);e[b]=s}else e[b].textContent=a}n?(a="",l&amp;&amp;(a+='&lt;div class="user"&gt;'+"&lt;/div&gt;"),a+='&lt;p class="tweet"&gt;'+t(d[b].innerHTML)+"&lt;/p&gt;",k&amp;&amp;(a+='&lt;p class="timePosted"&gt;'+e[b].getAttribute("aria-label")+"&lt;/p&gt;")):d[b].innerText?(a="",l&amp;&amp;(a+='&lt;p class="user"&gt;'+f[b].innerText+"&lt;/p&gt;"),a+='&lt;p class="tweet"&gt;'+d[b].innerText+"&lt;/p&gt;",k&amp;&amp;(a+='&lt;p class="timePosted"&gt;'+e[b].innerText+"&lt;/p&gt;")):(a="",l&amp;&amp;(a+='&lt;p class="user"&gt;'+f[b].textContent+ "&lt;/p&gt;"),a+='&lt;p class="tweet"&gt;'+d[b].textContent+"&lt;/p&gt;",k&amp;&amp;(a+='&lt;p class="timePosted"&gt;'+e[b].textContent+"&lt;/p&gt;"));c.push(a);b++}c.length&gt;j&amp;&amp;c.splice(j,c.length-j);d=c.length;f=0;e=document.getElementById(u);for(g="&lt;ul&gt;";f&lt;d;)g+="&lt;li&gt;"+c[f]+"&lt;/li&gt;",f++;e.innerHTML=g+"&lt;/ul&gt;";p=!1;0&lt;h.length&amp;&amp;(twitterFetcher.fetch(h[0].id,h[0].domId,h[0].maxTweets,h[0].enableLinks,h[0].showUser,h[0].showTime,h[0].dateFunction),h.splice(0,1))}}}(); /* * ### HOW TO CREATE A VALID ID TO USE: ### * Go to www.twitter.com and sign in as normal, go to your settings page. * Go to "Widgets" on the left hand side. * Create a new widget for what you need eg "user timeline" or "search" etc. * Now go back to settings page, and then go back to widgets page, you should * see the widget you just created. Click edit. * Now look at the URL in your web browser or see the script generated below the widget, you will see a long number like this: * 345735908357048478 in url or data-widget-id="345095893361512448" in the generated code * Use this as your ID below instead! */ /*************** * twitterFetcher.fetch('Put your twitter id here', 'ID of the container e.g id tweets of container div') */********************* twitterFetcher.fetch('345095893361512448', 'tweets', 5, true); function dateFormatter(date) { return date.toTimeString(); } &lt;/script&gt; &lt;div id="tweets" style="width: 200px;float:left;overflow:hidden"&gt;&lt;/div&gt; </code></pre>
35,081,638
0
How to show same video in two VideoViews simultaneously <p>I'm working with VideoView and I'm trying to show same video in two Videoviews like this <a href="https://play.google.com/store/apps/details?id=co.mobius.vrcinema" rel="nofollow">application</a></p> <p>I'm following this <a href="http://stackoverflow.com/questions/10023605/how-can-i-play-two-video-on-one-screen">link</a> to show the video in two VideoViews but I'm getting delay in both audio and video on both videoviews so please help me to solve this problem. I need to play the video at the same time without any delay</p> <p>Thank you..</p>
36,841,103
0
Java recursion sum of number non divisible by specific number <p>I have to find sum of the all even numbers that are not divisible by 7 using recursion. I tried this code but it seems I am making mistake somewhere because it returns 0: </p> <pre><code>public static void main(String[] args) { System.out.println(specialSum(50)); } public static int specialSum(int a) { if ((a &gt;= 1) &amp;&amp; ((specialSum(a-1))%7 !=0)) { return a + specialSum(a -1); } else{ return 0; } } } </code></pre>
21,170,663
0
<p>Heroku dynos are all running on machines within Amazon EC2 us-east-1 data center. They do not have any restrictions/firewalls on outgoing connections.</p> <p>As long as you have the proper Security Group settings to allow the connections from your dynos to your own EC2 instance, you should be good.</p> <p>It sounds like you haven't correctly opened up access from within us-east-1 to your instance. Double check your security group.</p> <p>Information on how to edit the correct security group:</p> <ol> <li>Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.</li> <li>Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave 0.0.0.0/0 in source field and click Add Rule, then Apply rule changes.</li> </ol>
6,451,581
0
PHP Login application - Check if username already exists when creating a new user <p>The title tells pretty much everthing, that needs to be said. I'm having a registration code looking like this: </p> <p>I wan't it to check, if the username entered already exists, if it does - write and $errMsg = ""; and echo it out later.. I hope you can help me, thanks. </p> <pre><code>if(isset($_POST['username']) &amp;&amp; isset($_POST['password']) &amp;&amp; isset($_POST['name']) &amp;&amp; isset($_POST['last_name']) &amp;&amp; isset($_POST['company'])){ if($username === '') { $errMsg = "Du skal udfylde brugernavn"; } elseif($password === ''){ $errMsg = "Du skal udfylde password"; } elseif($name === ''){ $errMsg = "Du skal udfylde navn"; } elseif($last_name === ''){ $errMsg = "Du skal udfylde efternavn"; } elseif($company === ''){ $errMsg = "Du skal udfylde firma"; } $sql = ("SELECT * FROM members WHERE username ='$username'"); $result = mysql_query($sql) or die('error'); $row = mysql_fetch_assoc($result); if(mysql_num_rows($result)) { $errMsg = 'Brugernavn findes, vælg et andet.'; } else { $sql = ("INSERT INTO members (username, password, name, last_name, company, salt)VALUES('$username', '$password', '$name', '$last_name', '$company', '$salt')")or die(mysql_error()); if(mysql_query($sql)) echo "Du er oprettet som profil."; } }//End whole if </code></pre>
14,374,814
0
<p>Ok one only learns by example, stop using the mysql_functions(), They are no longer maintained and are officially deprecated. And in PHP 5.6 they will most likely be removed, rendering you code broken.</p> <p>Move over to PDO with prepared querys. A Port of your current code using PDO:</p> <pre><code>&lt;?php // SQL Config $config['sql_host']='surveyipad.db.6420177.hostedresource.com'; $config['sql_db'] ='surveyipad'; $config['sql_user']='tom'; $config['sql_pass']='ben'; // SQL Connect try { $db = new PDO("mysql:host=".$config['sql_host'].";dbname=".$config['sql_db'], $config['sql_user'], $config['sql_pass']); $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); }catch (Exception $e){ die('Cannot connect to mySQL server.'); } // Check for POST, add isset($_POST['device_Id']) ect to add validations if($_SERVER['REQUEST_METHOD']=='POST'){ // Build your query with placeholders $sql = "INSERT INTO survey_responsese_pfizer (device_Id,R1,R2,R3,comment,update_date_time) VALUES (:device_Id, :R1, :R2, :R3, :comment, :update_date)"; // Prepare it $statement = $db-&gt;prepare($sql); // Assign your vairables to the placeholders $statement-&gt;bindParam(':device_Id', $_POST['device_Id']); $statement-&gt;bindParam(':R1', $_POST['R1']); $statement-&gt;bindParam(':R2', $_POST['R2']); $statement-&gt;bindParam(':R3', $_POST['R3']); $statement-&gt;bindParam(':comment', $_POST['comment']); $statement-&gt;bindParam(':update_date', $_POST['update_date_time']); // Execute the query $statement-&gt;execute(); echo htmlspecialchars($device_Id); } ?&gt; </code></pre> <p>Untested tho, hope it helps.</p>
39,870,541
0
<p>Add this style, this might help,</p> <pre><code>.ui-widget.ui-widget-content { left: auto !important; right: 160px !important; } </code></pre> <p>make sure you have added the style in proper <code>@media</code> statement. I have tested in Full HD, 1366 monitor. Screenshot attached.<a href="https://i.stack.imgur.com/BYJwA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BYJwA.png" alt="enter image description here"></a></p>
7,669,403
0
correct way to display image from php onto page <p>I am not getting my image correctly. I am unsure what is happening. First things first, the image is coming out of a mysql query. Little confused about how to make that image ready for a ajax call?</p> <p>here is how I get the image out mysql</p> <pre><code> if(mysql_query("insert into Personal_Photos (Email, Pics) values('$email', '$data')")) { $query="select Pics, MAX(ID) from Personal_Photos where Email='$email'"; $result=mysql_query($query) or die("Error: ".mysql_error()); $row=mysql_fetch_array($result); //$mime = 'image/yourtype'; //$base64 = base64_encode($contents); //$uri = "data:$mime;base64,$base64"; //header("Content-type: image/jpg"); echo '&lt;img src="data:image/jpeg;base64'.base64_encode($row['Pics']).'"/&gt;'; } </code></pre> <p>the jquery that I use is like so</p> <pre><code>$('#profilepicbutton').live('change', function(){ $("#preview").html(''); $("#preview").html('&lt;img src="loader.gif" alt="Uploading...."/&gt;'); $("#registerpt3").ajaxForm({ target: '#preview', success: function(data) { $("#preview").html(''); $("#preview").append(data); } }).submit(); }) </code></pre>
14,433,409
0
How can I run Selenium (rspec2/capybara) tests as if though dial up or mobile connection? <p>I'd like to run my test suite as if I were on a mobile or dial up connection. I'm using a rails stack with rspec2, selenium. Any advice?</p>
2,250,955
0
<p>I had initially thought of using composite commands. But by going through documentation it may not fit my requirements. </p> <p>Ex : Application supports 40 views Main region -> 20 Views that are active , all the view models are derived from baseviewmodel. </p> <p>toolbar -> save button -> databinding to compositesaveallcommand(activeaware monitor enabled) baseviewmodel -> save command -> registers/ unregisters based on specific filter conditions to compositesaveallcommand</p> <p>when user clicks save button ,compositesaveallcommand looks for all registered commands that are active, and checks for all registered viewmodel commands calls (canexecute method, and all registered commands need to return true) then invokes child commands ( execute method) .</p> <p>But in my case if the user make modifications in a single view , remaining 19 views there are no modifications. But I would like to execute save for single view. Looks like composite command will not invoke registered comamnds unless it can execute all.</p>
38,188,912
0
Sonata admin form mapper one-to-many relation with too many entries <p>I have a performance problem with sonata.</p> <p>I built a form with a one-to-many relation that works great between operation on several products, everything is fine in dev environment, but in production, I have 250000 products to be managed that makes queries very slow… I have an ajax query to replace my selector's content according to the maker of the product, but the first call (which param all the CRUD logic) is far too long…</p> <p>Here is my form mapper </p> <pre><code>-&gt;add( 'operationhasproducts', 'sonata_type_model', array( 'class' =&gt; 'MyBundle\Entity\Operationhasproducts', 'query' =&gt; $this-&gt;modelManager-&gt;createQuery('MyBundle\Entity\Product'), 'multiple' =&gt; true, 'by_reference' =&gt; false, 'btn_add' =&gt; false, 'required' =&gt; false ) ) </code></pre> <p>How can I keep the logic without loading 250000 products on loading the page </p> <p>I tried to put <code>'query'=&gt; $this-&gt;modelManager-&gt;createQuery('MyBundle\Entity\Product')-&gt;setMaxResults(10),</code> the form displays but then the crud logic no longer works, I have a data transformation error</p> <pre><code>Symfony\Component\Validator\ConstraintViolation Object(Symfony\Component\Form\Form).children[operationhasproducts] = [0 =&gt; 2739, 1 =&gt; 29217] Caused by: Symfony\Component\Form\Exception\TransformationFailedException Unable to reverse value for property path "operationhasproducts": Could not find all matching choices for the given values Caused by: Symfony\Component\Form\Exception\TransformationFailedException Could not find all matching choices for the given values </code></pre> <p>Any help will be welcome</p>
36,033,212
0
Mathematica DSolve diff. equation over a particular domain <p>I am looking for a way to solve the following differential equation:</p> <pre><code>DSolve[(1 - b*Abs[z])*f[z]/a == f''[z], f[z], z] </code></pre> <p>Therefore I tried to DSolve it distinguishing z>0 from z&lt;0 such as:</p> <pre><code>DSolve[(1 - b*z)*f[z]/a == f''[z], f[z], z&gt;0] </code></pre> <p>But I still does not work. Maybe adding a domain explicitly would help but I can't find a way to do so.</p> <p>Does anyone has any idea how do do such things?</p> <p>Thank you for your help and time</p>
4,534,254
0
changing the value given by date("U") without changing the server time <p>ive been using date("U") allover my script when suddenly i found that i need to add timezone option in the website , which means all date("U") should look like <code>date("U") + $someTime</code> , is there any way i could change the time that the option date("U") displays without the need to modify the date("U")'s in the script and without modifying the server time ?</p> <p>something like setting the date read by the 'date' function + or - some hours ???</p>
20,416,398
0
DocPad v6.57.0 - Failed to load/Unable to parse <p>I am new to DocPad, and I was running the KitchenSink demo with no issues.</p> <p>I then decided to follow the Beginner Guide on the DocPad website (no skeleton), and I am hitting a snag at "Installing the template engine" section. </p> <p>I got this warning when I tried to run docpad. I get the warning even if I stop DocPad (ctrl+c) and restart it. I am on OSX.</p> <pre> info: Generating... warning: Failed to load the file: /path-to-project/src/documents/about.html The error follows: warning: An error occured: Unable to parse. warning: Failed to load the file: /path-to-project/src/documents/index.html The error follows: warning: An error occured: Unable to parse. </pre>
38,914,083
0
<p>you can use the <code>title</code> property</p> <pre><code>&lt;p class="hover" title="{{item.name}}"&gt; </code></pre> <p>or if you what to use angular for it and not the tooltip</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('app', []) .controller('myController', function($scope) { $scope.myText = "some very very very very very long text"; }) .directive('hoverText', function () { return { restrict: 'A', scope: { hoverText: '=', maxChars: '=' }, link: function (scope, element) { element.text(scope.hoverText.substr(0, scope.maxChars) + '...') element.on('mouseenter', function() { element.text(scope.hoverText); }); element.on('mouseleave', function() { element.text(scope.hoverText.substr(0, scope.maxChars) + '...'); }); } }; })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>p</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="app" ng-controller="myController"&gt; &lt;p hover-text="myText" max-chars="20"&gt; &lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
20,792,799
0
<p>I know this won't help too much, but this code works perfectly fine in Chrome and Firefox</p> <p><a href="http://jsbin.com/iluXOGe/2/edit" rel="nofollow">http://jsbin.com/iluXOGe/2/edit</a></p>
10,584,163
0
<h2>No</h2> <p>Is the simple answer, you have to extend CIs functionality and use a library from a third party to provide these features for you. CI doesn't focus on the aesthetics of the "front-end". Its primary focus was "back-end". </p> <h2>Your Options:</h2> <p>look into Phil Sturgeons template library, and CI Sprinkles library first is for layout/theme/partials management, second is for asset management js/css minification and caching.</p> <p>Phil's Template Library: <a href="http://philsturgeon.co.uk/demos/codeigniter-template/user_guide/" rel="nofollow">http://philsturgeon.co.uk/demos/codeigniter-template/user_guide/</a></p> <p>Sprinkles Library: <a href="https://github.com/edmundask/Sprinkle" rel="nofollow">https://github.com/edmundask/Sprinkle</a></p> <h3>Or build your own basic template library</h3> <p>This is a great intro video how to do such. I have used this in the past, before i got into using Sparks. <a href="http://www.youtube.com/watch?v=gvGymDhY49E" rel="nofollow">http://www.youtube.com/watch?v=gvGymDhY49E</a></p> <h3>you can use Sparks to make lib management a bit easier</h3> <p>In 2.1 sparks aren't included however it is in the dev builds of CI so im sure at a later date it will be merged in with the base code. FOr now you can use this site to install Sparks to help you manage third party libraries.</p> <p><a href="http://getsparks.org" rel="nofollow">http://getsparks.org</a></p>
13,365,989
0
<p>$a == $b Equal TRUE if $a is equal to $b after type juggling. $a === $b Identical TRUE if $a is equal to $b, and they are of the same type. </p> <p>it looks that</p> <p>if you check 0 against a string with == then PHP returns true:</p> <p>php -r 'var_dump(0 == "statuses");' -> returns TRUE</p> <p>but not if your string has a number at the beginning:</p> <p>php -r 'var_dump(0 == "2statuses");' -> returns FALSE</p> <p>from the specs I get it that it attempts a conversion - in this case the string to number.</p> <p>so better use ===</p> <p><a href="http://php.net/manual/en/language.operators.comparison.php" rel="nofollow">http://php.net/manual/en/language.operators.comparison.php</a></p>
22,642,695
0
Proper Unit Test for ASP.NET MVC5 <p>I have got following code and I have no clue which proper Unit Test I have write out for those methods and how it can be done. Basically I would like to use NUnit.Framework. </p> <p>Thank you in advance for ANY clue!</p> <pre><code> [AllowAnonymous] public ActionResult ForgotPassword(string id) { var model = new ForgotPasswordViewModel(); if (!string.IsNullOrEmpty(id)) { #region Process Reset Password Key try { var forgotPasswordEvent = AppModel.ForgotPasswordEvents.SingleOrDefault(x =&gt; x.UIDHash == id); if (forgotPasswordEvent != null) { var stringToHash = string.Format("{0}---{1}---{2}", forgotPasswordEvent.UID.ToString(), forgotPasswordEvent.UserId.ToString(), forgotPasswordEvent.Created.ToString()); var readyHash = SecurityHelper.GetHashString(stringToHash); if (id == readyHash) { var forgotPasswordEventUserId = forgotPasswordEvent.UserId.ToString(); var realUser = AppModel.AspNetUsers.SingleOrDefault(x =&gt; x.Id == forgotPasswordEventUserId); if (realUser != null) { var resetPasswordViewModel = new ResetPasswordViewModel(); resetPasswordViewModel.ResetPasswordData = id; resetPasswordViewModel.UserName = realUser.UserName; return RedirectToAction("ResetPassword", "Account", resetPasswordViewModel); // ResetPassword(resetPasswordViewModel); } } } else { return RedirectToAction("Index", "Home"); } } catch (Exception) { } #endregion } #region Check if the user is logged in and fill out fileds for him. var sessionManager = SessionWrapper.GetFromSession&lt;SessionManager&gt;("_SessionManager"); if (sessionManager != null) { var clientId = sessionManager.AppUser.ClientId; if (clientId != null) { model.Email = sessionManager.AppUser.EmailID; model.UserName = sessionManager.AppUser.UserName; model.IsLoggedInUser = true; } } #endregion return View(model); } [HttpPost] [AllowAnonymous] public ActionResult ForgotPassword(ForgotPasswordViewModel model, FormCollection formCollection) { if (ModelState.IsValid) { try { #region Check user input var user = AppModel.AspNetUsers.SingleOrDefault(x =&gt; x.UserName == model.UserName); var areErrors = false; if (user == null) { ModelState.AddModelError("UserDoesnotExist", DLMModelEntities.Properties.Resource.UserDoesNotExist); areErrors = true; } if (user.EmailID != model.Email) { ModelState.AddModelError("EmailIsWrong", DLMModelEntities.Properties.Resource.EmailIsWrong); areErrors = true; } if (areErrors) return View(model); #endregion #region Send Email and inform user try { var forgotPasswordEvent = new ForgotPasswordEvent(); var resetPasswordEmailUserState = new ResetPasswordEmailUserState(); resetPasswordEmailUserState.ForgotPasswordEventId = Guid.NewGuid(); resetPasswordEmailUserState.UserId = Guid.Parse(user.Id); resetPasswordEmailUserState.Created = DateTime.Now; forgotPasswordEvent.UID = resetPasswordEmailUserState.ForgotPasswordEventId; forgotPasswordEvent.UserId = resetPasswordEmailUserState.UserId; forgotPasswordEvent.IsSent = false; forgotPasswordEvent.Created = resetPasswordEmailUserState.Created; var stringToHash = string.Format("{0}---{1}---{2}", resetPasswordEmailUserState.ForgotPasswordEventId.ToString(), resetPasswordEmailUserState.UserId.ToString(), resetPasswordEmailUserState.Created.ToString()); forgotPasswordEvent.UIDHash = SecurityHelper.GetHashString(stringToHash); AppModel.ForgotPasswordEvents.Add(forgotPasswordEvent); AppModel.SaveChanges(); var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"); // Set the MailerModel properties that will be passed to the MvcMailer object. var m = new MailerModel(); m.UserName = user.UserName; m.ResetPasswordLink = string.Format("{0}/{1}", Request.Url.AbsoluteUri, forgotPasswordEvent.UIDHash); m.FromEmail = smtp.From; m.Subject = AppConfiguration.ResetEmailSubject; m.ToEmail = model.Email; var client = new SmtpClientWrapper(); client.SendCompleted += (sender, e) =&gt; { if (e.Error != null || e.Cancelled) { // Handle Error } else { try { var forgotPasswordEventsToUpdate = AppModel.ForgotPasswordEvents.SingleOrDefault(x =&gt; x.UID == resetPasswordEmailUserState.ForgotPasswordEventId); if (forgotPasswordEventsToUpdate != null) { forgotPasswordEventsToUpdate.IsSent = true; AppModel.SaveChanges(); } } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } } }; Mailer.PasswordReset(m).SendAsync(resetPasswordEmailUserState, client); model.IsResetEMailSent = true; } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } #endregion } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } } return View(model); } </code></pre>
11,778,636
0
Submit a form with data from other form JSF <p>I have a form that I want to submit with JSF/Richfaces.</p> <p>To execute the form action, I need to be sure a data from another form is valid.</p> <p>So my question is, how can I submit a form with data come from another form ?</p> <p>My code is like this:</p> <pre><code>&lt;h:form id="form1" &gt; &lt;h:inputText id="data" validator="#{myBean.validateData}" /&gt; &lt;/h:form&gt; &lt;h:form id="form2" &gt; &lt;h:inputText id="data2" validator="#{myBean2.validateData2}" /&gt; &lt;a4j:commandLink id="button" action="#{bandeauTarifController.recalculer}" ajaxSingle="true" process="data" &gt; Test link &lt;/a4j:commandLink&gt; &lt;/h:form&gt; </code></pre> <p>I thought the "process" attribute could do this but not.</p> <p>Someone have an idea about that ?</p> <p>Thanks.</p>
21,783,196
0
<p>assuming you are using rake to apply an active record migration. The file path will be relative to where you started rake which I'm sure will be the projects root.</p> <p>The file path would be:</p> <p>content = File.read("app/views/layouts/application.html.erb")</p>
15,276,750
0
<p>By making the assumption that express middleware handling is not broken: Why don't you try to write an injection middleware that is responsible to inject the desired session data and place the injection middleware before your middleware function you want to test?</p> <p>With this approach you don't test client code directly but isolate the injection in your injection middleware.</p>
36,126,439
0
<p>Connectors are quite hit and miss when it comes to sites like the one you are trying..</p> <p>However there is a workaround for this particular site that you might want to try:</p> <p>If you notice when the page has changed to display the email values the url is in the following format: <a href="http://royalenfield.com/locateus/genuine-parts-distributors/" rel="nofollow">http://royalenfield.com/locateus/genuine-parts-distributors/</a>?<strong>country=90&amp;state=4&amp;city=119</strong></p> <p>You could train an extractor to extract just from these types of pages, and then run all the URLs with different <strong>country=X&amp;state=Y&amp;city=Z</strong> </p> <p>This would avoid the temperamental connector steps and having to enable javascript.</p> <p>N.B if you look in the html of the website you can see the values for the 3 fields above.</p> <p>This one is "state":</p> <pre><code>&lt;select id="divState" class="styled width110 hasCustomSelect" style="-webkit-appearance: menulist-button; width: 214px; position: absolute; opacity: 0; height: 30px; font-size: 12px;"&gt; &lt;option value="-1"&gt;Select State&lt;/option&gt; &lt;option value="2"&gt;Andhra Pradesh&lt;/option&gt; &lt;option value="4"&gt;Assam&lt;/option&gt; &lt;option value="5"&gt;Bihar&lt;/option&gt; &lt;option value="6"&gt;Chandigarh&lt;/option&gt; &lt;option value="7"&gt;Chhattisgarh&lt;/option&gt; &lt;option value="10"&gt;Delhi&lt;/option&gt; &lt;option value="11"&gt;Goa&lt;/option&gt; &lt;option value="12"&gt;Gujarat&lt;/option&gt; &lt;option value="13"&gt;Haryana&lt;/option&gt; &lt;option value="15"&gt;Jammu and Kashmir&lt;/option&gt; &lt;option value="16"&gt;Jharkhand&lt;/option&gt; &lt;option value="17"&gt;Karnataka&lt;/option&gt; &lt;option value="18"&gt;Kerala&lt;/option&gt; &lt;option value="20"&gt;Madhya Pradesh&lt;/option&gt; &lt;option value="21"&gt;Maharashtra&lt;/option&gt; &lt;option value="27"&gt;Orissa&lt;/option&gt; &lt;option value="29"&gt;Punjab&lt;/option&gt; &lt;option value="30"&gt;Rajasthan&lt;/option&gt; &lt;option value="32"&gt;Tamil Nadu&lt;/option&gt; &lt;option value="501"&gt;Telangana&lt;/option&gt; &lt;option value="34"&gt;Uttar Pradesh&lt;/option&gt; &lt;option value="36"&gt;Uttarakhand&lt;/option&gt; &lt;option value="37"&gt;West Bengal&lt;/option&gt; &lt;/select&gt; </code></pre>