pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
5,531,989 | 0 | <p>From your cakephp app you can check if a user exist in the phpbb forums table and you can use the phpbb session to check if a user is logged in.</p> |
10,938,897 | 0 | <p>There are three alternatives for unsolvable hash collisions on open addressing hash tables:</p> <ol> <li>Re-hash the entire table with a different hash function, and hope that no new unsolvable hash collisions occur.</li> <li>Resize the table (with all operations that this might incur), to guarantee some more possible slots.</li> <li>Keep a separate list for unsolvable hash collisions.</li> </ol> <p>None of those options are good. </p> <p>What you should do is to carefully chose your probing method in combination with the hash table size. If your table size was odd, with the same constant step, you would not run in this problem while there was still space in the table.</p> <p>Popular combinations include quadratic probing with a prime-sized hash table, that guarantees insertion success if the table is less than half-full, and <a href="http://stackoverflow.com/a/2349774/1157317">quadratic probing with triangular numbers and power of 2 hash table</a>, that guarantees insertion if the table isn't full. Power of 2 sized hash tables have many advantages, the only defect being that they are unforgiving on the quality of the hash algorithm.</p> |
39,355,129 | 0 | <p>Since you have 4 columns including the primary key column, you have to provide data for all four columns. Hence the first one is <strong>IDENTITY</strong> column, you can provide any value for that column as this column value will not be used but ommitted.</p> <p>In your case if you provide data like it will work:</p> <pre><code>1 11 11 11 1 22 22 22 1 33 55 66 </code></pre> <p>I have checked this and found it works. If you don't have any option to alter the csv file then you can create a staging table without the identity column and perform the bulk insert operation. After that, you can move data from your staging to target table by performing INSERT INTO command. I hope this might solve your problem.</p> |
25,103,303 | 0 | The Python curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling. |
26,114,957 | 0 | <p>this error may happen when you add hammer js in a script tag in your html, if this your case remove it and just depend on requirejs for loading it</p> |
29,889,112 | 0 | where the behavior of private and static method is different from only private method <p>As for my understanding:</p> <p>When a method is static it is </p> <ol> <li>early bind </li> <li>can call with the name of class even before no object is created </li> <li>can call only static member inside it.</li> </ol> <p>I never found any other behaviour of static either at compile time or runtime. <strong>Is there any?</strong></p> <p>When a method is private it is</p> <ol> <li>also early bind </li> <li>can only call inside call so can call directly without object.</li> </ol> <p>For example the <code>hugeCapacity()</code> method in the <code>ArrayList</code> class.</p> <pre><code>private static final int DEFAULT_CAPACITY = 10; private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } </code></pre> <p>Since there are in Java private+static method exist. Why their need occurs. Is it for restriction purpose, to restrict access of non static variables inside a method?</p> |
1,478,465 | 0 | <p>Here is a complete, working example.</p> <h2>Code</h2> <pre><code>USE master GO IF EXISTS (SELECT * FROM sys.databases WHERE name = N'A') DROP DATABASE A GO IF EXISTS (SELECT * FROM sys.databases WHERE name = N'B') DROP DATABASE B GO CREATE DATABASE A GO CREATE DATABASE B GO USE A GO CREATE TABLE X (Col1 varchar(10) NOT NULL) GO USE B GO CREATE TABLE X2 (Col1 varchar(10) NOT NULL) GO USE A GO CREATE TRIGGER dbo.trX_Insert ON dbo.X FOR INSERT AS BEGIN INSERT INTO B.dbo.X2 (Col1) SELECT Col1 FROM Inserted END GO INSERT INTO A.dbo.X (Col1) VALUES ('This') INSERT INTO A.dbo.X (Col1) VALUES ('That') GO SELECT * FROM A.dbo.X SELECT * FROM B.dbo.X2 GO </code></pre> <h2>Result</h2> <pre><code>Col1 ---------- This That Col1 ---------- This That </code></pre> |
22,722,188 | 0 | <p><a href="http://www.bootply.com/125688" rel="nofollow">http://www.bootply.com/125688</a></p> <pre><code>.form-control[disabled] { background-color:white; } </code></pre> |
40,900,686 | 1 | Make anaconda jupyter notebook auto save .py script <p>I would like to simply be able to launch the jupyter notebook from Anaconda and have it automatically save a .py script when I save the .ipynb. I tried modifying the <code>jupyter-notebook-script.py</code> in the Anaconda3/envs/env_name/Scripts/ but that wasn't the right way. I know I want to set the <code>post-save-hook=True</code> somewhere.</p> |
5,689,570 | 0 | <p>This behaviour of Joda Time Contrib is fixed in my project Usertype for Joda Time and JSR310. See <a href="http://usertype.sourceforge.net/" rel="nofollow">http://usertype.sourceforge.net/</a> which is practically otherwise a drop in replacement for JodaTime Hibernate.</p> <p>I have written about this issue: <a href="http://blog.jadira.co.uk/blog/2010/5/1/javasqldate-types-and-the-offsetting-problem.html" rel="nofollow">http://blog.jadira.co.uk/blog/2010/5/1/javasqldate-types-and-the-offsetting-problem.html</a></p> <p>Hope this helps,</p> <p>Chris</p> |
32,001,570 | 0 | Issue with experimental gradle: The android plugin must be applied to the project <p>I'm trying to run some native code with the NDK in Android Studio. I have followed the steps shown <a href="http://tools.android.com/tech-docs/new-build-system/gradle-experimental" rel="nofollow">HERE</a> to use the experimental Gradle, but obviously it's not all going smoothly. I'm getting this error: <code>The android or android-library plugin must be applied to the project</code> <br/> Here is my gradle file:</p> <pre><code>apply plugin: 'com.android.model.application' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'io.fabric' model { android { compileSdkVersion = 22 buildToolsVersion = "22.0.1" android.ndk { moduleName = "test" } defaultConfig.with { applicationId = "com.shaperstudio.dartboard" minSdkVersion.apiLevel = 15 targetSdkVersion.apiLevel = 22 versionCode = 1 versionName = "1.0" } } android.buildTypes { release { minifyEnabled = false proguardFiles += file('proguard-rules.pro') } } packagingOptions { exclude = 'META-INF/services/javax.annotation.processing.Processor' } } repositories { maven { url "https://jitpack.io" } maven { url 'https://maven.fabric.io/public' } } buildscript { repositories { jcenter() maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' classpath 'io.fabric.tools:gradle:1.+' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.0' compile 'com.android.support:recyclerview-v7:22.2.0' compile 'com.android.support:design:22.2.0' compile 'com.jakewharton:butterknife:6.1.0' compile 'de.greenrobot:eventbus:2.4.0' apt 'com.bluelinelabs:logansquare-compiler:1.1.0' compile 'com.bluelinelabs:logansquare:1.1.0' compile 'com.birbit:android-priority-jobqueue:1.3' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.facebook.android:facebook-android-sdk:4.1.0' compile 'com.parse.bolts:bolts-android:1.+' compile fileTree(dir: 'libs', include: '*.jar') compile('com.crashlytics.sdk.android:crashlytics:2.4.0@aar') { transitive = true; } } </code></pre> <p>Any help as to why I'm getting this error would be appreciated</p> |
28,000,225 | 0 | How to return a value from a range if cell contains that value <p>I have a list of Names (First and Surname) in A:A. I also have a range called 'Surnames'. How can I apply a formula so that B:B returns the surname only of A:A if that name is found in the range 'Surnames'.</p> <p>I other words, I want to check a cell in A1, if part of this cell value contains a name listed in my range of surnames, return the surname that A1 include in B1.</p> <p>I hope this makes sense, and thank you in advanced :)</p> |
32,306,132 | 0 | <p><code>self</code> when used as first method argument, is a shorthand for <code>self: Self</code> – there are also <code>&self</code> which equals <code>self: &Self</code> and <code>&mut self</code> which equals <code>self: &mut Self</code>.</p> <p><code>Self</code> in method arguments is syntactic sugar for the receiving type of the method (i.e. the type whose <code>impl</code> this method is in. This also allows for generic types without too much repetition.</p> |
7,448,853 | 0 | <p>I have an internationalized product. No translation has been done, but the strings are all externalized, so if we had a desire to ship the product localized for a specific country we could get the files translated, have the product tested, and ship it for use natively in that country.</p> <p>For now the fully internationalized product is all english, but the coding is all done. If someone were to attempt to check in code that was not proper the reviewer could rightly reject it on the grounds that it is not internationalized, and would render the product unable to be fully localized.</p> <p>But since no testing has been done then it really is not internationalized fully yet ... </p> |
34,190,402 | 0 | <p>You would have to use javascript and/or jquery to dynamically add the css class that has the animation to the desired element after the page has been loaded. We can do this with the $document.ready event in jquery.</p> <pre><code>$(document).ready(function(){ $('css selector').addClass('class-that-has-animation-binding'). }); </code></pre> <p>That is how he is doing it on the <a href="https://daneden.github.io/animate.css/" rel="nofollow">main site</a> if you view is source code. </p> |
35,852,133 | 0 | gantt expanding the timeline date <p>So, looking at this page... <a href="http://docs.dhtmlx.com/gantt/samples/01_initialization/01_basic_init.html" rel="nofollow">http://docs.dhtmlx.com/gantt/samples/01_initialization/01_basic_init.html</a></p> <p>Say I want to expand all the way to December 2017 by clicking on a task, and changing the date from there. If I do this, then the edited task goes off screen and gantt doesn't expand dynamically. Is there a function call that would allow me to expand the timeline via javascript? I can't seem to find it</p> |
22,576,321 | 0 | <p>First advice? Take a breath. You can't code effectively if you're pissed off all the time. You are going to make lots of mistakes, so you don't want to be pissed off. Accept that fact and make the code better.</p> <p>I would try passing the parent frame that created the dialog, not the dialog itself. </p> |
8,277,814 | 0 | How to compile *.lua files as resource library? <p>In original, I collect *.lua files in a folder , then load them in *.c files </p> <p>Now I want to hide them(*.lua) and let them in a xx.so or xx.dll </p> <p>if this can be done ?</p> <p>if can , then how to load them in c files ?</p> |
34,128,285 | 0 | <p>One way would be to:</p> <p>a) Copy your JSON to Clipboard (CTRL+C)</p> <p>b) On a Visual Studio class, click on EDIT-> Paste Special -> Paste JSON as classes. This will create the classes equivalent of your JSON for you. Your main object would be named as "Rootobject" and you can change this to whatever name you want.</p> <p>c) Add System.Web.Extensions to your references</p> <p>d) You can convert your JSON to class like so:</p> <pre><code>JavaScriptSerializer serializer = new JavaScriptSerializer(); Rootobject rootObject = serializer.Deserialize<Rootobject>(JsonString); </code></pre> <p>Where <code>JsonString</code> is your API output. </p> |
27,157,856 | 0 | Where do i write if item is not found, and display an appropriate message? <pre><code>public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) { Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the name of the ball you would like to modify: "); String name = keyboard.nextLine(); for (int i = 0; i < count; i++) { if (name.compareToIgnoreCase(nameBallArray[i]) == 0) { System.out.println("Please enter a new name for the ball: "); String ballName = keyboard.nextLine(); System.out.println("Please enter a new weight for the ball: "); int ballWeight = keyboard.nextInt(); System.out.println("Please enter a new hook potential for the ball: "); String hookPotential = keyboard.next(); nameBallArray[i] = ballName; ballWeightArray[i] = ballWeight; hookPotentialArray[i] = hookPotential; System.out.println("The ball list has been updated."); System.out.println(""); } } </code></pre> |
30,337,197 | 0 | <p>The next element after a <code>td</code> cannot be a <code>checkbox:checked</code>, because it is by definition a <code>td</code> element. The syntax of your <code>if</code> statement is also off.</p> <p>You probably meant:</p> <pre><code>if ($(this).closest('td').next().find('input[type=checkbox]:checked').length) { // Do something } </code></pre> <p>or</p> <pre><code>if ($(this).closest('td').next().find('input[type=checkbox]').is(":checked")) { // Do something } </code></pre> <p><strong>Live Example:</strong></p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on('click', '.exempt', function() { if ($(this).closest('td').next().find("input[type=checkbox]:checked").length) { alert("yes, it's checked"); } else { alert("no, it isn't"); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><table> <tbody> <tr> <td style="text-align: center; width: 20px; " class=""> <input type="checkbox" class="exempt" name="exempt"> </td> <td style="text-align: center; width: 20px; " class=""> <input type="checkbox" class="spammy" name="spammy"> </td> </tr> <tr> <td style="text-align: center; width: 20px; " class=""> <input type="checkbox" class="exempt" name="exempt"> </td> <td style="text-align: center; width: 20px; " class=""> <input type="checkbox" class="spammy" name="spammy" checked> </td> </tr> </tbody> </table> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script></code></pre> </div> </div> </p> <hr> <p>Separately: You have two elements with the same <code>id</code> value. That's invalid HTML, <code>id</code> values <strong>must</strong> be unique in the document.</p> |
34,125,439 | 0 | OSX sound output split across two USB devices <p>If two headsets are both connected to USB ports in OS X, the Preferences => Sound => Output pane only allows the user to select one of them at a time.</p> <p>I thought at first that there might be a way to "split" the output so that both USB devices receive it, as one can do with minijack-headsets connected to the audio output jack using a splitter. But I find that using a USB hub does not change how the operating system treats the two devices as distinct.</p> <p>However, is there a way to direct the same output to two or more devices simultaneously?</p> |
25,687,389 | 0 | _gaq.push won't send data <p>somehow my <code>_gaq.push</code> function is not working. If I set <code>debug = true</code> I can see the logs, and I know it gets to the else (when I have <code>debug=false</code>) because I tried adding a log in it. Here's my code</p> <pre><code>var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXX-X']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); var debug = false; function send_data(text, url) { if (debug) { console.log("_gaq.push(['_trackEvent', 'Site-change', " + text + ", " + url + "]);"); } else { _gaq.push(['_trackEvent', 'Site-change', text, url]); } } $('.navigation .child a').unbind('click').on('click', function(e) { var url = $(this).attr('href'); var text = $(this).text(); send_data(text, url); }); </code></pre> <p>Any idea?</p> |
17,963,361 | 0 | Hide the text on a button in android? <p>Please tell me how to hide the text on a button in android.</p> <p>When I try this code, the button is hidden but I just want to hide the text on the button.</p> <pre><code>Button b= (Button)findViewById(R.id.follow); b.setVisibility(View.GONE); </code></pre> <p>Please tell me how to solve this.</p> <p>Thank you.</p> |
22,863,487 | 0 | <p>The request which leads to this method being called need to pass through the Spring Security filter chain, otherwise there will be no security context available when the permissions are checked.</p> <p>Without seeing the rest of the stacktrace, I can't say 100%, but it looks like that's what's happening here, given the exception you are seeing (you should find similar issues if you search for the error message).</p> <p>So you need to make sure all the requests you want secured are handled by the security filter chain, and also that your filter chain is properly configured (which it should be automatically if you're using the namespace).</p> |
15,129,833 | 0 | Suppress Page header when there is no data in Details sections <p>I am using a datatable to load the data for the crystal report. Based on the data filtered by the user in the DataGridview and clicking on Print will display the filtered data in Report.</p> <p>All is fine.I have done this.When there is no data in the Details section I am suppressing it using the below formula in the suppress.</p> <pre><code>Shared NumberVar PageofLastField; If OnLastRecord then PageofLastField = PageNumber; </code></pre> <p>In the header section when there is no data in Details section supress page header.Below is the formula used.</p> <p>(Reference <a href="http://stackoverflow.com/questions/3294027/crystal-reports-suppress-a-page-header-if-the-page-has-0-records">Crystal Reports - Suppress a Page Header if the page has 0 records</a>)</p> <pre><code>Shared NumberVar PageofLastField; PageofLastField := PageofLastField; if pageofLastfield <> 0 and PageNumber > PageofLastField THEN TRUE ELSE FALSE </code></pre> <p>Below is the image of the crystal report.<img src="https://i.stack.imgur.com/TUfk4.png" alt="enter image description here"></p> <p>When I click PRINT button in the front end. When there is no data in Details section the Page header is displayed.</p> <p>Below image is the Second page of the report where there are no records and summary is displayed.</p> <p><img src="https://i.stack.imgur.com/EriJW.png" alt="enter image description here"></p> <p>If in the header section if I use the below formula </p> <pre><code>OnLastRecord AND Count({PaymentReportTable.InvID}) <> 1 </code></pre> <p>In the Second Page even if the records are displayed Pageheader is not displayed.I understand it becos the formula says it all.</p> <p><img src="https://i.stack.imgur.com/Vs4rV.png" alt="enter image description here"></p> <p>I have created around 12 Crystal reports and I am facing the same problem in all of them.</p> <p>Please advice.</p> |
29,988,115 | 0 | <p>You are not using <code>postdata</code> while sending request:</p> <pre><code>var postdata = "{ \"version\": \"1.0.1\", \"observations\": [ { \"sensor\": \"TISensorTag_temp_01\", \"record\": [ { \"starttime\": \"" + formatDate(new Date()) + "\", \"output\": [ { \"name\": \"ObjTemp\", \"value\": \"" + objtemp + "\" }, { \"name\": \"AmbTemp\", \"value\": \"" + ambtemp + "\" } ] } ] } ] }"; options.data = postdata; //added data to post request request.post(options, callback); </code></pre> <hr> <p>About <strong>Callback</strong>, you have initialized callback and in your case you don't have to pass callback as function parameter. Try use following:</p> <pre><code>async.series([ /*some functions*/ function() { setTimeout(callback, 2000); loop(); } ]) </code></pre> |
40,593,383 | 0 | <p>I am getting correct number with the following config:- </p> <pre><code> <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/> <flow name="Flow1" > <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/> <json:json-to-object-transformer doc:name="JSON to Object" returnClass="java.util.HashMap"/> <logger message="Order size #[message.payload.orders.order.size()] " level="INFO" doc:name="Logger"/> <json:object-to-json-transformer doc:name="Object to JSON"/> </flow> </code></pre> <p>and yes, your JSON is incorrect.. It should be :- </p> <pre><code>{ "orders" : { "order" :[ { "id" : "4358153416", "fulfillment" : { "tracking_number" : "915", "line-items" : { "id" : "8367362760" } } }] } } </code></pre> <p>You have missed <strong>[</strong> after order</p> |
27,828,258 | 0 | <p>You shouldn't be mocking at that level. Basically the idea is that you have interfaces that acts as a facade on database and ORM operations.</p> <pre><code>interface IFetchUsers { UserList GetAll(); User GetById(int id); } interface ICalculateDebt { float GetDebt(int accountId); } interface IPersistOrder { void Save(Order order); } </code></pre> <p>(forgive syntax errors, it's been a long time since I've done Java.)</p> <p>These are injected via the constructor into your other classes and become trivial to <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="nofollow">mock, or even stub</a>.</p> <p>Then, for actual db code you just implement these interfaces. You can even put all implementations in a single class.</p> <p>And that's it. No need to get fancy, but if you do want to get into fancier versions of this look into the repository design pattern (though I would argue that its not really necessary if using a good ORM).</p> |
6,063,744 | 0 | Ajax client for a CXF service <p>I'm new to CXF, and I was trying to implement a CFX client in Ajax. I had already implemented a client in Java but now I need to implement a client-side application to access CXF. I'm not even sure that it's possible to do that (Accessing CXF directly from client-side). If it's possible then kindly direct me to some ajax code. If not, then please help me with your ideas for a web-based CFX client. Thanks</p> |
30,225,516 | 0 | <p>This functionality is not implemented in Rails 3. Look at specification of this method <a href="http://apidock.com/rails/v3.2.13/ActionView/Helpers/UrlHelper/button_to" rel="nofollow">here</a>. It was implemented in Rails 4.</p> |
761,352 | 0 | Django QuerySet order <p>I am new to both django and python but I am beginning to get a grasp on things. I think.</p> <p>I have this problem and I can not seem to find an answer to it. (Though I assume it is really simple and the limiting factors are my google skills and lack of python/django knowledge)</p> <p>The scenario:</p> <p>a user can opt in to recieve temporary job openings at any number of stores he or she chooses.</p> <p>I would like to present a list of upcoming job openings (StoreEvents) sorted by the DateField only.</p> <pre><code>Example: Store A - 2009-04-20 Store B - 2009-04-22 Store A - 2009-04-23 </code></pre> <p>Atm I am stuck with presenting the data first sorted by store then by date since I am obviously accessing the StoreEvents through the Store model.</p> <pre><code>Example: Store A - 2009-04-20 Store A - 2009-04-23 Store B - 2009-04-22 </code></pre> <p>So my question is: Is it possible to create a QuerySet that looks like the first example and how do I do it?</p> <p>Examples of related models included:</p> <pre><code>class Store(models.Model): class StoreEvent(models.Model): info = models.TextField() date = models.DateField() store = models.ForeignKey(Store, related_name='events') class UserStore(models.Model): user = models.ForeignKey(User, related_name='stores') store = models.ForeignKey(Store, related_name='available_staff') </code></pre> <p>Edit:</p> <p>The following SQL does the trick but I still can't figure out how to do it in django:</p> <pre><code>SELECT * FROM store_storeevent WHERE store_id IN ( SELECT store_id FROM profile_userstore WHERE user_id =1 ) ORDER BY date </code></pre> |
17,492,192 | 0 | <p>With validation efficiency is not usually the concern. There are two types of validation that you should be concerned with:</p> <ol> <li>Input validation, e.g. will what the user is sending to the server malicious and intended to break/break into my application</li> <li>Business validation, which should happen in your business logic, and should be about maintaining valid, consistent values.</li> </ol> <p>Skipping over either of these is a very very good way to end up with either a hacked or badly broken application.</p> <p>If you're using ASP.net there are a plethora of libraries (mostly from Microsoft) to do the former, Anti-XSS lib etc.</p> <p>The latter would be most efficiently preformed in your shared business logic in the entities themselves. E.G your user entity should not allow an age of -1.</p> |
11,149,365 | 0 | trouble using lambda expressions and auto keyword in c++ <p>I'm trying to learn how to use lambda expressions in C++.</p> <p>I tried this simple bit of code but I get compile errors:</p> <pre><code>int main() { vector<int> vec; for(int i = 1; i<10; i++) { vec.push_back(i); } for_each(vec.begin(),vec.end(),[](int n){cout << n << " ";}); cout << endl; } </code></pre> <p>Errors:</p> <pre><code> forEachTests.cpp:20:61: error: no matching function for call to'for_each(std::vector<int>::iterator, std::vector<int>::iterator, main()::<lambda(int)>)' forEachTests.cpp:20:61: note: candidate is: c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_algo.h:4373:5: note:template<class _IIter, class _Funct> _Funct std::for_each(_IIter, _IIter, _Funct) </code></pre> <p>I also tried making the lambda expression an auto variable but I got a different set of errors.</p> <p>Here is the code:</p> <pre><code>int main() { vector<int> vec; for(int i = 1; i<10; i++) { vec.push_back(i); } auto print = [](int n){cout << n << " ";}; for_each(vec.begin(),vec.end(),print); cout << endl; } </code></pre> <p>This gave me the following errors:</p> <pre><code> forEachTests.cpp: In function 'int main()': forEachTests.cpp:20:7: error: 'print' does not name a type forEachTests.cpp:22:33: error: 'print' was not declared in this scope </code></pre> <p>I'm assuming these are problems with my compiler but I am not quite sure. I just installed MinGW and it appears to be using <code>gcc</code> 4.6.2.</p> |
36,843,106 | 0 | <p>You can use <code>position: absolute</code> and <code>transform: translate()</code></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>nav { position: relative; background: #2196F3; height: 50px; } .mdl-layout-title { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><nav> <span class="mdl-layout-title navbar">Title</span> </nav></code></pre> </div> </div> </p> |
36,206,566 | 0 | <p>The answer I found is that Haml doesn't play well with javascript. If you are going to have a js file it should be an Erb file. So rather that your_file.js.haml it should be your_file.js.erb.</p> |
28,104,867 | 0 | <p>I use a ClientRowTemplate to achieve something similar to the above.</p> <p>Look at this documentation: <a href="http://demos.telerik.com/aspnet-mvc/grid/rowtemplate" rel="nofollow noreferrer">http://demos.telerik.com/aspnet-mvc/grid/rowtemplate</a></p> <p>Basically I define my Row template in a partial view then I render the partial like this:</p> <pre><code>@(Html.Kendo().Grid(Model).Name("usersManageGrid") .Columns(columns => { columns.Bound(c => c.LoginId).Visible(false); columns.Bound(c => c.FullName).Title("Name").Width(120); columns.Bound(c => c.Email).Title("Username"); }).ClientRowTemplate(Html.Partial("_TestPartial").ToHtmlString())) </code></pre> <p>You can still specify and bind to other columns like the documentation shows. You can also pass in your sub view model if you wish as normal;</p> <pre><code>.ClientRowTemplate(Html.Partial("_TestPartial",x.SubViewModel).ToHtmlString()) </code></pre> <p>The partial view which contains the row template looks like this:</p> <pre><code><tr data-uid='#: LoginId #'> <td> <span class='description'><b>Name</b> : #: FullName# </span> </td> <td> @Html.Partial("_Test2Partial") </td> </tr> </code></pre> <p>Then you will see I render another partial view for the second column which simply has this in it:</p> <pre><code><span style="color:purple;"><b>Email</b> : #: Email# </span> </code></pre> <p>The end result looks like this:</p> <p><img src="https://i.stack.imgur.com/WoX8b.png" alt="enter image description here"></p> |
3,240,026 | 0 | PrincipalPermission vs. web.config for page access controls <p>I currently have my access permissions in <code>web.config</code>:</p> <pre><code> <location path="Account"> <system.web> <authorization> <allow users="?"/> </authorization> </system.web> </location> ... </code></pre> <p>I don't like this for two reasons:</p> <ol> <li><code>web.config</code> becomes a mess as my website builds up</li> <li>I'm not sure it's good security to keep the web page access rule so separated from the page itself. After all, I edit aspx/c# files most of the day and not web.config, so things tend to slip.</li> <li>This is a very weird one... I just added ASP.NET4 routing, which changes the URLs. So, all of a sudden my web.config permissions are no longer valid! Similar to point #2 above.</li> </ol> <p>I was thinking it would be better to just use PrincipalPermission as security attributes for the classes/c# files involved in each aspx. My question:</p> <ul> <li>Is this done by anyone, or is it a bad ideas?</li> <li>More importantly... My PrincipalPermission attribute generates an exception (good) but does not redirect users back to the logon page (bad). Can this be fixed?</li> </ul> |
34,609,362 | 0 | <p>As mentioned in the comments, the problem is your response redirects to another url, your <code>HttpUrlConnection</code> must handle redirects. See <a href="http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/" rel="nofollow">this</a> on how to do it. </p> |
26,487,619 | 0 | <p>You can skip it with <code>case ... when ... else</code> like you figured out by yourself:</p> <pre><code>... ||case when A.NEXTQUESTIONID is not null then 'NextQuestionID = '||A.NEXTQUESTIONID||',' else '' end || ... </code></pre> <p>You can also use the <code>nvl2</code> function for a shorter solution:</p> <pre><code>... || nvl2(A.NEXTQUESTIONID, 'NextQuestionID = '||A.NEXTQUESTIONID||',', '') || ... </code></pre> |
30,643,331 | 0 | How can I wait for an application launched by another application launched by my application Qt/C++ <p>I'm creating a Windows Add/Remove Programs application in Qt 5.4 and I'm becaming crazy to solve a little "puzzle":</p> <p>My application (APP_0) runs another application (APP_1) and waits for this APP_1 until it terminates. </p> <p>APP_1 is an uninstaller (i.e. uninstall.exe) and I've not the source code of the APP_1, just of my Qt APP_0.</p> <p>APP_1, instead of doing the uninstall job, it simply copies itself somewhere in the filesystem (I saw as Au_.exe but other apps could use different names and locations), runs this copy of itself (APP_2) and terminates.</p> <p>The APP_2 has a GUI and the job I'm waiting for (uninstall) is demanded to the final user of the running APP_2.</p> <p>In this situation my application (APP_0) stops waiting for APP_1 pratically immediately (because it launches APP_1 and waits for APP_1). But to work properly, obviously, I need to know instead when APP_2 is terminated...</p> <p>So the question is: is there a way (using some techniques (hooking?)) to know if and when APP_2 terminates?</p> <p>Note: Consider that the standard Windows Add/Remove Programs utility does the job successfully (it seems it waits for APP_2). You can test this, for example, installing Adobe Digital Edition. Its uninstaller (uninstall.exe) copies itself into a new folder in the User_Local_Temp folder as Au_.exe, runs it and terminates. But the OS utility successfully waits for Au_.exe and only after it terminates refreshes the list of installed programs.</p> <p>If this kind of technique (uninstall.exe copies itself somewhere ALWAYS with THE SAME name (Au_.exe) ) the problem could be resolved, obviously, very simply. But I don't think that the name of the copied uninstaller is always the same and also I don't like to assume things I'm not sure are real.</p> <p>Many thanks in advance</p> |
21,487,685 | 0 | How can I read multiple cookies with Perl's CGI.pm? <p>I am using CGI.pm to write out cookies. Now during the course of the user using my site, other cookies are added to the "test.com" cookie set, (as shown in the broswer history)</p> <p>But now I want to log the user out, and "clean" the PC. Since I don't know what scripts the user has used, I can't foresee what cookies would be on the PC.</p> <p>In short, it there a way to read all the cookies for "test.com" back into a script so I can then print them out again with a 1s duration, (effectively 'deleting' them) ** I know you can read the cookie back in with $xyz=cookie('$name') ... but how can I create the array holding the $name variable so I can loop through it? The script will also run on "test.com", so the cross site policy is not an issue</p> <p>+++++ <a href="http://stackoverflow.com/users/2766176/brian-d-foy">brian d foy</a> added a partial answer below. So this how I envisage the code might be strung together.</p> <pre><code>use CGI::Cookie; %cookies = CGI::Cookie->fetch; for (keys %cookies) { $del_cookie.="cookie(-NAME=>'$cookies[$_]',-PATH=>'/',-EXPIRES=>'+1s');"; } print header(-cookie=>[$del_cookie]); </code></pre> <p>I wondered how the script would recognise the domain. Appears the script is intelligent enough to only load the cookies for the domain for which the script is being executed on. (Now I've just got to find out why Firefox doesn't delete expired cookies!! Just found some listed that expired 29th - 31st Jan within my test domain, and at first wondered why they didn't appear in my cookie list!)</p> |
36,362,270 | 0 | <p>You don't need an SqlDataAdapter and all the infrastructure required to work with if you just have a single value returned by your Stored Procedure. Just use ExecuteScalar</p> <pre><code>int count = 0; using (var con = new SqlConnection(connectionString)) using (var cmd = new SqlCommand("RunAStoredProc", con)) { cmd.CommandType = CommandType.StoredProcedure; count = (int)cmd.ExecuteScalar(); } Console.WriteLine(count); Console.ReadKey(); </code></pre> <p>However if your really want to use an adapter and a dataset then you can find the result of your query reading the value from the first row and first column from the returned table</p> <pre><code>int count = Convert.ToInt32(table1.Rows[0][0]); </code></pre> <p>or even (without declaring the table1 variable)</p> <pre><code>int count = Convert.ToInt32(ds.Tables[0].Rows[0][0]); </code></pre> <p>To discover the difference between the result of the first select statement and the count of rows returned in the second select statement you could write</p> <pre><code>int allStudents = Convert.ToInt32(ds.Tables[0].Rows[0][0]); int enrolledStudents = ds.Tables[1].Rows.Count; int notEnrolledStudents = allStudents - enrolledStudents; </code></pre> |
39,171,971 | 0 | <p>Try to delete or rename .suo file (including extension). This file is at the same location where your solution file is. It worked for me.</p> |
37,601,024 | 0 | ActiveResource with nested relation fails with routing error <p>I am newbie to the rails world and in my project we have following model on server side </p> <pre><code> class Server < ActiveRecord::Base has_many :disks, :dependent => :destroy accepts_nested_attributes_for :disks, :reject_if => lambda { |a| a[:size].blank? }, :allow_destroy => true end class ServersController < ApplicationController def new @server = Server.new 4.times { @server.disks.build } respond_to do |format| format.xml { render :xml => @server.to_xml(:include => :disks) } format.json { render :json => @server.to_json(:include => :disks) } end end end </code></pre> <p>and </p> <pre><code>class Disk < ActiveRecord::Base belongs_to :server validates :size, presence: true end </code></pre> <p>On Client Side we have </p> <pre><code>class Server < ActiveResource::Base self.site = URLS_CONFIG['server_url'] self.format = :json self.include_root_in_json = true end </code></pre> <p>and </p> <pre><code>class Disk < ActiveResource::Base self.site = URLS_CONFIG['server_url'] self.prefix = "/servers/:server_id/" self.format = :json end </code></pre> <p>When I try </p> <pre><code>disk1 = @server.disks.build </code></pre> <p>On client side it gave error </p> <pre><code>ActiveResource::ResourceNotFound: Failed. Response code = 404. Response message = Not Found. from /usr/local/bundle/gems/activeresource-4.0.0/lib/active_resource/connection.rb:144:in `handle_response' from /usr/local/bundle/gems/activeresource-4.0.0/lib/active_resource/connection.rb:123:in `request' </code></pre> <p>When I checked on server side the error was </p> <pre><code>ActionController::RoutingError (No route matches [GET] "/servers/disks/new.json"): 11:21:06 web.1 | actionpack (4.2.2) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call' 11:21:06 web.1 | web-console (2.1.3) lib/web_console/middleware.rb:29:in `call' 11:21:06 web.1 | actionpack (4.2.2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' 11:21:06 web.1 | railties (4.2.2) lib/rails/rack/logger.rb:38:in `call_app' 11:21:06 web.1 | railties (4.2.2) lib/rails/rack/logger.rb:22:in `call </code></pre> <p>Can anyone tell me what went wrong here ? I wanted to show all disks for the server on the front end and allow user to edit and update it.</p> |
598,110 | 0 | <p>Until there's a reason given why it can't work, just use the facilities provided to you by the platform (the DLL and so forth).</p> |
15,361,648 | 0 | <p>There are likely to be several "problems", or ways to make it faster. I wouldn't call them "bottlenecks" because often they are not localized. Typically they are perfectly good code - it was just never supposed that they would be on the "critical path".</p> <p>Suppose the problems, when fixed, would save these percentages:</p> <p><img src="https://i.stack.imgur.com/EFeVX.jpg" alt="enter image description here"></p> <p>Just finding one of them would give you a certain amount of speedup. Like if you just find A, that would give you a speedup of 1/(1-0.3) = 1.43 or 43%. If you did that, you could, like most people, be happy and stop. However, if you continued and also found B, your total speedup would be 1/(1-0.51) = 2.04 or 104%. That's a lot more than 43%, even though B was smaller than A. Fixing C brings you up to 2.92 times faster, and D brings you to 4.2 times faster.</p> <p>What? Fixing smaller problems has higher payoff? They can, because speedup factors compound. Fixing A and B in that order gives you 1.43 * 1.43 = 2.04. If you happen to fix them in the opposite order you get 1.27 * 1.61 = 2.04</p> <p>Each time you fix something, the other issues become larger, percentage-wise and easier to find, and the speedups accumulate like a high-yield investment. By the time you fix A, B, C, D, and E, the one left is F and it isn't 5%, it's 30%. Fix all of them, and now you are 8.5 times faster! However, if you miss one, like D, because your profiling tool fails to expose it, you are only 4.5 times faster.</p> <p><em>That's the price you pay for not finding a problem.</em></p> <p>That's why I rely on <a href="http://stackoverflow.com/a/378024/23771"><em>a manual technique</em></a>, because, relative to profilers, it finds all problems they find, and it finds ones they don't. Profilers are often concerned with peripheral issues, like accuracy of measurement, which doesn't help to find problems. If you're wondering why, <a href="http://scicomp.stackexchange.com/a/2719/1262"><em>here's the math</em></a>.</p> |
3,140,611 | 0 | <p>Assuming it's a business site:</p> <p>What's your target market? How long do you expect until you release a working version of your website? If current trends continue, what will be IE6's market share by then? How much profit/value will those users bring? How much will it cost to support those additional users? Unless the costs are far below the profit, then don't bother. Otherwise, it might be a good idea.</p> <p>If it's not a for-profit site(hobby, for instance), then you probably shouldn't bother, unless there's a really significant IE6 market share in your target market.</p> <p>By the way, remember to use graceful degradation when possible and use feature detection instead of browser detection. Finally, avoid blocking IE6 users and instead just display a warning saying the website is untested in their browser and suggesting an update(this last piece of advice only applies if you don't plan to support IE6)</p> |
16,184,902 | 0 | <p>Once a program goes out of memory it can be hard for it to recover. You need to think carefully about how to try and clean up when that happens. For example, in your saveImageToExternalStorage, it doesn't clean up the fOut if an exception occurs inside your try/catch. So you should do things like put </p> <pre><code>OutputStream fOut = null; </code></pre> <p>outside the try/catch, and then close it in a finally block of the try/catch. And pay attention to the possibility of further exceptions in the catch of finally blocks.</p> |
28,229,830 | 0 | <p>You can implement a wrapper for fb.App and override Session method to return IFbSession instead of Facebook.Session.</p> <pre><code>package main import fb "github.com/huandu/facebook" type IFbApp interface { ExchangeToken(string) (string, int, error) Session(string) IFbSession } type MockFbApp struct { IFbApp } func (myFbApp *MockFbApp) ExchangeToken(token string) (string, int, error) { return "exchangetoken", 1, nil } func (myFbApp *MockFbApp) Session(token string) IFbSession { return &MyFbSession{} } type IFbSession interface { User() (string, error) Get(string, fb.Params) (fb.Result, error) } type MyFbSession struct { IFbSession } func (myFbSession *MyFbSession) User() (string, error) { return "userid", nil } func (myFbSession *MyFbSession) Get(path string, params fb.Params) (fb.Result, error) { return fb.Result{}, nil } type RealApp struct { *fb.App } func (myFbApp *RealApp) Session(token string) IFbSession { return myFbApp.App.Session(token) } func SomeMethod() { Facebook(&MockFbApp{}) Facebook(&RealApp{fb.New("appId", "appSecret")}) } func Facebook(fbI IFbApp) { fbI.ExchangeToken("sometokenhere") fbI.Session("session") } func main() { SomeMethod() } </code></pre> |
15,760,778 | 0 | <p>here is wat u want <a href="https://github.com/studhadoop/xmlparsing-hadoop/blob/master/XmlParser11.java" rel="nofollow">https://github.com/studhadoop/xmlparsing-hadoop/blob/master/XmlParser11.java</a></p> <pre><code>line 170 :if (currentElement.equalsIgnoreCase("name")) line 173 :else if (currentElement.equalsIgnoreCase("value")) </code></pre> <p>name and value are the tags in my xml file . In ur case if you need to process the tags inside FACULTY,u can use Name instead of name and Age instead of value.</p> <pre><code>conf.set("xmlinput.start", "<Faculty>"); conf.set("xmlinput.end", "</Faculty>"); </code></pre> |
1,762,373 | 0 | <p>The preferred way to interact with a db when using an ORM is not to use queries but to use objects that correspond to the tables you are manipulating, typically in conjunction with the session object. SELECT queries become get() or find() calls in some ORMs, query() calls in others. INSERT becomes creating a new object of the type you want (and maybe explicitly adding it, eg session.add() in sqlalchemy). UPDATE becomes editing such an object, and DELETE becomes deleting an object (eg. session.delete() ). The ORM is meant to handle the hard work of translating these operations into SQL for you.</p> <p>Have you read <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html" rel="nofollow noreferrer">the tutorial</a>?</p> |
24,619,003 | 0 | <blockquote> <p>I don't want to create B class object </p> </blockquote> <p>Add a constructor or factory method which doesn't require a B.</p> <pre><code>public A(B b){ this(b.getList()); } /* package local */ A(List<String> list){ this.list = list; } </code></pre> <p>By making the constructor package local it can be accessed by unit tests in the same package.</p> <blockquote> <p>How to test someMethod without calling constructor of A?</p> </blockquote> <p>You can use </p> <pre><code>A a = theUnsafe.allocateInstance(A.class); </code></pre> <p>but this is not recommended unless you have no other option e.g. deserialization.</p> |
13,163,450 | 0 | Stored Procedures using LINQ with VB.Net <p>Newby here and I cant understand why the data isnt staying in the table.</p> <p>The Stored Procedure:</p> <pre><code>ALTER PROCEDURE dbo.AccountAdd @AccountName nvarchar(50) ,@Address1 nvarchar(50) ,@Address2 nvarchar(50) ,@Address3 nvarchar(50) ,@Town nvarchar(50) ,@County nvarchar(50) ,@Postcode nvarchar(10) ,@Phone1 nvarchar(50) ,@Phone2 nvarchar(50) ,@Phone3 nvarchar(50) ,@Email1 nvarchar(50) ,@Email2 nvarchar(50) ,@ContactName nvarchar(50) ,@Position nvarchar(50) ,@AccountType nvarchar(50) AS INSERT INTO [dbo].[Accounts] ([AccountName] ,[Address1] ,[Address2] ,[Address3] ,[Town] ,[County] ,[Postcode] ,[Phone1] ,[Phone2] ,[Phone3] ,[Email1] ,[Email2] ,[ContactName] ,[Position] ,[AccountType]) VALUES (@AccountName ,@Address1 ,@Address2 ,@Address3 ,@Town ,@County ,@Postcode ,@Phone1 ,@Phone2 ,@Phone3 ,@Email1 ,@Email2 ,@ContactName ,@Position ,@AccountType) RETURN @@IDENTITY </code></pre> <p>The VB Code:</p> <pre><code>Dim db As New DBClassesDataContext Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click db.Connection.Open() Dim q = db.AccountAdd("Mark Cooney", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv") db.Connection.Close() Label1.Text = q End Sub </code></pre> <p>So when I click button1, q equals a new id but the data isnt there!!</p> <p>What am I missing please? Sorry I'm trying to understand LINQ</p> |
15,905,056 | 0 | <p>If your static lib is another project in the same solution as the project that links to the lib, then you need to set a dependency between the two projects so that the build process will build the lib first and the other project second.</p> <p>To do this, right-click on the Solution abd choose "Project dependencies" from the pop-up menu.</p> |
39,259,681 | 0 | <p>It works for me:</p> <pre><code> {ok, F} = file:read_file("warning.gif"), httpc:request(post,{Url, [],"multipart/form-data", F},[],[]). </code></pre> <p>I recieved on cowboy web server with function <code>cowboy_req:body(Req)</code>:</p> <pre><code>{ok,<<71,73,70,56,57,97,11,0,11,0,230,64,0............>>, {http_req,#Port<0.65562>,ranch_tcp,keepalive,<0.8736.0>,<<"POST">>, 'HTTP/1.1', {{127,0,0,1},58154}, <<"localhost">>,undefined,8000,<<"/test1">>, [<<"test1">>], <<>>,undefined,[], [{<<"content-type">>,<<"multipart/form-data">>}, {<<"content-length">>,<<"516">>}, {<<"te">>,<<>>}, {<<"host">>,<<"localhost:8000">>}, {<<"connection">>,<<"keep-alive">>}], [{<<"content-length">>,516}, {<<"expect">>,undefined}, {<<"content-length">>,516}, {<<"connection">>,[<<"keep-alive">>]}],undefined,[],done,undefined,<<>>,true,waiting,[],<<>>, undefined}} </code></pre> |
40,267,118 | 0 | <p>You can create a class <code>no-gutter</code> for your <code>row</code> and remove the margin/padding that's added by bootstrap, like suggested in <a href="http://stackoverflow.com/questions/16489307/how-to-remove-gutter-space-for-a-specific-div-only-bootstrap/21282059#21282059">this post</a>:</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-css lang-css prettyprint-override"><code>.row.no-gutter { margin-left: 0; margin-right: 0; } .row.no-gutter [class*='col-']:not(:first-child), .row.no-gutter [class*='col-']:not(:last-child) { padding-right: 0; padding-left: 0; } .row > div { background: lightgrey; border: 1px solid; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/> <div class="row no-gutter"> <div class="col-md-2"> 1 </div> <div class="col-md-10"> 2 </div> </div></code></pre> </div> </div> </p> <p>I've set a gray background and a border for demonstration purposes. Watch the result in fullscreen to see, that there is no space anymore between the columns. More information about the predefined margin and padding in Bootstrap can be <a href="http://getbootstrap.com/css/" rel="nofollow">found here</a>.</p> |
20,835,797 | 0 | <p>using inline-jquery</p> <pre><code>onkeyup="if($(this).val()==''){ $(this).css({'text-align':'right'})} else{ $(this).css({'text-align':'left'})}" </code></pre> <p><a href="http://jsfiddle.net/Cq5ep/" rel="nofollow">Demo</a></p> |
10,412,443 | 0 | <p>The Java final keyword is used in the Java programming language under different conditions and has different implications. For example:</p> <ol> <li>To declare a constant variable,</li> <li><p>To declare a constant method parameter.</p> <ol> <li><p>A variable declared as final must have an initialization prior to its usage. This variable cannot be assigned a new value such as (a = b). But if the variable is not of primitive type then its properties can be set using the set methods or any other public fields. This means that the object instance reference cannot be changed but the properties of the object instance can be changed as long as they themselves are not declared final.</p></li> <li><p>To prohibit the parameter being modified in the method where it is being used.</p></li> </ol></li> </ol> |
28,336,001 | 0 | <p>At each terminal node (leaf) you are printing <code>)</code>s for all parents; you should only do so for <em>consecutive right-side</em> parents.</p> <p>I suggest renaming <code>parents</code> to <code>depth</code> and adding a <code>right_depth</code> parameter.</p> <p><strong>Edit:</strong> after playing around with it a bit, I decided it was better to delegate it to the tree:</p> <pre><code>class Node: INDENT = " " __slots__ = ["lhs", "word_label", "left_child", "right_child"] def __init__(self, lhs, *args): self.lhs = lhs num_args = len(args) if num_args == 1: self.word_label = args[0] self.left_child = None self.right_child = None elif num_args == 2: self.word_label = None self.left_child = args[0] self.right_child = args[1] else: raise ValueError("should have one arg (word_label: str) or two args (left: Node and right: Node)") def is_terminal(self): return self.word_label is not None def tree_str(self, depth=0, indent=None): if indent is None: indent = self.INDENT if self.is_terminal(): return "\n{}({} '{}' )".format( indent * depth, self.lhs, self.word_label ) else: return "\n{}( {}{}{} )".format( indent * depth, self.lhs, self.left_child .tree_str(depth + 1, indent), self.right_child.tree_str(depth + 1, indent) ) def __str__(self): return self.tree_str() </code></pre> <p>then some syntactic helpers,</p> <pre><code>def make_leaf_type(name): def fn(x): return Node(name, x) fn.__name__ = name return fn for leaf_type in ("VB", "DT", "NNS", "IN", "NP_NNP", "TO", "NN", "PUNC"): locals()[leaf_type] = make_leaf_type(leaf_type) def make_node_type(name): def fn(l, r): return Node(name, l, r) fn.__name__ = name return fn for node_type in ("TOP", "S_VP", "NP", "PP"): locals()[node_type] = make_node_type(node_type) </code></pre> <p>so I can create the tree,</p> <pre><code>tree = \ TOP( S_VP( VB('List'), NP( NP( DT('the'), NNS('flights') ), PP( PP( IN('from'), NP_NNP('Baltimore') ), PP( TO('to'), NP( NP_NNP('Seattle'), NP( NP( DT('that'), NN('stop') ), PP( IN('in'), NP_NNP('Minneapolis') ) ) ) ) ) ) ), PUNC('.') ) </code></pre> <p>which then prints like</p> <pre><code>>>> print(tree) ( TOP ( S_VP (VB 'List' ) ( NP ( NP (DT 'the' ) (NNS 'flights' ) ) ( PP ( PP (IN 'from' ) (NP_NNP 'Baltimore' ) ) ( PP (TO 'to' ) ( NP (NP_NNP 'Seattle' ) ( NP ( NP (DT 'that' ) (NN 'stop' ) ) ( PP (IN 'in' ) (NP_NNP 'Minneapolis' ) ) ) ) ) ) ) ) (PUNC '.' ) ) </code></pre> <p>which I believe is <em>actually</em> what is desired.</p> |
28,113,856 | 0 | 'while' statement cannot complete without throwing an exception - Android <p>With this method I'm updating <code>TextView</code> every second. </p> <pre><code> private void UpdatingTime(final String endTime, final long diffInDays) { new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(ONE_SECOND); mHandler.post(new Runnable() { @Override public void run() { // Updating time every second long diffInHours = Methodes.diffInHours(endTime, diffInDays); long diffInMinutes = Methodes.diffInMinutes(endTime, diffInDays, diffInHours); long diffInSeconds = Methodes.diffInSeconds(endTime, diffInDays, diffInHours, diffInMinutes); tvTime2.setText(addZeroInFront(diffInHours) + ":" + addZeroInFront(diffInMinutes) + ":" + addZeroInFront(diffInSeconds)); } private String addZeroInFront(long diffInHours) { String s = "" + diffInHours; if (s.length() == 1) { String temp = s; s = "0" + temp; } return s; } }); } catch (Exception e) { e.printStackTrace(); } } } }).start(); } } </code></pre> <p>This method is working perfect. But I got this warning:</p> <blockquote> <p>'while' statement cannot complete without throwing an exception.</p> <p>Reports for, while, or do statements which can only exit by throwing an exception. While such statements may be correct, they are often a symptom of coding errors.</p> </blockquote> <p>I hate warnings and I want to fix it. How can i fix this warning, or there is a better solution for this infinite loop...?</p> |
13,205,504 | 0 | <p>An <code>IntentService</code> runs in the background on a <code>seperate Thread</code> so anything done in the service will not effect the UI. BUT once the service finishes doing what it is suppose to, the service terminates itself. </p> <p>A <code>service</code> also does stuff in the background BUT on the <code>UI thread</code> so if you have any time consuming things that need to be done it will hold up the UI. this also runs until you tell it to stop for the most part.</p> <p>If you are using alarms to trigger everything I would say the IntentService is fine. </p> |
26,539,171 | 0 | Difference between interface-abstract (not duplicate) <p>I want to know the difference between the two codes. I have a interface: lets say : </p> <pre><code>public interface iaminterface { void m1(); void m2(); void m3(); } </code></pre> <p>First Code : </p> <pre><code>public abstract class iamabstract implements iaminterface { public void m1(){} public abstract void m2(); // abstract method .So i need to override this in the subclasses. } public class car extends iamabstract { public void m2(){} public void m3(){} } public class train extends iamabstract { public void m2() {} public void m3() {} } </code></pre> <p>This code will compile successfully. But this code is same as writing :</p> <p>Second Code: </p> <pre><code> public abstract class iamabstract implements iaminterface { public void m1(){} } public class car extends iamabstract { public void m2(){} public void m3(){} } public class train extends iamabstract { public void m2() {} public void m3() {} } </code></pre> <p>I don't understand the difference in the two codes. Both codes will function in a similar way. One has a abstract method and another does not have a abstract method, so we need to implement the unimplemented methods of the interface. So , what's the use of writing the method m2() as abstract in the first code. ?</p> |
18,949,721 | 0 | <p>Use redirect_to with status 303</p> <pre><code>def destroy @task = Task.find(params[:id]) @task.destroy redirect_to :action => :index, status: 303 end </code></pre> <p>redirect_to documentation says:</p> <p><a href="http://api.rubyonrails.org/classes/ActionController/Redirecting.html">http://api.rubyonrails.org/classes/ActionController/Redirecting.html</a></p> <p>If you are using XHR requests other than GET or POST and redirecting after the request then some browsers will follow the redirect using the original request method. This may lead to undesirable behavior such as a double DELETE. To work around this you can return a 303 See Other status code which will be followed using a GET request.</p> |
29,035,815 | 1 | combining python lists in savetxt <p>I have 2 python lists that I want to save side by side using np.savetxt().</p> <p>I have tried:</p> <pre><code>np.savetxt('./filename.txt',np.hstack([list1,list2]),fmt=['%f','%f']) </code></pre> <p>but I get the error message</p> <pre><code>raise AttributeError('fmt has wrong shape. %s' % str(fmt)) AttributeError: fmt has wrong shape. ['%f', '%f'] </code></pre> <p>I don't know if it is relevant, but the lists are in decimal.Decimal format.</p> <p>What am I doing wrong please?</p> <hr> <p>edit: I originally said "vstack" but I meant "hstack".</p> |
5,779,073 | 0 | <pre><code>result = [] z = ActiveSupport::JSON.decode( '{ "0X1W6": "{\"type\":\"Hourly\",\"hr\":\"12\",\"min\":\"30\",\"every_hr\":\"5\"}", "Tk18f": "{\"type\":\"Daily\",\"hr\":\"12\",\"min\":\"30\",\"days_checked\":[1,4]}" }') z.each_value do|i| x = {} ActiveSupport::JSON.decode(i).each{|k,v| x[k.to_sym] = (v.class == String && v.to_i.to_s == v) ? v.to_i : v } result << x end </code></pre> |
21,197,777 | 0 | linux shell search for number that does not ocur between numbers <p>I want to search for a number in string that does not occur between numbers.</p> <p>For example: string="10003096,10007051,10003098,10007053,10000952,10002696,10003619,900004608"</p> <p>If i search for 10003096, then it exists. But if i search for 1000, then it means it does not exist. Even if i search for 10000952,10002696, then it means it does not exist.</p> <p>How can i write the shell script for this?</p> <p>Please help.</p> <p>I have tried various options with grep and sed but it does not help.</p> |
17,262,932 | 0 | <p>You need to invoke session_start at beginning of each file where session data is accessed.</p> |
8,978,409 | 0 | <p>The spacing is intentional and cannot be changed (without custom drawing the entire thing, which is <a href="http://christian-helle.blogspot.com/2009/10/listview-custom-drawing-in-netcf.html" rel="nofollow">not so easy in managed code</a>), as WinMo 6.5 and later supposedly moved toward more "finger friendly" UIs. </p> <p>I realize the link is for a ListView, but the TreeView in CE also supports custom drawing in the same way, and that link is the only custom drawn <em>anything</em> I've seen for the CF.</p> |
39,816,968 | 0 | <p>The line</p> <pre><code>while ((nextLine = br.readNext()) != null) { </code></pre> <p>takes advantage of the fact that an "assignment" is also an "expression" that has a value - the assigned value.</p> <p>So the line, reading from inside the parentheses out, does the following:</p> <ol> <li>Calls <code>readNext()</code> for the object <code>br</code>;</li> <li>Assigns the result of the call to <code>nextLine</code>;</li> <li>Tests the value assigned for <code>null</code>;</li> <li>If it <em>is</em> <code>null</code>, it jumps past the body of the <code>while</code> loop, to 7.;</li> <li>If it is <em>not</em> <code>null</code>, it executes the body of the <code>while</code> loop;</li> <li>It then goes back to 1. again.</li> <li>It continues the program.</li> </ol> |
13,347,920 | 0 | Google Analytics iOS SDK - Multiple accounts <p>I am trying to make my view controllers be tracked by two different accounts on my iPhone app. I am currently using the version 1.5.1 of the SDK, which doesn't support this functionality. On the documentation of the version 2, it says that it supports multiple trackers, but I couldn't figure out a way to make both track the same view. Does anyone know how can I do that?</p> <p>Thanks!</p> |
41,064,717 | 0 | Java thread pool executor implementation with job execution that don't exceed a defined duration <p>I want to find a way to have an thread pool executor implementation where if a thread job execution exceed a defined duration, the thread is killed (then the executor will create a new thread for a future job).</p> <p>Does any library have that ? or does java 8 have this kind of executor ?</p> <p>Thanks.</p> |
37,653,196 | 0 | Why isn't the divide() function working in Java BigInteger? <p>I'm attempting to divide the variable 'c' by 2(stored in 'd'). For some reason that doesn't happen. I'm passing 10 and 2 for input right now. </p> <pre><code>import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); BigInteger a = new BigInteger(sc.next()); BigInteger b = sc.nextBigInteger(); BigInteger d = new BigInteger("2"); System.out.println(d); BigInteger c = a.subtract(b); c.divide(d); System.out.println(c); a.subtract(c); System.out.println(a); System.out.println(c); } } </code></pre> <p>Any help would be appreciated. Thanks in advance!</p> |
23,863,338 | 0 | <p>This is a very interesting scenario. While in general, we can change any method which is returning void to return anything else without much impact, main method is a special case.</p> <p>In earlier programming languages, the return from main method was supposed to return exit values to the OS or calling environment.</p> <p>But in case of Java (where multi-threading concept case into picture), returning a value from main method would not be right, as the main method returns to JVM instead of OS. JVM then finishes other threads e.g. deamon threads (if any) and performs other exit tasks before exit to OS.</p> <p>Hence allowing main method to return, would have lead to a false expectation with the developers. hence it is not allowed.</p> |
429,859 | 0 | <p>If time isn't an issue implementing OAuth security may be useful. OAuth uses a public key, and also a secret. The mess is hashed (in most cases) and the server will use the public key + it's copy of the secret to do the same hashing and make sure its result matches the requests. </p> <p>The benefit is you wouldn't need to use HTTPS or POST. Get* REST api methods should be using the HTTP GET method (I'm not sure if being RESTful is your goal, just thought I would point that out). I agree with Mr. Pang, use <a href="http://www.business.com/employees" rel="nofollow noreferrer">http://www.business.com/employees</a>. The query string could contain the list of department ids.</p> <p>For your case the service call wouldn't have the 'accessKey' argument, rather it would become the public key (I imagine) and be used in either the headers, query string, or as a POST param.</p> <p>Some good info on OAuth: <a href="http://www.hueniverse.com/hueniverse/" rel="nofollow noreferrer">http://www.hueniverse.com/hueniverse/</a></p> |
22,708,037 | 0 | <p>If you want get all items in result table, you can get <code>ctx.CurrentGroup.ResultRows</code>.</p> |
26,292,279 | 0 | <p>Yes, you have a <code>return</code> on the previous line. The method is done.</p> <pre><code>return monthlyPayment; // <-- the method is finished. boolean isValid; // <-- no, you can't do this (the method finished on the // previous line). </code></pre> |
33,848,992 | 0 | <p>Store the questions and a counter to store which question has been asked in <code>$_SESSION['questions']</code>. Use the counter (also stored in the <code>$_SESSION</code>) to figure out what the next question is and increment it after each submit.</p> <p>To do this check after <code>session_start();</code> if <code>$_SESSION['questions']</code> is set. If not get your questions and store them into <code>$_SESSION['questions]</code> and set the counter to 0.</p> <p>Instead of the <code>foreach()</code> you access your questions by <code>$_SESSION['questions'][$_SESSION['counter']]</code> but do not forget to increase the counter each time.</p> <hr> <p>Sample code:</p> <p>The part to set set / get the questions and increase the counter: <pre><code>session_start(); if(!isset($_SESSION['questions'])) { $query = "SELECT * FROM question_table"; $statement = $db->prepare($query); $statement->execute(); $question = $statement->fetchall(); $statement->closeCursor(); $_SESSION['questions'] = $question; $_SESSION['counter'] = 0; } if (isset($_POST["submit"])){ // DO YOUR STUFF $_SESSION['counter']++; } ?> </code></pre> <p>The part the output the question:</p> <pre><code><?php $question = $_SESSION['questions'][$_SESSION['counter']]; if(empty($question)) { // FINISHED ALL QUESTIONS } else { ?> <form action="QuestionAndOption.php" method="POST"> Question <?php echo $_SESSION['counter'] . ": " . $question["Question"]; ?><br> A: <input type="radio" name="option" value="OptionA"> <?php echo $question["OptionA"]; ?><br> B: <input type="radio" name="option" value="OptionB"> <?php echo $question["OptionB"]; ?><br> C: <input type="radio" name="option" value="OptionC"> <?php echo $question["OptionC"]; ?><br> D: <input type="radio" name="option" value="OptionD"> <?php echo $question["OptionD"]; ?><br> <button name="submit" type="submit">Submit</button> </form> <?php } // if close ?> </code></pre> |
9,046,428 | 0 | <p>You can't do that. You need to setup a delegate protocol. See <a href="http://www.raywenderlich.com/5191/beginning-storyboards-in-ios-5-part-2" rel="nofollow">This tutorial</a> and search down for the words "new delegate" and it will explain how that is done. That is the design pattern you need to use. There are several steps involved so follow closely. It is worth learning. Delegate protocols are common in iPhone Apps.</p> <p>In a current project I created a delegate protocol to communicate between two controller: SelectNoteViewController (Select) and EditNoteViewController (Edit). The basic idea is that Select is used to select from a list of notes and Edit is used to edit those notes. Now, I need Edit to have access back into the data and methods kept by Select because I have buttons in edit to call up the previous or next note from the list which is managed by Select so I implement a delegate protocol. Select is a delegate for Edit. That means Select does things for Edit. Here is the essential code.</p> <p>SelectNoteViewController.h:</p> <pre><code>// this next statement is need to inform Select of the protocols defined in Edit #import "EditNoteViewController.h" // STEP 1 @interface SelectNoteViewController : UITableViewController <EditNoteViewControllerDelegate> { ... // STEP 2: this says Select implements the protocol I created ... // STEP 3: EditNoteViewController Delegate Methods - these are the methods in the protocol - (Notes *)selectPreviousNote; - (Notes *)selectNextNote; </code></pre> <p>SelectNoteViewController.m:</p> <pre><code>// STEP 4: the protocol methods are implemented - (Notes *)selectPreviousNote { if (isPreviousToSelectedNote) { NSIndexPath *indexPath, *previousIndexPath; indexPath = [self.tableView indexPathForSelectedRow]; previousIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]; // update the selected row self.selectedNote = [self.fetchedResultsController objectAtIndexPath:previousIndexPath]; [self.tableView selectRowAtIndexPath:previousIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle]; [self setPreviousNote]; [self setNextNote]; } return selectedNote; } - (Notes *)selectNextNote { if (isNextToSelectedNote) { NSIndexPath *indexPath, *nextIndexPath; indexPath = [self.tableView indexPathForSelectedRow]; nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:0]; // update the selected row self.selectedNote = [self.fetchedResultsController objectAtIndexPath:nextIndexPath]; [self.tableView selectRowAtIndexPath:nextIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle]; [self setPreviousNote]; [self setNextNote]; } return selectedNote; } ... ... if ([[segue identifier] isEqualToString:@"editNote"]) { // STEP 5: this is where Edit is told that its delegate is Select [[segue destinationViewController] setEditNoteViewControllerDelegate:self]; // STEP 5 </code></pre> <p>Select now has the structure to do be a delegate for Edit. Now Edit needs to define the protocol on its end that it is going to use to get to those methods in Select.</p> <p>EditNoteViewController.h</p> <pre><code>#import ... // put protocol after import statements // STEP 6 @protocol EditNoteViewControllerDelegate <NSObject> - (Notes *)selectPreviousNote; - (Notes *)selectNextNote; @end @interface ... // STEP7: Edit needs a property to tell it who the delegate is - it was set back in Select.m @property (weak) id <EditNoteViewControllerDelegate> editNoteViewControllerDelegate; </code></pre> <p>EditNoteViewController.m</p> <pre><code>// STEP 8: the property is synthesized @synthesize editNoteViewControllerDelegate; ... // STEP 9: now when any method needs to call selectPreviousNote or selectNext Note it does it like this: selectedNote = [self.editNoteViewControllerDelegate selectPreviousNote]; // or selectedNote = [self.editNoteViewControllerDelegate selectNextNote]; </code></pre> <p>That is it. Of course the protocol methods are like and other method and they can be passed parameters which what you need to do to pass data back which was your question in the first place. As a side note, see that I can pass data from Select to Edit without a protocol by creating properties in Edit and setting those properties in the prepareForSegue method of Select. Doing so gives me one shot to set some parameters when Edit is instantiated. My use of a the delegate protocol goes back to Select and has it pass another note (previous or next) to Edit. I hope that helps. You can see there are several steps to creating a delegate protocol. I numbered them 1-9. If the data is not making it back, I usually find I forgot one of the steps.</p> |
29,683,014 | 0 | <p>You can get rid of that kernel loop to calculate <code>D</code> with this <a href="http://in.mathworks.com/help/matlab/ref/bsxfun.html" rel="nofollow"><code>bsxfun</code></a> based <a href="http://in.mathworks.com/help/matlab/matlab_prog/vectorization.html" rel="nofollow"><code>vectorized</code></a> approach -</p> <pre><code>D = squeeze(sum(bsxfun(@min,A,permute(B,[3 2 1])),2)) </code></pre> <p>Or avoid <code>squeeze</code> with this modification -</p> <pre><code>D = sum(bsxfun(@min,permute(A,[1 3 2]),permute(B,[3 1 2])),3) </code></pre> <p>If the calculations of <code>D</code> involve <code>max</code> instead of <code>min</code>, just replace <code>@min</code> with <code>@max</code> there.</p> <hr> <p><strong>Explanation:</strong> The way <code>bsxfun</code> works is that it does <em>expansion</em> on singleton dimensions and performs the operation as listed with <code>@</code> inside its call. Now, this expansion is basically how one achieves vectorized solutions that replace for-loops. By <code>singleton dimensions</code> in arrays, we mean dimensions of <code>1</code> in them. </p> <p>In many cases, singleton dimensions aren't already present and for vectorization with <code>bsxfun</code>, we need to create <code>singleton dimensions</code>. One of the tools to do so is with <a href="http://in.mathworks.com/help/matlab/ref/permute.html" rel="nofollow"><code>permute</code></a>. That's basically all about the way vectorized approach stated earlier would work.</p> <p>Thus, your kernel code -</p> <pre><code>... case {'dist_histint','ih'} [m,d]=size(A); [n,d1]=size(B); if (d ~= d1) error('column length of A (%d) != column length of B (%d)\n',d,d1); end % With the MATLAB JIT compiler the trivial implementation turns out % to be the fastest, especially for large matrices. D = zeros(m,n); for i=1:m % m is number of samples of A if (0==mod(i,1000)) fprintf('.'); end for j=1:n % n is number of samples of B D(i,j) = sum(min([A(i,:);B(j,:)]));%./max(A(:,i),B(:,j))); end end </code></pre> <p>reduces to -</p> <pre><code>... case {'dist_histint','ih'} [m,d]=size(A); [n,d1]=size(B); if (d ~= d1) error('column length of A (%d) != column length of B (%d)\n',d,d1); end D = squeeze(sum(bsxfun(@min,A,permute(B,[3 2 1])),2)) %// OR D = sum(bsxfun(@min,permute(A,[1 3 2]),permute(B,[3 1 2])),3) </code></pre> <p>I am assuming the line: <code>if (0==mod(i,1000)) fprintf('.'); end</code> isn't important to the calculations as it does printing of some message. </p> |
11,524,076 | 0 | <p>Store the image names in an NSMutableArray and shuffle the array, e.g. via methods like <a href="http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray">this SO answer</a></p> <p>Then loop over the array. </p> |
3,072,842 | 0 | <p>In addition to JQuery, Google CDN also hosts JQueryUI and all the default Themeroller CSS UI themes (including images!). If you're planning to build a UI from JQuery this is pretty clutch.</p> <p><a href="http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/" rel="nofollow noreferrer">http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/</a></p> |
21,522,600 | 0 | <p><code>160000</code> is not a timestamp in any way that PHP (or other common systems) define a timestamp. What you have is merely a time of day expressed in "military time" stored as an integer. So first of all, any <code>gm</code> function is likely not what you want to use, since you are missing timezone information from this "timestamp" to begin with, hence conversion to GM time is ambiguous if not impossible.</p> <p>The best you may be able to do is:</p> <pre><code>$timestamp = DateTime::createFromFormat('His', sprintf('%06d', 160000))->format('U'); echo strftime('%H:%M', $timestamp); </code></pre> |
16,610,057 | 0 | Spring JPA 2.0 Repository / Factory not working <p>I'm trying to implement a custom java Spring JPA repository, as described in the <a href="http://static.springsource.org/spring-data/data-jpa/docs/current/reference/html/repositories.html#repositories.custom-implementations" rel="nofollow">Spring documentation</a>. It seems that my spring config insists on creating the repositories in the standard way, instead of using the given MyRepositoryFactoryBean, giving me </p> <pre><code>Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.myapp.repository.impl.DocumentRepositoryImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.myapp.repository.impl.DocumentRepositoryImpl.<init>() at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:83) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1006) ... 43 more Caused by: java.lang.NoSuchMethodException: com.myapp.repository.impl.DocumentRepositoryImpl.<init>() at java.lang.Class.getConstructor0(Class.java:2730) at java.lang.Class.getDeclaredConstructor(Class.java:2004) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78) </code></pre> <p>I'm using Spring 3.2.2-RELEASE and spring-data-jpa-1.3.2-RELEASE, which is the latest if I'm correct. Here's my spring config:<br> </p> <pre><code><?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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"> <import resource="spring-repository-config.xml"/> <import resource="spring-security-config.xml"/> <context:component-scan base-package="com.myapp.web.controller"/> <context:component-scan base-package="com.myapp.webservice.controller"/> </code></pre> <p>And here's the spring-repository-config.xml: </p> <pre><code><?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/data/jpa" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"> <repositories base-package="com.myapp.repository" factory-class="com.myapp.repository.impl.MyRepositoryFactoryBean"/> <!-- entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" --> </code></pre> <p></p> <p>If've added debug breakpoints in all the methods of the com.myapp.repository.impl.MyRepositoryFactoryBean class, but these were not called.</p> <p>The basic interface, just like in the example</p> <pre><code>package com.myapp.repository.impl; @NoRepositoryBean public interface MyRepository<T, ID extends Serializable> extends JpaRepository<T, ID> { </code></pre> <p>The base implementation: </p> <pre><code>package com.myapp.repository.impl; @NoRepositoryBean public class MyRepositoryImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, ID> implements MyRepository<T, ID> { private EntityManager entityManager; public MyRepositoryImpl(Class<T> domainClass, EntityManager entityManager) { super(domainClass, entityManager); // This is the recommended method for accessing inherited class dependencies. this.entityManager = entityManager; } public void sharedCustomMethod(ID id) { // implementation goes here } } </code></pre> <p>And the factory: </p> <pre><code>package com.myapp.repository.impl; import java.io.Serializable; import javax.persistence.EntityManager; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.RepositoryFactorySupport; public class MyRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> { protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { return new MyRepositoryFactory(entityManager); } private static class MyRepositoryFactory<T, I extends Serializable> extends JpaRepositoryFactory { private EntityManager entityManager; public MyRepositoryFactory(EntityManager entityManager) { super(entityManager); this.entityManager = entityManager; } protected Object getTargetRepository(RepositoryMetadata metadata) { return new MyRepositoryImpl<T, I>((Class<T>) metadata.getDomainType(), entityManager); } protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) { // The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory // to check for QueryDslJpaRepository's which is out of scope. return MyRepositoryImpl.class; } } } </code></pre> <p>My repositories interfaces are defines as: </p> <pre><code>package com.myapp.repository; public interface DocumentRepository { // extends MyRepository<Document, Long> public Document findByDocumentHash(String hashCode); public Document findById(long id); } </code></pre> <p>And the implementation is</p> <pre><code>package com.myapp.repository.impl; import java.io.Serializable; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; public class DocumentRepositoryImpl<Document, ID extends Serializable> extends MyRepositoryImpl<Document, Serializable> { private static final long serialVersionUID = 1L; public DocumentRepositoryImpl(Class<Document> domainClass, EntityManager entityManager) { super(domainClass, entityManager); } </code></pre> <p>And I use these repositories as autowired refernces in my controllers: </p> <pre><code>package com.myapp.web.controller; @Controller @RequestMapping(value = "/documents") public class DocumentController { @Autowired private DocumentRepository documentRepository; @RequestMapping(method = RequestMethod.GET) public ModelAndView list(HttpServletRequest request) { this.documentRepository. ... } </code></pre> <p>I've looked at various resources on the web like <a href="http://stackoverflow.com/questions/15140867/cant-autowire-repositories-created-by-jparepositoryfactorybean">this one</a>, but I can't tell the difference with my code. Any hints are more than welcome!</p> |
5,450,555 | 0 | <p>I assume that you meant to return the <code>list</code> local variable that you declare in the <code>returnLists</code> function. What you'll be getting back is actually the class variable, also called <code>list</code>. This is because the local <code>list</code> variable has gone out of context by the time the code reaches your return statement (the local <code>list</code> variable is within the context of the <code>try</code> block you have declared). If you want to return the value from the local <code>list</code> variable change the first couple of lines of <code>returnLists</code> to this:</p> <pre><code>public List returnLists(String fileN) { mp3Lister woww = null; String fName; String lName; mp3Lister qwewq; List list = new LinkedList(); try { </code></pre> <p>and then remove the declaration of the <code>list</code> variable inside the try block.</p> |
10,374,930 | 1 | Matplotlib: Annotating a 3D scatter plot <p>I'm trying to generate a 3D scatter plot using Matplotlib. I would like to annotate individual points like the 2D case here: <a href="http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot">Matplotlib: How to put individual tags for a scatter plot</a>.</p> <p>I've tried to use this function and consulted the Matplotlib docoment but found it seems that the library does not support 3D annotation. Does anyone know how to do this?</p> <p>Thanks!</p> |
30,477,134 | 0 | <p>You can use the functions in xmppStreamManagement for sending the request and get received id:</p> <pre><code>[xmppStreamManagement requestAck]; </code></pre> <p>and</p> <pre><code>- (void)xmppStreamManagement:(XMPPStreamManagement *)sender wasEnabled:(NSXMLElement *)enabled - (void)xmppStreamManagement:(XMPPStreamManagement *)sender didReceiveAckForStanzaIds:(NSArray *)stanzaIds </code></pre> <p>make sure the stream management is enabled by:</p> <pre><code>[self.xmppStreamManagement enableStreamManagementWithResumption:YES maxTimeout:0]; </code></pre> |
37,519,872 | 0 | How to implement PTZ camera joystick and controller in AngularJS <p>I am working in a Video management application where I need to desing and implement PTZ camera controllers and joystick. </p> <p>My concern is:</p> <ol> <li><p>Is it possible to make a stick in html where user can press click and move to change the angle.</p></li> <li><p>Is there any sample app where ptz controllers can be demonstrated like Tilt top,left,right,bottom in a image. (Or any other way.)</p></li> </ol> |
5,179,602 | 0 | <p>you should expose a DateTime dependency property on the control, done like so:</p> <pre><code> public DateTime Day { get { return (DateTime)GetValue(DayProperty); } set { SetValue(DayProperty, value); } } // Using a DependencyProperty as the backing store for Day. This enables animation, styling, binding, etc... public static readonly DependencyProperty DayProperty = DependencyProperty.Register("Day", typeof(DateTime), typeof(DayOfWeek), new UIPropertyMetadata(DateTime.MinValue)); </code></pre> <p>if you want this to be auto generated, what you should do is have an ItemsControl that contains this dayControl of yours, like so:</p> <pre><code> <ItemsControl x:Name="DaysItemsControl"> <ItemsControl.ItemTemplate> <DataTemplate> <custom:DayDisplay Day="{Binding}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </code></pre> <p>and then DataBind it from code behind:</p> <pre><code> DateTime[] week = new DateTime[] { new DateTime(2000,1,1), new DateTime(200,1,2) }; DayItemsControl.ItemsSource = week; </code></pre> |
30,123,349 | 0 | How do I remove empty nav tag in wordpress website? <p>Hello I would like to know how do i remove empty nav tag in the navigation bar. <a href="http://abraham-accountants.co.uk/" rel="nofollow">http://abraham-accountants.co.uk/</a></p> |
10,198,630 | 0 | <p>You may want to look at example 17-2 on the following site since it looks to cover what you are trying to do <a href="http://www.datypic.com/books/defxmlschema/chapter17.html" rel="nofollow">http://www.datypic.com/books/defxmlschema/chapter17.html</a>.</p> <p>EDIT: The feedback is that the key does need to be unique, so I'm removing that part of my response to avoid confusion.</p> |
24,039,059 | 0 | <p>In the highstock you cannot use categories, only datetime type, so you should parse your data to timestamp and use it in the data.</p> |
17,151,984 | 0 | <p>In the calendar setter area you getting the instance with actual date, then changing it's value, but not with add or substracting some piece of time. It's value is totally differs from the expected, because you setting absolute values not relatives.</p> <p>I've just extracted the calendar changes from your code and executed to demonstrate:</p> <pre><code>Calendar calendar = Calendar.getInstance(); System.out.println(calendar.getTime()); calendar.set(Calendar.DAY_OF_WEEK, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); System.out.println(calendar.getTime()); calendar.add(Calendar.HOUR, 1); System.out.println(calendar.getTime()); </code></pre> <p>the result is:</p> <pre><code>Mon Jun 17 18:00:56 CEST 2013 Sat Jun 22 00:01:00 CEST 2013 Sat Jun 22 01:01:00 CEST 2013 </code></pre> |
8,916,704 | 0 | <p>You can do it with Generalized Algebraic Data Types. We can create a generic (GADT) type with data constructors that have type constraints. Then we can define specialized types (type aliases) that specifies the full type and thus limiting which constructors are allowed.</p> <pre><code>{-# LANGUAGE GADTs #-} data Zero data Succ a data Axis a where X :: Axis (Succ a) Y :: Axis (Succ (Succ a)) Z :: Axis (Succ (Succ (Succ a))) type Axis2D = Axis (Succ (Succ Zero)) type Axis3D = Axis (Succ (Succ (Succ Zero))) </code></pre> <p>Now, you are guaranteed to only have <code>X</code> and <code>Y</code> passed into a function that is defined to take an argument of <code>Axis2D</code>. The constructor <code>Z</code> fails to match the type of <code>Axis2D</code>.</p> <p>Unfortunately, GADTs do not support automatic <code>deriving</code>, so you will need to provide your own instances, such as:</p> <pre><code>instance Show (Axis a) where show X = "X" show Y = "Y" show Z = "Z" instance Eq (Axis a) where X == X = True Y == Y = True Z == Z = True _ == _ = False </code></pre> |
23,598,839 | 0 | angular.js nested directive scope scope attribute <p>I would like to to a "map" tag witch should contains "marker" tags.</p> <p>my problem is that I would like to set the "marker" attributes using variables from the "map" parent scope.</p> <p>if I do this:</p> <pre><code> <map center="{{userPosition}}"> <marker lat="13.555232324" lng="43.555232324" text="Text1" on-click="callback('id_0')" ></marker> </map> </code></pre> <p>my code works, but I would like to do something like:</p> <pre><code> <map center="{{userPosition}}"> <marker lat="{{nearRooms['id_0'].lat}}" lng="{{nearRooms['id_0'].lng}}" text="Text1" on-click="callback('id_0')" ></marker> </map> </code></pre> <p>right now I can just read "lat" as a string.</p> <p>my map directive:</p> <pre><code>ngBMap.directive('map', [ function ($compile){ return { restrict: 'E', controller: ['$scope', function($scope) { this.markers = []; $scope.markers = []; this.mapHtmlEl = null this.map = null; this.exeFunc = function(func, context, args){ $scope.$parent[func].apply(context, args) } this.initializeMarkers = function(){ for (var i=0; i<this.markers.length; i++) { var marker = this.markers[i]; this.map.entities.push(marker); } } this.initializeMap = function(scope, elem, attrs){ var map_canvas = document.createElement('div') var _thisCtrl = this; .... this.mapHtmlEl = map_canvas; } this.setCenter = function(position){ var position = eval(position) var _position = new Microsoft.Maps.Location(position[0], position[1]) if(this.map) this.map.setView({center : _position}); } }], scope: { 'center': '@', }, link: function(scope, element, attrs, ctrl) { scope.$watch('center', function(center) { console.log('center: '+center) if(center){ ctrl.setCenter(center) } }, false); ctrl.initializeMap(scope, element, attrs) element.html(ctrl.mapHtmlEl) } } </code></pre> <p>}]);</p> <p>my marker directive:</p> <pre><code>ngBMap.directive('marker', [ function ($compile){ return { restrict: 'E', require: '^map', link: function(scope, element, attrs, mapController) { console.log('marker init') var getMarker = function() { var lat = attrs.lat ..... var marker = _marker; return marker; }//end getMarker var marker = getMarker(); mapController.markers.push(marker); } }}]); </code></pre> |
38,958,511 | 0 | java on osx - xmx ignored? <p>i've got two computers running on Mac OS X El Capitan and Ubuntu 16.04 LTS. On both is Java SDK 1.8.0_101 installed.</p> <p>When I try to start an game server on Ubuntu with more memory than available, I get the following output:</p> <pre><code>$ java -Xms200G -Xmx200G -jar craftbukkit.jar nogui Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x00007f9b6e580000, 71582613504, 0) failed; error='Cannot allocate memory' (errno=12) # # There is insufficient memory for the Java Runtime Environment to continue. # Native memory allocation (mmap) failed to map 71582613504 bytes for committing reserved memory. # An error report file with more information is saved as: # </code></pre> <p>On Mac OS I don't get this error:</p> <pre><code>$ java -Xms200G -Xmx200G -jar craftbukkit.jar nogui Loading libraries, please wait... </code></pre> <p>Both computers have 8GB of memory. I also tried with an other Apple computer - same problem.</p> <p>Is that a bug of java mac version?</p> <p>(Is there a way to force limit the memory usage e.g. to 1GB? -Xmx1G won't work and I wasn't able to find another reason. Not here neither on google)</p> <p>Thank you!</p> <p>Sorry for my bad english...</p> |
4,927,396 | 0 | <pre><code>var lis = $('ul > li'); function switchClass(i) { lis.eq(i).removeClass('current'); lis.eq(i = ++i % lis.length).addClass('current'); setTimeout(function() { switchClass(i); }, 2000); } switchClass(-1); </code></pre> <p><a href="http://jsfiddle.net/7ec63/" rel="nofollow">http://jsfiddle.net/7ec63/</a></p> |
31,526,846 | 0 | <p>This could be accomplished with a one-line PowerShell command:</p> <p><code>powershell "Get-ChildItem C:\...\Archives\*.* | Where-Object {$_.Name -notlike '"*_XYZ.*'"} | Foreach-object {Rename-Item -Path $_.FullName -NewName ($_.name -replace '\.', '_XYZ.')}"</code></p> |
7,830,596 | 0 | <p>Call <a href="http://developer.android.com/reference/android/app/Dialog.html#setCancelable%28boolean%29" rel="nofollow">setCancelable</a> using the false argument. Like this:</p> <pre><code> progressDialog.setCancelable(false); </code></pre> |
2,473,282 | 0 | <p>Simply put you can't. There are a couple of approaches to work around this problem though.</p> <p>The most common is to use an interface. Say <code>IMyType</code></p> <pre><code>interface IMyType { void foo(); } class A : IMyType ... class B : IMyType ... void bar<T>(T t) where T : IMyType { t.Foo(); } </code></pre> <p>This is a bit heavy weight though is it requires a metadata change for a solution. A cheaper approach is to provide a lambda expression which calls the appropriate function.</p> <pre><code>void bar<T>(T t, Action doFoo) { ... doFoo(); } var v1 = new A(); var v2 = new B(); bar(v1, () => v1.Foo()); bar(v2, () => v2.Foo()); </code></pre> |