pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
30,783,336 | 0 | Loading Image Animation only once <p>I have the following implementation and it is fully functional. I need to show loading animation image first time only, my current implementation it shows loading animation all the time.</p> <pre><code> var theDataSource = new kendo.data.DataSource({ transport: { read: function (op) { setTimeout(function () { op.success(data); }, 4000); } }, group: { field: "series" }, sort: { field: "category", dir: "asc" }, requestStart: function () { kendo.ui.progress($("#loading"), true); }, requestEnd: function () { kendo.ui.progress($("#loading"), false); } }); </code></pre> <h2><strong><a href="http://jsfiddle.net/8xbpws9x/" rel="nofollow">FIDDLE</a></strong></h2> |
2,011,537 | 0 | <p>Check the rest of your javascript. <code>return false;</code> or <code>.preventDefault();</code> should do the trick. If they're not working, it usually means there's an error somewhere else in your js, and your browser never gets to that line of code.</p> |
29,844,792 | 0 | Dynamically setting bar graph values from a XML source <p>I got some great help parsing some RSS into a menu yesterday using jQuery <a href="http://stackoverflow.com/questions/29818858/parse-rss-title-into-html-using-javascript">Parse RSS feed with JS</a>, and inspired by this I would like to use something similar to control some chart bars on a website. </p> <p>Some background:</p> <blockquote> <p>We are aiming to use a floating score in our upcoming tech reviews on a webpage, meaning that you assign a product an absolute score (lets say 67) and then the maximum score would be able to move as new and better products hit the market. This way you would still be able to read a review from last year and use the score for something meaningful, as the score of 67 is now measured against this years max-score. Hope it makes sense.</p> </blockquote> <p>Anyhow, our CMS only permits javascript to be embedded in news entries, so I can't store our review scores in SQL or use php, and I was thinking of using XML instead (not optimal, but it should work). Each review would then contain a certain number of results including the beforementioned final score (and some intermediate sub-scores as well). I need to be able to insert a piece of JS code that extracts the scores for a specific review from the XML file and inserts the HTML code needed to draw the bars.</p> <p>I have a JSfiddle set up, that contains the XML, it has the chart (hardcoded though), and using the jQuery code from my previous question I can sort of extract the results, but the code loops through all the XML and I don't really have a clue how to pick out the specific review number I need nor how to get things measured against the max-score, so it just prints everything right now and calculates a score based on a max-score of 100. I haven't tied the values to my chart yet, so the test version just prints the results in a ul/li.</p> <p><a href="http://jsfiddle.net/TorbenRasmussen/sLxdfyj7/35/" rel="nofollow">Link to JSFiddle</a></p> <p>So basically I need some sort of code that I can invoke from my HTML that goes along the lines of </p> <pre><code>ShowScores(testno) </code></pre> <p>that would write everything inside the first </p> <pre><code><div class="row">..</row> </code></pre> <p>containing the bars, where the %-width of the bars would be calculated as the score assigned divided by the maxscore:</p> <ul> <li>Each item has 3 assigned scores: scorePicture, scoreFeature, scoreUI, and 1 calculated total score (weighted average)</li> <li>A global max score exists for each of the 3 scores: topscorePicture, topscoreFeature, topscoreUI</li> </ul> <p>As I suck at JS, I have spent 5 hours getting to this point, and I have no clue how to make things load from e.g. a <code>testscore.xml</code> file instead and then extract what I need with jQuery - and I probably also need some help making my HTML load the script i.e. how to invoke it afterwards. <a href="https://api.jquery.com/jQuery.parseXML/" rel="nofollow">The documentation on jQuery</a> is concerned with loading all content in the XML and not just a specific node?</p> <p>All help is appreciated.</p> <p>My own thoughts on some pseudo code would be a script that, when envoked from my HTML document would do something like</p> <pre><code>function(reviewNo) var max1 = load maxscore1 from XML var max2 = load maxscore2 from XML var max3 = load maxscore3 from XML var score1 = load assignedscore1 for reviewNo from XML var score2 = load assignedscore2 for reviewNo from XML var score3 = load assignedscore2 for reviewNo from XML Calculate % width of bar 1, bar 2 and bar 3 and save as variables as math.round() write HTML DIV code and subsitute the width of the bars with the calculated values from above </code></pre> |
4,041,000 | 0 | What is this error? (And why doesn't it occur in other classes?) <p>I'm trying to write a some container classes for implementing primary data structures in C++. The header file is here:</p> <pre><code>#ifndef LINKEDLIST1_H_ #define LINKEDLIST1_H_ #include <iostream> using namespace std; template<class T> class LinkedList1; template<class T> class Node; template<class T> class Node { friend class LinkedList1<T> ; public: Node<T> (const T& value) { this->Data = value; this->Next = NULL; } Node<T> () { this->Data = NULL; this->Next = NULL; } T Data; Node* Next; }; template<class T> class LinkedList1 { friend class Node<T> ; public: LinkedList1(); // LinkedList1<T>(); ~LinkedList1(); // Operations on LinkedList Node<T>* First(); int Size(); int Count(); bool IsEmpty(); void Prepend(Node<T>* value); //O(1) void Append(Node<T>* value); void Append(const T& value); void Insert(Node<T>* location, Node<T>* value); //O(n) Node<T>* Pop(); Node<T>* PopF(); Node<T>* Remove(const Node<T>* location); void Inverse(); void OInsert(Node<T>* value); // TODO Ordered insertion. implement this: foreach i,j in this; if i=vale: i+=vale, break; else if i<=value<=j: this.insert(j,value),break void print(); private: Node<T>* first; int size; }; #endif /* LINKEDLIST1_H_ */ </code></pre> <p>When I try to use it in another class, for example like this:</p> <pre><code>void IDS::craete_list() { LinkedList1<int> lst1 = LinkedList1<int>::LinkedList1<int>(); } </code></pre> <p>this error occurs:</p> <pre><code>undefined reference to 'LinkedList1<int>::LinkedList1<int>()' </code></pre> <p>The constructor of the class is public and its header file is included. I also tried to include the .cpp file of the class, but that didn't help. I wrote other classes such SparseMatrix and DynamicArray in exactly the same way and there was no error!...</p> |
3,155,741 | 0 | Free Editor for NAnt Scripting? <p>Is there any Free Editor for NAnt scripting with little bit of intelligence is fine....</p> <p><br/> nrk</p> |
10,292,838 | 0 | <ul> <li><p><strong>Shared hosting</strong>: check government requirements, I'm not in the health care field, but I'd be very surprised if there are no rules/laws governing storage of sensitive personal information. If credit cards/ecommerce has PCI DSS requirements, I would think health care data would have at least same level (likely stricter) data protection rules (e.g. <a href="http://www.hhs.gov/ocr/privacy/hipaa/understanding/index.html" rel="nofollow"><strong>HIPAA</strong></a>?)</p></li> <li><p>I don't know much about 1&1, but "where" may also be an issue(?) - <strong>where</strong> are the servers (of 1&1) physically located?</p></li> <li><p>yet another thought: instead of having salt/pwd generated by user (how long/secure should they be?) Perhaps look into <a href="http://technet.microsoft.com/en-us/library/bb510663%28v=sql.100%29.aspx" rel="nofollow">SQL server encryption options</a>, moving the job to SQL instead of users and/or code. </p></li> <li><p>Decide if data should be encrypted or hashed (storage/retrieval vs. lookup) - re: password = hashed, SSN - depends on usage I guess. <a href="http://technet.microsoft.com/en-us/library/ms174415%28v=sql.100%29.aspx" rel="nofollow">Hash can also be done in SQL Server</a>....</p></li> </ul> |
16,370,364 | 0 | <p>Here is an example of formatting your date to ISO 8601</p> <p><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Example.3A_ISO_8601_formatted_dates" rel="nofollow">https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Example.3A_ISO_8601_formatted_dates</a></p> <p>There are several approaches you can use to format the date/time, below is a blog on such examples.</p> <p><a href="http://blog.stevenlevithan.com/archives/date-time-format" rel="nofollow">http://blog.stevenlevithan.com/archives/date-time-format</a></p> <p>It's hard to understand what you want to do from your wording but maybe this will help you to get a little further along.</p> <p>Good luck.</p> |
10,450,991 | 0 | asp.net mvc - Data lost on post back <p>I have a form that only has a checkbox. If the checkbox is not checked then the page won't be valid and won't submit the data. On the view I have out putted some fields from the model object, just to let the user know what they are deleting. When I click the Submit button and the model state is not valid the page will show the validation error but the data from the model is no longer there!</p> <p>Does anyone know how I can persist this data without making another call to the database to populate the model object?</p> <p>Thanks</p> |
10,997,143 | 0 | django ajax and non-ajax templates <p>i have a django template - one that is normally loaded via a standard get request. However, i would also like to use this template for an ajax get. </p> <p>I know i can use request.is_ajax to distinguish the call, and thus work out <em>which</em> page i should serve - what i don't know is how to avoid replication.</p> <p>The problem is, the page extends a base htm file - one that has all the bells and whistles (you know, header, menu et al). I don't want this to appear in the ajax page though! What i'd like there is for the page to appear, <em>not</em> extending base htm</p> <p>I can only think that perhaps i have two files - one that has just the contents (ajax version) and another that extends base htm, and somehow imports (not extends) the first file... </p> <p>any ides how i'd do the above, or how i am meant to solve this generally?</p> |
20,873,730 | 0 | <p>Perhaps it can be achieved by wrapping the <code>InputStream</code> in a <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/ProgressMonitorInputStream.html#ProgressMonitorInputStream%28java.awt.Component,%20java.lang.Object,%20java.io.InputStream%29" rel="nofollow"><code>ProgressMonitorInputStream</code></a>. But make sure you do not block the Event Dispatch Thread, or it will freeze until completion. </p> <p>See <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/progress.html" rel="nofollow">How to Use Progress Bars</a> for details.</p> |
9,201,258 | 0 | How to Detect when entering a password field <p>I am currently trying to debug an issue I've been experiencing with the program 'matchbox-keyboard'(http://matchbox-project.org/), and I'm hoping for some assistance. matchbox-keyboard is an on-screen keyboard that I am currently using in a touchscreen kiosk to allow users to enter some basic input for doing searches etc. It may be a little old, but nonetheless it is ideal for my application because it is an 'on-demand' keyboard (i.e. it only appears when needed), lightweight, and works well with matchbox-window-manager, which I am using on the device. However, one of the sites the kiosk must visit requires the user to log in temporarily, and for some reason the on-screen keyboard disappears whenever the user clicks in the password field.</p> <p>The site that the users must visit cannot be changed, so I resolved myself to try and patch matchbox-keyboard to change this behavior. To that end, I have traced the issue back to a custom Atom defined in the code, as follows</p> <pre><code>typedef enum { MBKeyboardRemoteNone = 0, MBKeyboardRemoteShow, MBKeyboardRemoteHide, MBKeyboardRemoteToggle, } MBKeyboardRemoteOperation; </code></pre> <p>=============</p> <pre><code>void mb_kbd_remote_init (MBKeyboardUI *ui) { Atom_MB_IM_INVOKER_COMMAND = XInternAtom(mb_kbd_ui_x_display(ui), "_MB_IM_INVOKER_COMMAND", False); } </code></pre> <p>This Atom is then checked for in the Xevents, and then data from the xevent (<code>xevent->xclient.data.l[0]</code>) is used to determine what state to put the keyboard in. The thing I can't figure out is how does the X display know when the Xevent is supposed to be a '_MB_IM_INVOKER_COMMAND' type, and how it actually sets the data value. Specifically, how/why it sets the value of <code>xevent->xclient.data.l[0]</code> to 2 (<code>MBKeyboardRemoteHide</code>) when I enter a password field.</p> <p>I have tried scouring the code for references to the critical objects mentioned here, as well as reading up on Xlib Events from the guide here: <a href="http://tronche.com/gui/x/xlib/events/" rel="nofollow">http://tronche.com/gui/x/xlib/events/</a>, and searching for answers on google, but honestly this is just a bit over my head, and I can't get a grip on the issue. At this point it has passed from a necessity for my kiosk project and become more of a curiosity on my part(and something that will drive me nuts until I figure it out), so if anybody could help me get some answers, I would be most appreciative.</p> <p>========== Update ==========</p> <p>Further testing/information: </p> <p>the issue does not appear to be browser implementation specific, as I tried my desired website,as well as a basic test HTML page that has only a text and password field, on a gecko browser(Firefox), as well as a webkit browser(Midori), and in both browsers, on both pages, the behavior was the same. Here's the test HTML page for reference: </p> <pre><code><head> </head> <body> <form> Name: <input type="text" name="firstname"><br> PW: <input type="password" name="lastname"> </form> </body> </html> </code></pre> <p>It appears to me that the password field, is intentionally rejecting focus for some reason, whereby clicking the field directly causes the gtk-im method focus-out to be called. My suspicion is that it's probably a part of the GTK implementation, possibly related to the act that password fields are typically 'hidden'. Perhaps this is done to prevent the on-demand clipboard from storing passwords or something to that effect?</p> <p>When examining the event list/debug output from clicking on the password field and on the text field, the list of received events for each field type is very similar. Many of the events are the same type, but there are a few differences between them that I am still trying to decode. I know the event numbers are mostly meaningless in this context, but for illustration, here's the different event lists for non-password field:</p> <pre><code>matchbox-keyboard-remote.c:47,mb_kbd_remote_process_xevents() got a message of type _MB_IM_INVOKER_COMMAND, val 1 matchbox-keyboard-ui.c:560,mb_kbd_ui_redraw() mark matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 37748776 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651628 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651629 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35682433 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 </code></pre> <p>and for password field:</p> <pre><code>matchbox-keyboard-remote.c:47,mb_kbd_remote_process_xevents() got a message of type _MB_IM_INVOKER_COMMAND, val 2 matchbox-keyboard-ui.c:1230,mb_kbd_ui_event_loop() Hide timed out, calling mb_kbd_ui_hide matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651628 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35682433 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35665943 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 39845918 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651628 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651629 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35682433 </code></pre> <p>Unfortunately this is the best my info gets at the moment, since my C skills are quite rusty.</p> |
23,354,327 | 0 | <p>First thing, you should fix up your markup, your nesting is wrong:</p> <pre><code><nav> <ul> <li id="menu_toggle">Menu</li> <li><a href="#">Link 01</a></li> <li><a href="#">Link 02</a></li> <li><a href="#">Link 03</a></li> </ul> </nav> </code></pre> <p>And change your CSS to something like this:</p> <pre><code>nav li { display: none; } nav.open li, nav:hover li, #menu_toggle { display: block; } </code></pre> <p>This means all your list items are invisible, but for the toggle and if the nav has a class <code>open</code>, or if the mouse hovers the nav (on a desktop).</p> <p>Then your JavaScript (jQuery) could look like this:</p> <pre><code>$(function(){ // document ready $('#menu_toggle').on('touchstart', function(){ $('nav').toggleClass('open'); }); }); </code></pre> <p>This will toggle the menu on a touch device when <code>hover</code> isn't really working.</p> <p>Tracking a touch anywhere else but the menu is a bit trickier, you could:</p> <ol> <li>Add a once off event handler to the rest of the document whenever you open the menu</li> <li>Put an overlay between the menu and your content and catch events on that</li> </ol> <p>So for option 1, assuming you have something like this:</p> <pre><code><nav>...</nav> <div id="content">...</div> </code></pre> <p>You could do this:</p> <pre><code>$(function(){ // document ready var isMenuOpen = false; $('#menu_toggle').on('touchstart', function(){ // reverse boolean isMenuOpen = !isMenuOpen; // add/remove class depending on state $('nav').toggleClass('open', isMenuOpen); if( isMenuOpen ){ // If menu is now open, add a closing event handler to the content $('#content').once('touchstart', function(){ $('nav').removeClass('open'); }); } }); }); </code></pre> |
16,220,532 | 0 | <p>This seems to work: <a href="http://jsfiddle.net/QLn9b/1/" rel="nofollow">http://jsfiddle.net/QLn9b/1/</a></p> <p>It is using your original code:</p> <pre><code>$("select").change(function() { $("select").not(this).find("option[value="+ $(this).val() + "]").attr('disabled', true); }); </code></pre> |
2,428,589 | 0 | <pre><code><script type="text/javascript"> function voimakaksikkoStats(obj) { alert(obj.TestsTaken); } </script> <script type="text/javascript" src="http://www.heiaheia.com/voimakaksikko/stats.json"></script> </code></pre> <p>I never got it working with jQuery, but the simple code above solved my problems. I found help from Yahoo: <a href="http://developer.yahoo.com/common/json.html" rel="nofollow noreferrer">http://developer.yahoo.com/common/json.html</a></p> |
20,254,549 | 0 | <p>I was able to make GWT work with libgdx simply by:</p> <ul> <li>downloading (<a href="http://www.gwtproject.org/download.html" rel="nofollow">http://www.gwtproject.org/download.html</a>) the GWT SDK,</li> <li>extracting it,</li> <li>then in the project structure -> <code>project-name-html</code> -> dependencies,</li> <li>just press the + and add the extracted GWT directory</li> <li>A dialog appears and I just unticked all the samples</li> </ul> <p>The "Dependencies Storage Format" needed to be "Intellij IDEA", not Eclipse for this to work for me.</p> |
33,240,205 | 1 | Pass list of different named tuples to different csv by tuple name <p>I have a program in which I wish to record all major changes that occur. For example: each time a variable x changes in value record the time of the change and the change itself. Within the program there are many such changes and not all have the same number of parameters. </p> <p>I decided to use namedtuples to store each instance of a change and to then put those namedtuples into a single master data list -ready for export to csv. I have used tuples as of course they are immutable which is ideal for record keeping. Below I have tried to explain in as concise a manner as possible what I have done and tried. Hopefully my problem and attempts so far are clear.</p> <p>So I have:</p> <pre><code>data = [] </code></pre> <p>as the main repository, with namedtuples of the form:</p> <pre><code>a_tuple = namedtuple('x_change', ['Time', 'Change']) another_tuple = namedtuple('y_change', ['Time', 'Change', 'id']) </code></pre> <p>I can then append instances of these namedtuples each time a change is detected to data using commands as below:</p> <pre><code>data.append(a_tuple(a_time, a_change)) data.append(another_tuple(a_time, a_change, an_id)) </code></pre> <p>If I then print out the contents of data I would get output like:</p> <pre><code>x_change(a_time=4, a_change=1) y_change(a_time=5, a_change=3, an_id = 2) y_change(a_time=7, a_change=1, an_id = 3) x_change(a_time=8, a_change=3) </code></pre> <p>what I would like to do is export these tuples to csv files by tuple name. So in the above case I would end up with two csv files of the form:</p> <pre><code>name, time, change x_change, 4, 1 x_change, 8, 3 </code></pre> <p>and;</p> <pre><code>name, time, change, id y_change, 5, 3, 2 y_change, 7, 1, 3 </code></pre> <p>I have to date managed to write to a single csv as below:</p> <pre><code>with open ('events.csv', 'w', newline='') as csvfile: output = csv.writer(csvfile, delimiter = ',') for row in data: output.writerow(row) </code></pre> <p>which produces the output minus the tuple name. So:</p> <pre><code>4, 1 5, 3, 2 7, 1, 3 8, 3 </code></pre> <p>I have also tried:</p> <pre><code>with open ('events.csv', 'w', newline='') as csvfile: output = csv.writer(csvfile, delimiter = ',') for row in data: output.writerow(str(row)) </code></pre> <p>Which splits the file into csv format, including the tuple name, by every character getting (first line only included): </p> <pre><code>x, _, c, h, a, n, g, e, 4, 1 </code></pre> <p>I have searched for a solution but not come across anything that fits what I am trying to do and am now at a loss. Any assistance would be appreciated.</p> |
35,759,859 | 0 | <p>If I assume that the values are unique in each column, then the key idea is doing a join on the <em>second</em> column in the table followed by aggregation.</p> <p>A <code>having</code> clause can count the number of matches and be sure that it matches the expected number in the first table:</p> <pre><code>select t1.c1, t2.c1 from t1 join t2 on t1.c2 = t2.c2 group by t1.c1, t2.c1 having count(*) = (select count(*) from t1 tt1 where tt1.c1 = t1.c1); </code></pre> |
25,691,983 | 0 | <p>The reason why you are getting different results is the fact that your colour segmentation algorithm uses <a href="http://en.wikipedia.org/wiki/K-means_clustering" rel="nofollow"><em>k</em>-means clustering</a>. I'm going to assume you don't know what this is as someone familiar in how it works would instantly tell you that this is why you're getting different results every time. In fact, the different results you are getting after you run this code each time are a natural consequence to <em>k</em>-means clustering, and I'll explain why. </p> <p>How it works is that for some data that you have, you want to group them into <em>k</em> groups. You initially choose <em>k</em> random points in your data, and these will have labels from <code>1,2,...,k</code>. These are what we call the <strong>centroids</strong>. Then, you determine how close the rest of the data are to each of these points. You then group those points so that whichever points are closest to any of these <em>k</em> points, you assign those points to belong to that particular group (<code>1,2,...,k</code>). After, for all of the points for each group, you update the <strong>centroids</strong>, which actually is defined as the representative point for each group. For each group, you compute the average of all of the points in each of the <em>k</em> groups. These become the <strong>new</strong> centroids for the next iteration. In the next iteration, you determine how close each point in your data is to <strong>each of the centroids</strong>. You keep iterating and repeating this behaviour until the centroids don't move anymore, or they move very little.</p> <p>How this applies to the above code is that you are taking the image and you want to represent the image using only <em>k</em> possible colours. Each of these possible colours would thus be a centroid. Once you find which cluster each pixel belongs to, you would replace the pixel's colour with the centroid of the cluster that pixel belongs to. Therefore, for each colour pixel in your image, you want to decide which out of the <em>k</em> possible colours this pixel would be best represented with. The reason why this is a colour segmentation is because you are <strong>segmenting</strong> the image to belong to only <em>k</em> possible colours. This, in a more general sense, is what is called <strong>unsupervised segmentation</strong>.</p> <p>Now, back to <em>k</em>-means. How you choose the initial centroids is the reason why you are getting different results. You are calling <em>k</em>-means in the default way, which automatically determines which initial points the algorithm will choose from. Because of this, you are <strong>not guaranteed</strong> to generate the same initial points each time you call the algorithm. If you want to <strong>repeat</strong> the same segmentation no matter how many times you call <code>kmeans</code>, you will need to <strong>specify the initial points yourself</strong>. As such, you would need to modify the <em>k</em>-means call so that it looks like this:</p> <pre><code>[cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', 3, 'start', seeds); </code></pre> <p>Note that the call is the same, but we have added two additional parameters to the <em>k</em>-means call. The flag <code>start</code> means that you are specifying the initial points, and <code>seeds</code> is a <code>k x p</code> array where <em>k</em> is how many groups you want. In this case, this is the same as <code>nColors</code>, which is 3. <code>p</code> is the dimension of your data. Because of the way you are transforming and reshaping your data, this is going to be 2. As such, you are ultimately specifying a <code>3 x 2</code> matrix. However, you have a <code>Replicate</code> flag there. This means that the <em>k</em>-means algorithm will run a certain number of times specified by you, and it will output the segmentation that has the least amount of error. As such, we will repeat the <code>kmeans</code> calls for as many times as specified with this flag. The above structure of <code>seeds</code> will no longer be <code>k x p</code> but <code>k x p x n</code>, where <code>n</code> is the number of times you want to run the segmentation. This is now a 3D matrix, where each 2D slice determines the initial points for each run of the algorithm. Keep this in mind for later.</p> <p>How you choose these points is up to you. However, if you want to randomly choose these and not leave it up to you, but want to reproduce the same results every time you call this function, you should set the <a href="http://www.mathworks.com/help/matlab/ref/rng.html" rel="nofollow">random seed generator</a> to be a known number, like <code>123</code>. That way, when you generate random points, it will always generate the same sequence of points, and is thus reproducible. Therefore, I would add this to your code before calling <code>kmeans</code>.</p> <pre><code>rng(123); %// Set seed for reproducibility numReplicates = 3; ind = randperm(size(ab,1), numReplicates*nColors); %// Randomly choose nColors colours from data %// We are also repeating the experiment numReplicates times %// Make a 3D matrix where each slice denotes the initial centres for each iteration seeds = permute(reshape(ab(ind,:).', [2 nColors numReplicates]), [2 1 3]); %// Now call kmeans [cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', numReplicates, 'start', seeds); </code></pre> <p>Bear in mind that you specified the <code>Replicates</code> flag, and we want to repeat this algorithm a certain number of times. This is <code>3</code>. Therefore, what we need to do is specify initial points for <strong>each run of the algorithm</strong>. Because we are going to have 3 clusters of points, and we are going to run this algorithm 3 times, we need 9 initial points (or <code>nColors * numReplicates</code>) in total. Each set of initial points has to be a <strong>slice</strong> in a 3D array, which is why you see that complicated statement just before the <code>kmeans</code> call.</p> <p>I made the number of replicates as a variable so that you can change this and to your heart's content and it'll still work. The complicated statement with <a href="http://www.mathworks.com/help/matlab/ref/permute.html" rel="nofollow"><code>permute</code></a> and <a href="http://www.mathworks.com/help/matlab/ref/reshape.html" rel="nofollow"><code>reshape</code></a> allows us to create this 3D matrix of points very easily.</p> <p>Bear in mind that the call to <a href="http://www.mathworks.com/help/matlab/ref/randperm.html" rel="nofollow"><code>randperm</code></a> in MATLAB only accepted the second parameter as of recently. If the above call to <code>randperm</code> doesn't work, do this instead:</p> <pre><code>rng(123); %// Set seed for reproducibility numReplicates = 3; ind = randperm(size(ab,1)); %// Randomly choose nColors colours from data ind = ind(1:numReplicates*nColors); %// We are also repeating the experiment numReplicates times %// Make a 3D matrix where each slice denotes the initial centres for each iteration seeds = permute(reshape(ab(ind,:).', [2 nColors numReplicates]), [2 1 3]); %// Now call kmeans [cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', numReplicates, 'start', seeds); </code></pre> <hr> <p>Now with the above code, you should be able to generate the same colour segmentation results every time.</p> <p>Good luck!</p> |
31,639,787 | 0 | <p>Since your array is sorted, you can use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(int[],%20int)" rel="nofollow">Arrays.binarySearch</a> which returns index of the element if it is present in the <code>array</code>, otherwise returns <code>-1</code>.</p> <pre><code>if(Arrays.binarySearch(numbers,j) != -1){ system.out.println("It is in the array."); } else { system.out.println("It is not in the array."); } </code></pre> <p>Just a faster way to search and you also don't need to convert your <code>array</code> to <code>list</code>.</p> |
38,520,200 | 0 | <blockquote> <p>In your Block file</p> </blockquote> <pre><code>namespace "Your Module namespace"; class modelclass extends \Magento\Framework\View\Element\Template { /** @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory */ protected $_orderCollectionFactory; /** @var \Magento\Sales\Model\ResourceModel\Order\Collection */ protected $orders; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory, array $data = [] ) { $this->_orderCollectionFactory = $orderCollectionFactory; parent::__construct($context, $data); } public function getOrders() { if (!$this->orders) { $this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect('*'); } return $this->orders; } </code></pre> <blockquote> <p>In your phtml file</p> </blockquote> <pre><code>$_orders = $block->getOrders(); if ($_orders && count($_orders)) { $complete = $pending = $closed = $canceled = $processing = $onHold = 0; foreach ($_orders as $_order) { $label = $_order->getStatusLabel(); switch ($label) { case 'Complete' : $complete++; break; case 'Pending' : $pending++; break; case 'Processing' : $processing++; break; case 'Canceled' : $canceled++; break; case 'Closed' : $closed++; break; } } echo "Order Status <br>"; echo "Completed Order " . $complete . "<br>"; echo "Pending Order " . $pending . "<br>"; echo "Closed Order " . $closed . "<br>"; echo "Canceled Order " . $canceled . "<br>"; echo "Processing Order" . $processing . "<br>"; } else{ echo "You have no Orders"; } </code></pre> |
39,333,857 | 0 | <p>The variable <code>more</code> is only in scope inside the do while loop. One solution would be to declare more outside the loop and only update its value inside.</p> <p>Like this...</p> <pre><code>public static void main(String[] args) { Scanner input = new Scanner(System.in); String cont = "y"; String more = null; do { . .// code here . System.out.println("Do you want to continue?"); more = input.next(); } while (more.equals(cont)); </code></pre> <p>This happens because any variable which is declared inside a do-while construct is only in scope within that same loop, it cannot be accessed outside the loop, or in the loop condition.</p> <p>Declaring the variable outside the loop and within main gives access to the variable anywhere inside the main method.</p> |
4,567,218 | 0 | C#:SerialPort: read and write buffer size <p>I am writing a program to send and receive data via a serial port with C#.</p> <p>Although I have read this reference: <a href="http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readbuffersize.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readbuffersize.aspx</a>, I am not quite clear if I change the values of the buffer for reading and writing:</p> <pre><code>serialPort.ReadBufferSize = 1; // or 1024 ? serialPort.WriteBufferSize = 1;// or 1024 ? </code></pre> <p>The values (1 or 1024) should be better to be smaller or bigger?</p> <p>Thanks in advance.</p> |
12,118,389 | 0 | <p>If you have a 5 second animation and you stop it in the middle and then you restart the same animation with the same final point for the animation and you tell it to run for 5 seconds, it will go slower because it has less distance to go in the 5 seconds.</p> <p>If you want it to restart with the same speed it had before, then you have to reduce the amount of time in the second animation to reflect a pro-rated amount of time.</p> <p>Remember <code>speed = distance / time</code>. If your restarted animation has a shorter distance to travel but the same time, it's going be a slower speed unless you also reduce the time proportionally.</p> |
32,706,267 | 0 | <p>There is only 1 <code>IFRAME</code> on the page so you can just find it by tag name. The page loaded very slowly for me but I'm in the US so that may have something to do with it. You may have to wait for the <code>IFRAME</code> to become available and then get a handle to it.</p> |
7,545,226 | 0 | CoreData (storing new object) in AppDelegate = SIGABRT <p>I've intented to make a simple function in AppDelegate to store some data in database (CoreData) which would be called from various <code>ViewController</code> classes connected do <code>AppDelegate</code>. This is the body of this function:</p> <pre><code>- (void) setSetting:(NSString *)setting :(NSString *)value { NSManagedObject* newSetting = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:self.managedObjectContext]; [newSetting setValue:value forKey:setting]; NSError* error; [self.managedObjectContext save:&error]; } </code></pre> <p>But calling this function (even from AppDelegate itself) returns SIGABRT on line with <code>setValue</code></p> <p>But when I implement the function in <code>ViewController</code> class (replacing <code>self.</code> with proper connection to <code>AppDelegate</code> of course) - it works <strong>fine</strong>.</p> <p>I don't get it and I would really appreciate some help in creating flexible function in <code>AppDelegate</code> to save the data in database.</p> |
17,131,774 | 0 | <p>Use <code>fields_for</code> for the associated models.<br> <strong>There should be no square brackets arround the parameters of <code>fields_for</code></strong></p> <p>In your code example, I cannot find the relation between <code>Patient</code> and <code>Diagnosis</code>, and the plural of diagnosis is <strong>diagnoses</strong>, you can specify this in <code>config/initializers/inflections.rb</code>:</p> <pre><code>ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'diagnosis','diagnoses' end </code></pre> <p>So your <code>Patient</code> model should contain</p> <pre><code>class Patient < ActiveRecord::Base attr_accessible :age, :name, :city, :street, :number has_many :diagnoses end </code></pre> <p>And you can write in your form:</p> <pre><code> <div class="field"> <%= f.label :content %><br /> <%= f.text_field :content %> </div> <%= fields_for(@patient, @patient.diagnoses.build) do |u| %> <div class="field"> <%= u.label :content %><br /> <%= u.text_field :content %> </div> <% end %> <div class="actions"> <%= f.submit %> </div> </code></pre> |
22,312,293 | 0 | <p>If I understand you correctly URL rewriting is not what you need. Why? Because mapping an external URL to some internal URL / alias is not going to help you serve the file.</p> <p>What you need is a way to have an external URL process a request and return the file in question. Luckily Drupal 7 makes this pretty easy to do.</p> <p>1.) Define a menu mapping in hook_menu()</p> <pre><code> function MODULE_menu() { $items = array(); $items['pdf'] = array( 'title' => 'Map PDF', 'page callback' => 'MODULE_show_pdf', 'access callback' => TRUE, 'description' => 'TBD', 'type' => MENU_CALLBACK, ); return ($items); } </code></pre> <p>2.) Define your callback function</p> <pre><code> function MODULE_show_pdf($somehtmlfile = '') { $stream_wrapper_uri = 'public://pdf/' . $somehtmlfile . '.pdf'; $stream_wrapper = file_create_url($stream_wrapper_uri); $stream_headers = array( 'Content-Type' => file_get_mimetype($stream_wrapper_uri), 'Content-Length' => filesize($stream_wrapper_uri), 'Pragma' => 'no-cache', 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Expires' => '0', 'Accept-Ranges' => 'bytes' ); file_transfer($stream_wrapper_uri, $stream_headers); } </code></pre> <p>Some things to note:</p> <ol> <li><p>There is no need to explicitly define somehtmlfile param in the menu. This allows you more flexibility in that you can simply define whatever params you would like this external URL to support simply by adjusting the params in the callback function.</p></li> <li><p>When public stream wrapper dirs/files are sub-dir of: sites/default/files</p></li> <li><p>It is assumed that although you have somehtmlfile in the URL that you really want to stream somehtmlfile.pdf (if you want to stream somehtmlfile.html then simply adjust the hard coded '.pdf' suffix)</p></li> <li><p>file_transfer calls drupal_exit() as its last step which essentially ends request processing.</p></li> <li><p>Make sure to flush your cache otherwise the above will not work as menu entries are cached and the external URL will fail to be found</p></li> </ol> |
3,069,644 | 0 | <p>Created two scripts: one serializes it's arguments to a <code>[a-ZA-Z0-9=_]*</code> strings <a href="http://vi-server.org/vi/bin/serialize.sh" rel="nofollow noreferrer">http://vi-server.org/vi/bin/serialize.sh</a>, other starts this command line (with optional prepended arguments) <a href="http://vi-server.org/vi/bin/deserialize.sh" rel="nofollow noreferrer">http://vi-server.org/vi/bin/deserialize.sh</a>.</p> <p>Serialize:</p> <pre><code>#!/bin/bash n=$#; for ((i=0; i<$n; ++i)); do if [ -z "$1" ]; then echo 1 else printf '%s' "$1" | base64 -w 0 echo fi shift done | tr '\n' '_' echo -n "0" </code></pre> <p>Deserialize:</p> <pre><code>#!/bin/bash if [ -z "$1" ]; then echo "Usage: deserialize data [optional arguments]" echo "Example: \"deserialize cXFx_d3d3_0 eee rrr\"" echo " will execute \"eee rrr qqq www\"" exit 1; fi DATA="$1"; shift i=0 for A in ${DATA//_/' '}; do if [ "$A" == "0" ]; then break; fi if [ "$A" == "1" ]; then A="" fi ARR[i++]=`base64 -d <<< "$A"` done exec "$@" "${ARR[@]}" </code></pre> <p>Example: </p> <pre><code>deserialize `serialize qqq www` echo </code></pre> |
30,827,763 | 0 | <p><code>View.OnClickListener</code> is an interface which you need to implement when you want to handle click events. In your code, you are doing that by doing <code>new View.OnClickListener()</code>. Here you are actually creating an anonymous class that implements <code>View.OnClickListener</code>. And any class that implements <code>View.OnClickListener</code> must also implement all the methods declared in it (e.g. the <code>onClick</code> method). Also, in <code>public void onClick(View v) {..}</code>, the <code>View v</code> denotes the view or the button that was clicked so that you can perform whatever you want with it. For example, get it's id, change it's color etc.</p> |
14,659,172 | 0 | Perl script to split a file and process then concatenate based on size and a string <p>Could somebody help me to get some logic to following in perl I am using windows 7.</p> <p>C:\script>perl split_concatenate.pl large_file a or b (Input would be large file and value a or b to process it later).</p> <ol> <li>Check the file if it is greater than 40KB (some size), and choice is "a" , if not run a command </li> </ol> <p>command -i large_file.txt -o large_file_new -a</p> <p>else if the choice is b </p> <p>command -i large_file.txt -o large_file_new -b</p> <p>else</p> <p>if it is greater say 40KB+, split the file for each 40KB arround (will be part1,) and append a first "particular string" which will be in the file_part2 to the part1 save it for processing, if there are multiple "particular string" then create subsequent files which should end with next "particular string" in the following part. ("Particular String" starts with some String but ends in different value). So script should search if there are more "Particular string", in the part2 or so and append first available one, if there is only one available no need to anything just split. As file always should end with a particular string. </p> <p>Then process same command </p> <p>command -i filepart1.txt -o filepart1.dat -a command -i filepart2.txt - o filepart2.dat (if needed) -a </p> <p>or </p> <p>command -i filepart1.txt -o filepart1.dat -b command -i filepart2.txt - o filepart2.dat (if needed) -b</p> <p>After this needs to be concatenated.</p> <p>Concatenate filepart1.dat + filepart2.dat + filepartN =large_file.dat</p> <p>I started to find the size first using below code,</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use File::stat; my $filesize = stat("Full_File.txt")->size; print "Size: $filesize\n"; exit 0; </code></pre> <p>It will be great if some one help so I can learn. If this is not possible, then @ each 500th line the file reaches to 40KB, so I think this would be easier, every 500th line append the Next available "Particular String", and split and process above command, if file is less than 1000 lines then only 2 split and no need to append in the part2 as already it has one in its eof. May be easier? </p> <p>Better explanation:</p> <p>large_file.txt </p> <pre><code>xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx xxxxxx var:value_var_v(abcd) xxxxxxx // first split happens here as here assume it is 40kb xxxxxx xxxxxxx var:value_var_v(efgh) </code></pre> <p>If this is too big then split at line 5, say <code>large_files_part1</code>. Its end should contain <code>var:value_var_v(1234)</code>. After the 5th line it should split again at line 9 and will become <code>large_files_part2</code> and have <code>var:value_var_v(4567)</code> at the end. part3 wil go till line 12 and include <code>var:value_var_v(abcd)</code> at the end, and so on. If there is only one <code>var:value_var_v?</code> after the first split then only two parts is fine as long as the lines in both parts is arround 500. If there are say 1300 line in the main file then three splits are needed. The end of each file should have the next available "string", so the 1001st line will be the first <code>var:value_var_v(1234)</code> available after line 1000. String always starts with var:value_var_v, end with any thing. Hope this is clear.</p> <p>Output Expected: First case: So, out put will be, _part1.txt will be arround 40,000 if it had only one occurrence of string</p> <pre><code>xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx xxxxxx var:value_var_v(abcd) xxxxxxx // split happened here var:value_var_v(efgh) _part2.txt xxxxxxx xxxxx var:value_var_v(efgh) </code></pre> <p>After I do some process on these files (part1 and par2) I again concatenate</p> <p>_part1+_part2=large+file</p> <p>Final large_file after concatenation:</p> <pre><code> xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx xxxxxx var:value_var_v(abcd) xxxxxxx // split happened here var:value_var_v(efgh) **** xxxxxxx xxxxx var:value_var_v(efgh) </code></pre> <p>2nd splitting and concatenate case:</p> <p>If that file is too big say 80KB and has many strings "var:value_var() after a first split @40KB,do subsequent splits where it sees a next string which will be again "var:value_var_v()" and do a split, based on the string else based on the size. Everytime the file pat shoudl contain next available var:value_var_v().</p> <p>Orginal file:</p> <pre><code> xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx - - // assume now split happens here as here assume it is 40kb there are two more strings starting with var:value_var_v, split after var:value_var_v(abcd) and print this string in previous parts eof. Then final part will be ending with var:value_var_v(efgh). keep as it is. xxxxxx xxxxxx xxxxx var:value_var_v(abcd) xxxxxxx xxxxxx xxxxxxx var:value_var_v(efgh) part1.txt xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx - - // split happens here as here assume it is 40kb var:value_var_v(abcd) - //prints next available string which is var:value_var_v(abcd) _part2.txt xxxxxx xxxxxx xxxxx var:value_var_v(abcd) // Here part1 and part2 ends with same string. _part3.txt xxxxxxx xxxxxx xxxxxxx var:value_var_v(efgh) - This is last part and size should be below 40KB </code></pre> <p>process all of these part1,part2,part3 then concatenate to a big file.</p> <p>Final file after concatenating</p> <p>Full fille would look like.</p> <pre><code>xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx // split happened here in the first split assumed 40KB var:value_var_v(abcd) ****** xxxxxx xxxxxx xxxxx var:value_var_v(abcd) ****** xxxxxxx xxxxxx xxxxxxx var:value_var_v(efgh) ****** </code></pre> <p>PS: Once I get processed end of in each part I get **** a unique value and retain it as it during concatenation.</p> |
4,607,943 | 0 | PHP Image content type problem <p>I have a specific problem, and cant get over it.</p> <p>For my latest project I need a simple PHP script that display an image according to its ID sent through URL. Here's the code:</p> <pre><code>header("Content-type: image/jpeg"); $img = $_GET["img"]; echo file_get_contents("http://www.somesite.hr/images/$img"); </code></pre> <p>The problem is that the image doesn't show although the browser recognizes it (i can see it in the page title), instead I get the image URL printed out.</p> <p>It doesn't work neither on a server with remote access allowed nor with one without. Also, nothing is printed or echoed before the header.</p> <p>I wonder if it is a content type error, or something else. Thanks in advance.</p> |
12,524,453 | 0 | Two Page Curl Effect in iPad <p>I am using the Leaves project to move from one pdf page to another it is working fine. Now the page curl is from left to right and from right to left like a note book. Now the effect was to turn a single page but i want to turn the two pages .one page has to display in left side and another page has to display in right side.</p> |
31,897,692 | 0 | Reading byte array from files in Visual Basic <p>I have a code for Visual Basic programming language that reads byte array from files, I use that code:</p> <pre><code>Imports System.IO Imports System.Threading Public Class Form1 Dim thread As New Thread(AddressOf RW_EXE) Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click With OpenFileDialog1 If .ShowDialog() = Windows.Forms.DialogResult.OK Then thread.IsBackground = True Control.CheckForIllegalCrossThreadCalls = False thread.Start() End If End With End Sub Sub RW_EXE() RichTextBox1.Text = "" Dim FS As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read) Dim BS As New BinaryReader(FS) Dim x As Integer = BS.BaseStream.Position Dim y As Integer = BS.BaseStream.Length Dim s As String = "" ProgressBar3.Maximum = y While x < y RichTextBox1.Text &= BS.ReadByte.ToString("X") & " " ProgressBar3.Value = x x += 10 End While RichTextBox1.Text = s FS.Close() BS.Close() thread.Abort() End Sub </code></pre> <p>That code does it's job well, but I have one problem, It's very slow, it takes big time to read array bytes from files with size of 100 KB and from bigger files.</p> <p>Please, help.</p> <p>Thanks for attention.</p> |
36,948,772 | 0 | Rails - Nested Forms will create, but information won't be saved <p>I've been struggling to get my nested form to save the users' inputs. The "outer" form saves the information perfectly. The "inner", or nested, one creates a new object, and passes hidden-field informations, but all other values are "nil".</p> <p>Each order has one or more date_orders, and you should be able to create the first one through this form.</p> <p>My code follows. Please help me spot anything that might be causing that. I've browsed StackOverflow extensively.</p> <p>orders_controller.rb</p> <pre><code>class OrdersController < ApplicationController def new @order = Order.new @order.date_orders.build end def create @order = Order.new(order_params) @order.date_orders.build if @order.save flash[:success] = "Success" redirect_to current_user else render 'new' end end def order_params params.require(:order).permit( :user_id, :description, date_order_attributes: [:id, :order_date, :time_start, :time_end, :order_id]) end end </code></pre> <p>order.rb</p> <pre><code>class Order < ActiveRecord::Base has_many :date_orders, :dependent => :destroy accepts_nested_attributes_for :date_orders end </code></pre> <p>date_order.rb</p> <pre><code>class DateOrder < ActiveRecord::Base belongs_to :order end </code></pre> <p>routes.rb --> date_orders is not mentioned in the routes. Is that a problem?</p> <p>orders/new.html.erb</p> <pre><code><%= form_for(@order, :html => {:multipart => true}) do |f| %> <!-- form_for fields FIELDS --> <%= fields_for :date_orders do |builder| %> <%= builder.hidden_field :order_id, :value => @order.id %> <- THIS WORKS <%= builder.label :date %> <%= builder.date_field :order_date %> <%= builder.label :starting_time %> <%= builder.time_field :time_start %> <%= builder.label :ending_time %> <%= builder.time_field :time_end %> <% end %> <%= f.submit "Request", class: "btn" %> <% end %> </code></pre> <p>EDIT: example of a hash that is created:</p> <pre><code><DateOrder id: 9, order_date: nil, time_start: nil, time_end: nil, order_id: 29, created_at: "2016-04-29 22:43:18", updated_at: "2016-04-29 22:43:18">enter code here` </code></pre> |
29,665,446 | 0 | <p>You can change the hostname value for key <code>IdentityProviderSSOServiceURL</code> in <code>repository/conf/security/authenticators.xml</code> file. </p> |
23,054,234 | 0 | <p>You have to initialize collection before using it like i.e.</p> <pre><code>following=new ArrayList<IntWritable>(); </code></pre> <p>You just declare following and tweets but not initialized it. </p> |
28,557,144 | 0 | Screenrecord causing phone framerate to drop <p>I have a nexus running Lollipop and I tried to use the new options available to screenrecord, </p> <p>I used </p> <pre><code>adb shell screenrecord --o raw-frames --bit-rate 4000000 /sdcard/output.raw </code></pre> <p>And the framerate went for a toss, the device became really sluggish, but If I use the default mp4 format it's actually faster.</p> <p>Technically If I save the trouble of encoding shouldn't device performance be snappier? Am I doing something wrong?</p> |
25,551,516 | 0 | <p>You are using an aggregate function <code>max</code> with out providing a grouping criteria so your table prices will be treated as one group and the results of query will be returned in indeterminate order means it will give you the max value for your criteria but it will not guarantee you to give the relevant date which has the max value so your second query can be written as</p> <pre><code>select ((close-open)/open) as daychange, date from prices order by daychange desc limit 1 ; </code></pre> <p>So the above query will calculate daychange for each row and it will sort the result by daychange values in descending order and limiting to 1 will give you the max value for your criteria and the relevant data value too</p> |
20,683,123 | 0 | <p>Make sure to use these commands in viewdidload [RMMapView class]; mapView.contents.tileSource = [[RMOpenStreetMapSource alloc] init];</p> |
18,074,013 | 0 | <p>The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.</p> <p>If you are supposed to get a JSON Object you can just put:</p> <pre><code>JSONObject myObject = new JSONObject(result); </code></pre> |
17,292,402 | 0 | Form submitting to wrong url in php <p>I am creating a simple registration form in html and submitting it via post method to register.php which is under a directory named controller. When I submit the form, it redirects to wrong URL.<br/> <strong>This is the form:</strong><br/></p> <pre><code><form action="controller/register.php" method="post" enctype="multipart/form-data" id="pre-registration-form"> <fieldset> <legend><span>Type of Entry</span></legend> <table id="rally-type"> <tr> <td>Sponsored</td> <td>Non-sponsored</td> </tr> <tr> <td><input type="radio" id="xtreme" name="entry-type" value="xtreme" /></td> <td><input type="radio" id="ndure" name="entry-type" value="ndure" /></td> </tr> </table> </fieldset> <fieldset> <legend> <span>Vehicle Details</span> </legend> <table> <tr> <td>Category</td> <td><select name="vehicle-category" id="vehicle-category-list"> <option value="0">Select</option> <option value="2whlr">2 Wheeler</option> <option value="2whlr">4 Wheeler</option> <option value="2whlr">4 Wheel Drive</option> </select></td> <td>Make</td> <td> <select name="vehicle-make"> <option value="0">....</option> <option value="1">....</option> . . . </select> </td> </tr> <tr> <td>Model</td> <td><input type="text" name="make-model" /></td> <td>Year</td> <td><input type="text" name="make-year" /></td> </tr> </table> </fieldset> . . . . <input type="submit" name="submit" value="Submit" /> </code></pre> <p></p> <p>When I try to submit the form, it redirects to <code>controller/index.php</code> rather than <code>controller/register.php</code><br/> When I rename <code>register.php</code> file to <code>index.php</code> then the firefox gives the following error: <br/><br/></p> <blockquote> <p><strong>The page isn't redirecting properly</strong><br/> Firefox has detected that the server is redirecting the request for this address in a way that will never complete.<br/><br/> This problem can sometimes be caused by disabling or refusing to accept cookies.</p> </blockquote> <p><br/><br/> I have tried this on wamp as well as lamp server and both produces the same error. What might be the root of this problem? </p> |
34,817,388 | 0 | Rake stats not working <p>I'm trying to fetch some information about my project with rake stats but I'm getting the following </p> <pre><code>rake aborted! ArgumentError: invalid byte sequence in UTF-8 </code></pre> <p>When I run the command bundle exec rake stats with --trace, I get the following:</p> <pre><code>ArgumentError: invalid byte sequence in UTF-8 /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:50:in `block in calculate_directory_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:32:in `foreach' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:32:in `calculate_directory_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:34:in `block in calculate_directory_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:32:in `foreach' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:32:in `calculate_directory_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:26:in `block in calculate_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:26:in `map' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:26:in `calculate_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:7:in `initialize' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/tasks/statistics.rake:15:in `new' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/tasks/statistics.rake:15:in `block in <top (required)>' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `eval' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `<main>' </code></pre> <p>What can I do to solve this ?</p> |
5,075,586 | 0 | <p>You could use <code>break;</code> but if you do you can't check return values (use <code>return;</code> or <code>return $bool;</code> for that).</p> <p>I think a construction like this would do:</p> <pre><code>.submit(function () { if (verifyInput()) { // continue } else { // show user there is something wrong } }); </code></pre> <p><code>verifyInput()</code> in this case would return a boolean, of course, representing wether or not the form was properly filled.</p> |
35,083,537 | 0 | <p>you can use <code>df.apply</code> which will apply each column with provided function, in this case counting missing value. This is what it looks like,</p> <p><code>df.apply(lambda x: x.isnull().value_counts())</code></p> |
31,859,432 | 0 | allow people to only alter certain values in an input JavaScipt <p>I have the following code</p> <pre><code><input id="startDate "type="text" name="courseDate" value="MM/YYYY" /> </code></pre> <p>I was wondering how I could use JavaScript to ensure that a user can only edit the "MM" and "YYYY" in the textbox.</p> <p>Thanks Y</p> |
33,423,484 | 0 | <p>CoreLocation offers a geocoder service (<a href="https://developer.apple.com/library/watchos/documentation/CoreLocation/Reference/CLGeocoder_class/index.html" rel="nofollow" title="CLGeocoder, Apple Documentation">CLGeocoder, Apple documentation)</a> that allows for translation back and forth between lat/lon coordinates and street addresses. However, this service does not provide business/resident names, so you will have to use a third-party service to get that information.</p> |
15,528,594 | 0 | My View Controller gets deallocated when the app goes to the background <p>My View Controller class gets deallocated when the app goes to the background. I'm using ARC.</p> <p>I have a UIViewController that subscribes to a notifications when the app becomes active and executes a method. But once the app is about 30 secs in the background and then resumes, the app crashes with "message sent to deallocated instance". </p> <p>Enabling Zombie objects shows that the View Controller itself is the Zombie.</p> <p>Thank you!</p> <p><b>Instantiation of my view controller (in AppDelegate):</b></p> <pre><code>UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; MyViewController *myViewController = [storyBoard instantiateViewControllerWithIdentifier:@"MyViewController"]; </code></pre> <p><b>The foreground notification in AppDelegate:</b></p> <pre><code>- (void)applicationDidBecomeActive:(UIApplication *)application { [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationForegrounded object:self]; } </code></pre> <p><b>The foreground notification in the view controller:</b></p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resumeForeground) name:kNotificationForegrounded object:nil]; } </code></pre> <p><b>I tried creating a strong reference in the AppDelegate, but the view controller still gets deallocated:</b></p> <pre><code>@property (strong, nonatomic) MyViewController *myViewController; </code></pre> <p><b>I tried adding the view controller to an array and have a strong reference to the array in the AppDelegae, but still I get the same results:</b></p> <pre><code>@property (strong, nonatomic) NSMutableArray *viewControllers; //... UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; MyViewController *myViewController = [storyBoard instantiateViewControllerWithIdentifier:@"MyViewController"]; self.viewControllers = [[NSMutableArray alloc] init]; [self.viewControllers addObject:myViewController]; </code></pre> |
10,142,446 | 0 | Using private frameworks for QT in xcode 4.3 <p>The Mac QT Installer puts its shared libraries under <code>/Library/Frameworks/QtXXX.Framework</code>.<br> I'm building a QT application using a qmake-generated xcode project. I'd like to add these frameworks as private framewords inside my app bundle for easy deployment.</p> <p>I've tried various options for doing this but I don't seem to be able to make it work. What I did - </p> <ul> <li>change the Qt framework files in <code>/Library/Frameworks/</code> using <code>install_name_tool</code> as described <a href="http://stackoverflow.com/questions/1621451/bundle-framework-with-application-in-xcode">here</a></li> <li>copy the these framework bundles manually to inside the app bundle</li> <li>recompiling the bundle.</li> </ul> <p>When I change the name of the original framework so it would appear that it's not there, the app crashes and says that it doesn't find the needed framework. What am I doing wrong?</p> <p>Using xcode 4.3 on OSX 10.7.3</p> |
38,130,800 | 0 | <p>I just created a blog post that hopefully answers your question about projecting the points onto a solid.</p> <p><a href="http://modthemachine.typepad.com/my_weblog/2016/06/projecting-points-onto-a-solid.html" rel="nofollow">http://modthemachine.typepad.com/my_weblog/2016/06/projecting-points-onto-a-solid.html</a></p> <p>Regarding your second question about getting the solid as a point cloud; it is possible. You'll want to look at the CalculateFacets, CalculateFacetsWithOptions, and GetExistingFacets methods. These all do the same thing in that they return a set of points that represent a triangle approximation of the solid.</p> |
16,656,904 | 0 | inserting multiple rows in sqlite using implode <p>I have tried to insert multiple rows but got empty rows in database and other errors. So,tried to use implode (as a better alternative?) but must be doing something wrong here.</p> <pre><code>$sql = array(); foreach($_POST as $key => $value ) { $sql[] = '("'.sqlite_escape_string($key['cust_name']).'", '.$key['address'].')'; } $stmt = $db->prepare('INSERT INTO customers VALUES (cust_name, address) '.implode(','. $sql)); $stmt->execute($sql); </code></pre> |
14,318,552 | 0 | Need to redirect 404 to the home page. <p>I only have one 404 left and have no idea how to fix it. So I need to redirect that single page to the home page. </p> <p>I need <a href="http://www.name.co.uk/blog/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" rel="nofollow">http://www.name.co.uk/blog/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif</a> to redirect to the homepage within the .htaccess file.</p> <p>Many thanks </p> |
38,486,562 | 0 | <p>I had similar issues recently, also with a site hosted on Azure though I don't think that was the cause. Found out the CORS error was somehow being triggered by SQL timeout exceptions because our stored procedures were processing huge amounts of data and it was taking too long. Sped up some of the procs and most of the CORS errors stopped happening, the same needs to be done for the other procs and then they will all work again.</p> <p>Looks like you were having a different issue, but if anyone is having CORS errors that show up a few minutes after a request is made this would be worth looking into.</p> |
23,557,718 | 0 | <pre><code>SELECT AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, BillLimit, Mode, PNotes, gtab82.memno FROM VCustomer AS v1 INNER JOIN gtab82 ON gtab82.memacid = v1.AcId WHERE (AcGrCode = '204' OR CreDebt = 'True') AND Masked = 'false' ORDER BY AcName </code></pre> <p>You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for <code>VCustomer</code> but only use it in the <code>ON</code> clause for uncertain reasons. You may want to review that aspect of your code.</p> |
12,476,557 | 0 | How do I get data from requested server page? <p>I got two php pages: <strong>client.php</strong> and <strong>server.php</strong></p> <p><strong>server.php</strong> is on my web server and what it does is open my amazon product page and get price data and serialize it and return it to <strong>client.php</strong>.</p> <p>Now the problem I have is that <strong>server.php</strong> is getting the data, but when I return it and do <code>echo</code> after using <code>unserialize()</code>, it shows nothing. But if I do <code>echo</code> in <strong>server.php</strong>, it shows me all the data. </p> <p>Why is this happening? Can anyone help me please? </p> <p>This the code I have used:</p> <p><strong>client.php</strong></p> <pre><code>$url = "http://www.myurl.com/iec/Server.php?asin=$asin&platform=$platform_variant"; $azn_data = file_get_contents($url); $azn_data = unserialize($azn_data); echo "\nReturned Data = $azn_data\n"; </code></pre> <p><strong>server.php</strong></p> <pre><code>if(isset($_GET["asin"])) { $asin = $_GET["asin"]; $platform = $_GET["platform"]; echo "\nASIN = $asin\nPlatform = $platform"; //Below line gets all serialize price data for my product $serialized_data = amazon_data_chooser($asin, $platform); return($serialized_data); } else { echo "Warning: No Data Found!"; } </code></pre> |
4,335,306 | 0 | <p>You can use a <code>TemplateField</code>, and, inside it something like this:</p> <pre><code><asp:Image runat="server" id="myImg" ImageUrl='<%# GetImage(DataBinder.Eval(Container.DataItem, "b_attach")) >%' visible='<%# null != DataBinder.Eval(Container.DataItem, "b_attach") %> /> </code></pre> |
2,182,911 | 0 | <p><strong>It's easy to know what to charge your customer.</strong> This is alway the biggest problems for us, because we don't know the scope of the project we can't give the customer a fixed price, and most customers demands a fixed price. </p> |
24,636,491 | 0 | <style> not working as intended for <table> on Outlook 2007 <h1> Problematic </h1> <p>< style> tags don't seem to work properly in an Email sent to Outlook 2007.</p> <h1> Context </h1> <p>I use an asp.net server to send an Email with a table. This table has the inputs that the client entered.</p> <h2> What it should do </h2> <p><img src="https://i.stack.imgur.com/JBcBp.jpg" alt="Table (From JSFiddle)"><br> <a href="http://jsfiddle.net/6tca6/" rel="nofollow noreferrer">PrintScreened from JSFiddle</a></p> <h2> What it does </h2> <p><img src="https://i.stack.imgur.com/sHOJY.jpg" alt="Table (From Outlook 2007)"><br> PrintScreened from Outlook 2007 message.</p> <h1> Stipulations</h1> <p>The VB code doesn't matter (as it sends the Email properly), the problem comes from the <code>mailMessage.body</code> text.</p> <p>Here is the code for it :</p> <pre><code>Dim table As String Dim mailMessage As New MailMessage() 'There are two multiline textboxes which I want to create a table from table = "<table><thead><tr><th>Length</th><th>Force</th></tr></thead><tbody>" For i = 0 To UBound(Split(length.Text, Environment.NewLine)) table += "<tr><td>" & Split(length.Text, Environment.NewLine)(i) & "</td>" table += "<td>" & Split(force.Text, Environment.NewLine)(i) & "</td></tr>" Next table += "</tbody></table>" mailMessage.Body = table & _ "<style>" & vbCrLf & _ "table {display: inline-table; border:3px solid; border-collapse:collapse;}" & vbCrLf & _ "thead {border:2px solid;}" & vbCrLf & _ "tbody {border:1px solid;}" & vbCrLf & _ "th {border:1px solid; padding:3px;}" & vbCrLf & _ "td {font-size:90%; border:1px solid; padding:3px; text-align:left;}" & vbCrLf & _ "</style>" </code></pre> <p>This <em>should</em> translate into <a href="http://jsfiddle.net/6tca6/" rel="nofollow noreferrer"><em>this</em></a>, but something goes wrong in the process.</p> <p>From <a href="https://www.campaignmonitor.com/css/" rel="nofollow noreferrer">https://www.campaignmonitor.com/css/</a>, all the <code>style</code> commands I used should work..</p> <h1> Question </h1> <p>What have I done wrong?</p> <h2> Update 1 </h2> <p>I tried to put the <code><style></code> tags in front of the table, it did this :</p> <pre class="lang-asp prettyprint-override"><code><style>[...]</style> <table>[...]</table> </code></pre> <p><img src="https://i.stack.imgur.com/sG0Nw.jpg" alt="Style in front"></p> <p>It seems like the last CSS command overwrites all of the previous ones (table 3px border gets overwritten by <code>td</code>...)</p> <p>I tried <em>JRulle</em> proposition, it gave this :</p> <p><img src="https://i.stack.imgur.com/92Qw9.jpg" alt="JRulle's proposition"></p> <p>Both of those will work in case no solution is found, but I would really want to have the table borders bigger than the inner borders for ... style. Is that possible?</p> <h2> Update 2 </h2> <p>Following <em>JRulle's</em> second proposition :</p> <p><strong>Without collapse</strong></p> <p><img src="https://i.stack.imgur.com/uE1ki.jpg" alt="W/o Collapse"></p> <p>This is an expected result, as my first row are <code><th></code>, so the style should not draw borders for them.</p> <p><strong>With Collapse</strong></p> <p><img src="https://i.stack.imgur.com/ViPfj.jpg" alt="enter image description here"></p> <p>This is now really weird, it seems the collate function actually put the inner borders OVER the outside borders...</p> |
35,693,478 | 1 | Create data by combining query results in Django <p>I have a 1-n relation in my models, e.g., 1 classroom - n students. </p> <pre><code>Classroom 1 - Joe Classroom 1 - Tim Classroom 1 - Julia Classroom 2 - Bob Classroom 2 - Alice </code></pre> <p>In my view I want to show a row for each classroom and a comma separated list for the students:</p> <pre><code>Classroom1 | Joe, Tim, Julia Classroom2 | Bob, Alice </code></pre> <p>Right now, I find the records for each classroom and create the list of students and combine that to create a dictionary.</p> <p>Is there a more efficient way to create this data? Can I save the list of students with each Classroom?</p> |
26,934,580 | 0 | <p>Try this.....</p> <pre><code>SELECT username ,count(CASE WHEN tblCall.started_at BETWEEN '2014-11-10 00:00:00' AND '2014-11-10 23:00:00' THEN tblCall.call_id ELSE NULL END) AS [10-11-2014] ,count(CASE WHEN tblCall.started_at BETWEEN '2014-11-11 00:00:00' AND '2014-11-11 23:00:00' THEN tblCall.call_id ELSE NULL END) AS [11-11-2014] ,count(CASE WHEN tblCall.started_at BETWEEN '2014-11-12 00:00:00' AND '2014-11-12 23:00:00' THEN tblCall.call_id ELSE NULL END) AS [12-11-2014] FROM tblUser INNER JOIN tblCall ON tblCall.from_user_id = tblUser.[user_id] WHERE tblUser.can_manage_accounts = '1' AND tblUser.telephone_ext != '' AND tblUser.blocked = '0' GROUP BY tblUser.username </code></pre> <h2>Dynamic Sql</h2> <pre><code>CREATE TABLE TEST_TABLE(UserName VARCHAR(100), started_at DATETIME) GO INSERT INTO TEST_TABLE VALUES ('Mark' , '2014-11-13 23:59:59.997'),('Jane' , '2014-11-13 23:59:59.997'),('Sam' , '2014-11-13 23:59:59.997'), ('Mark' , '2014-11-13 23:59:59.997'),('Jane' , '2014-11-13 23:59:59.997'),('Sam' , '2014-11-13 23:59:59.997'), ('Holly' ,'2014-11-12 23:59:59.997'),('Sally' ,'2014-11-12 23:59:59.997'),('Mandy' ,'2014-11-12 23:59:59.997'), ('Holly' ,'2014-11-12 23:59:59.997'),('Sally' ,'2014-11-12 23:59:59.997'),('John' ,'2014-11-11 23:59:59.997'), ('James' ,'2014-11-11 23:59:59.997'),('John' ,'2014-11-11 23:59:59.997'),('James' ,'2014-11-11 23:59:59.997'), ('Josh' ,'2014-11-10 23:59:59.997'),('Jamie' ,'2014-11-10 23:59:59.997') GO </code></pre> <h2>Query</h2> <pre><code>DECLARE @Range_Start DATE = '2014-11-11' DECLARE @Range_End DATE = '2014-11-13' DECLARE @Date_Columns NVARCHAR(MAX); DECLARE @Sql NVARCHAR(MAX); SELECT @Date_Columns = STUFF(( SELECT DISTINCT ', ' + QUOTENAME(CONVERT(VARCHAR(10), started_at, 120)) FROM TEST_TABLE WHERE CAST(started_at AS DATE) >= @Range_Start AND CAST(started_at AS DATE) <= @Range_End FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,'') SET @Sql = N' SELECT * FROM ( SELECT UserName, COUNT(*) AS Total, CONVERT(VARCHAR(10), started_at, 120) AS started_at FROM TEST_TABLE WHERE CAST(started_at AS DATE) >= @Range_Start AND CAST(started_at AS DATE) <= @Range_End GROUP BY UserName, CONVERT(VARCHAR(10), started_at, 120) ) t PIVOT ( SUM(Total) FOR started_at IN (' + @Date_Columns + ') )p ' Execute sp_executesql @Sql ,N'@Range_Start DATE, @Range_End DATE' ,@Range_Start ,@Range_End </code></pre> <h2>Result</h2> <pre><code>╔══════════╦════════════╦════════════╦════════════╗ ║ UserName ║ 2014-11-11 ║ 2014-11-12 ║ 2014-11-13 ║ ╠══════════╬════════════╬════════════╬════════════╣ ║ Holly ║ NULL ║ 2 ║ NULL ║ ║ James ║ 2 ║ NULL ║ NULL ║ ║ Jane ║ NULL ║ NULL ║ 2 ║ ║ John ║ 2 ║ NULL ║ NULL ║ ║ Mandy ║ NULL ║ 1 ║ NULL ║ ║ Mark ║ NULL ║ NULL ║ 2 ║ ║ Sally ║ NULL ║ 2 ║ NULL ║ ║ Sam ║ NULL ║ NULL ║ 2 ║ ╚══════════╩════════════╩════════════╩════════════╝ </code></pre> |
30,988,049 | 0 | mustache populate JSON object error <p>I have code below. I need to populate a JSON object using mustache. Unfortunately, it shows nothing to me. </p> <pre><code> <script type="text/javascript"> var data = "[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]"; var template = $("#template").html(); Mustache.parse(template); var rendered = Mustache.render(template, data); $('#PatrList').html(rendered); </script> <body> <div id="PatrList"></div> <script id="template" type="x-tmpl-mustache"> {{ #. }} <div> PR_ID: <h2> {{PR_ID}} </h2> ---- P_ID: <h2> {{P_ID}} </h2> </div> {{ /. }} </script> </body> </code></pre> |
36,964,253 | 0 | Should Core Data Stack inherit from NSObject and why? <p>Recently it is practice to move the core data stack implementation from the app delegate to a different class. In most implementations I see that the core data stack inherits from NSObject, even in Apple's documentation. </p> <ol> <li>Is there a reason for that? It seems to work without it.</li> <li>Why is Apple's init method not calling super.init() isn't it a must have?</li> </ol> <p></p> <pre><code>import UIKit import CoreData class DataController: NSObject { var managedObjectContext: NSManagedObjectContext init() { // This resource is the same name as your xcdatamodeld contained in your project. guard let modelURL = NSBundle.mainBundle().URLForResource("DataModel", withExtension:"momd") else { fatalError("Error loading model from bundle") } // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = psc dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let docURL = urls[urls.endIndex-1] /* The directory the application uses to store the Core Data store file. This code uses a file named "DataModel.sqlite" in the application's documents directory. */ let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite") do { try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil) } catch { fatalError("Error migrating store: \(error)") } } } } </code></pre> <p><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1" rel="nofollow">Initializing the Core Data Stack</a></p> |
30,083,621 | 0 | <p>Your <code>ClickListener</code> is an inner non-static class the coupling of this 'has-a' is no different than if your class <code>Activity</code> implemented <code>View.OnClickListener</code>. This is because your inner <code>ClickListener</code> requires an instance of <code>ActivityMain</code> and really can't be reused. I would argue that you're over engineering and aren't actually gaining anything. </p> <p>EDIT: To answer your question I like to have anonymous <code>View.OnClickListener</code> for each widget. I think this creates the best separation of logic. I also have methods like <code>setupHelloWorldTextView(TextView helloWorldTextView);</code> where I put all my logic related to that widget.</p> |
15,598,057 | 0 | <p>OK I found it,</p> <p>The error was the <strong>ColumnSeries</strong> was missing the <strong>Title</strong> attribute, like this:</p> <pre><code><charting:Chart Name="columnChart" Grid.Row="1" Grid.Column="1" Width="400" Height="400"> <charting:Chart.Series> <charting:ColumnSeries Title="Chart Title" ItemsSource="{Binding items}" IndependentValueBinding="{Binding Name}" DependentValueBinding="{Binding Value}" IsSelectionEnabled="True"> </charting:ColumnSeries> </charting:Chart.Series> </charting:Chart> </code></pre> <p>It seems that the <strong>Title</strong> attribute is mandatory.</p> |
1,518,182 | 0 | <p><strong>#ifdef</strong> is short for <strong>#if defined</strong> and I think you don't need parenthesis on neither, so basically they are the same. </p> <p>Coming from Turbo C, I'm used to looking at <strong>#ifdef</strong> rather than <strong>#if defined</strong></p> |
40,639,337 | 0 | Parse Platform - Retrieve relations in object <p>Okay, so I am really quite familiar with Parse and have used most features in daily development. However, now I need to work with some many-to-many relationships and can't seem to get it to work right. I've tried reading several posts on Stack... but no luck.</p> <p>Any help would be appreciated:</p> <p>1) 'Projects' class = (main grouping class and project details) a) 'projectTasks' is setup as a relation column and points to the Tasks class.</p> <p>2) 'Tasks' class = (tasks submitted by user and grouped in projects)</p> <p>3) I want to be able to Query for certain projects, and get the relation data at same time.</p> <pre><code>test: function(){ console.warn("Running relations test....") var deferred = $q.defer() var Projects = Parse.Object.extend("Projects"); var query = new Parse.Query(Projects) query.equalTo("objectId",Parse.User.current().id) query.include("projectTasks") query.find({ success: function(res){ console.log(res) deferred.resolve(res) }, error: function(e,r){ console.log(e,r) deferred.reject(e) } }) return deferred.promise }, </code></pre> <p>The response I get never returns the actual data from the relation field... just another promise or whatever it is.</p> <p><a href="https://i.stack.imgur.com/IeGI5.png" rel="nofollow noreferrer">screen shot of response</a></p> <p>Maybe I'm just going about this all wrong. Any help would be appreciated. I want to store a project, store tasks, and be able to associate tasks to a project and quickly retrieve all the info per project.</p> |
33,296,297 | 0 | <p>I think that what you are looking for are <a href="http://guides.emberjs.com/v2.1.0/templates/writing-helpers/#toc_class-based-helpers" rel="nofollow">class-based helpers</a>. You might have trouble with the resetting of the value, so keep an eye open for alternative solutions.</p> |
20,399,116 | 0 | Fastest way to retreive data from database <p>I am working on a ASP.NET project with C# and Sql Server 2008.</p> <p>I have three tables:</p> <p><img src="https://i.stack.imgur.com/2bGzV.png" alt="Users"> <img src="https://i.stack.imgur.com/4OXWK.png" alt="DataFields"> <img src="https://i.stack.imgur.com/tH8nI.png" alt="DataField Values"></p> <p>Each user has a specific value for each data field, and this value is stored in the DataFieldsValues.</p> <p>Now I want to display a report that looks like this:</p> <p><img src="https://i.stack.imgur.com/e76bV.png" alt="enter image description here"></p> <p>I have created the objects <code>User</code>, and <code>DataField</code>. In the DataField object, there is the Method <code>string GetValue(User user)</code>, in which I get the value of a field for a certain user.</p> <p>Then I have the list of Users <code>List<User> users</code> and the list of DataFields <code>List<DataField> fields</code> and I do the following:</p> <pre><code>string html = string.Empty; html += "<table>"; html += "<tr><th>Username</th>"; foreach (DataField f in fields) { html += "<th>" + f.Name + "</th>"; } html += "</tr>" foreach (User u in users) { html += "<tr><td>" + u.Username + "</td>" foreach (DataField f in fields) { html += "<td>" + f.GetValue(u) + "</td>"; } html += "</tr>" } Response.Write(html); </code></pre> <p>This works fine, but it is <strong>extremely</strong> slow, and I am talking about 20 users and 10 data fields. Is there any better way in terms of performance to achieve this? </p> <p>EDIT: For each parameter inside the classes, I retrieve the value using the following method:</p> <pre><code>public static string GetDataFromDB(string query) { string return_value = string.Empty; SqlConnection sql_conn; sql_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XXXX"].ToString()); sql_conn.Open(); SqlCommand com = new SqlCommand(query, sql_conn); //if (com.ExecuteScalar() != null) try { return_value = com.ExecuteScalar().ToString(); } catch (Exception x) { } sql_conn.Close(); return return_value; } </code></pre> <p>For instance:</p> <pre><code>public User(int _Id) { this.Id = _Id this.Username = DBAccess.GetDataFromDB("select Username from Users where Id=" + this.Id) //... } </code></pre> |
37,907,423 | 1 | Pickle Trained Classifier Only Return 1 Predicted Label to All Test Data <p>I'm having trouble about pickle trained classifier. I pickled a classifier that I trained using 8000 training tweets. each tweet has been labeled with 1 out of 4 labels (Health, Music, Sport and Technology) when I tried using the pickle trained classifier in new tweets for testing, it return only 1 out of 4 labels to all of new tweets. new tweets are tweets I stream directly from Twitter using Tweepy.</p> <p>here's the code I use to pickle the trained classifier using 8000 tweets for training that stored in database:</p> <pre><code>#set precision for numpy np.set_printoptions(precision=1) #get data from MySQL table using pandas engine = create_engine('mysql+mysqlconnector://root:root@localhost:3306/thesisdb?charset=utf8mb4') ttweets = pd.read_sql_query('SELECT label_id, tweet FROM training_tweets', engine) #text preprocessing (remove HTML markup, remove punctuation, tokenizing, remove stop words and stemming) using NLTK def Preprocessing(pptweets): pptweets = pptweets.lower() removeurl = re.sub(r'https:.*$',":", pptweets) removepunc = removeurl.replace("_", " ") tokenizer = RegexpTokenizer(r'\w+') tokenizetweets = tokenizer.tokenize(removepunc) removesw = [w for w in tokenizetweets if not w in stopwords.words('english')] stemmer = SnowballStemmer("english") stemmedtweets = [stemmer.stem(tokenizetweets) for tokenizetweets in removesw] return " ".join(stemmedtweets) #initialize an empty variable to hold the preprocessed tweets cleantweets = [] #loop over each tweet for i in range(0, len(ttweets["tweet"])): cleantweets.append(Preprocessing(ttweets["tweet"][i])) #text feature extraction using Bag of Words vectorizer = CountVectorizer(analyzer="word", tokenizer=None, preprocessor=None, stop_words=None, max_features=5000) #use fit_transform() to fit the model and learn the vocabulary as well as transform the training data into feature vectors traintweetsfeatures = vectorizer.fit_transform(cleantweets) #convert the result to array using Numpy traintweetsfeatures = traintweetsfeatures.toarray() #create a Logistic Regression classifier variable and train it using the training tweets clfr = LogisticRegression() x_train, y_train = traintweetsfeatures, ttweets["label_id"] clfr.fit(x_train, y_train) #save trained classifier in pkl file if os.path.exists(dest): os.remove(classifiername) os.remove(vectorizername) pickle.dump(clfr, open(os.path.join(dest, 'clfr.pickle'), 'wb'), protocol=2) pickle.dump(vectorizer, open(os.path.join(dest, 'vectorizer.pickle'), 'wb'), protocol=2) else: os.makedirs(dest) pickle.dump(clfr, open(os.path.join(dest, 'clfr.pickle'), 'wb'), protocol=2) pickle.dump(vectorizer, open(os.path.join(dest, 'vectorizer.pickle'), 'wb'), protocol=2) </code></pre> <p>and below is the code to use pickle trained classifier for predicting label of new tweets:</p> <pre><code>if request.method == 'POST': auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) getlabelid = Label.query.filter_by(label_id=request.form['label']).first() getlabelname = getlabelid.label_name number = int(request.form['number']) def Preprocessing(pptweets): pptweets = pptweets.lower() removeurl = re.sub(r'https:.*$',":", pptweets) removepunc = removeurl.replace("_", " ") tokenizer = RegexpTokenizer(r'\w+') tokenizetweets = tokenizer.tokenize(removepunc) removesw = [w for w in tokenizetweets if not w in stopwords.words('english')] stemmer = SnowballStemmer("english") stemmedtweets = [stemmer.stem(tokenizetweets) for tokenizetweets in removesw] return " ".join(stemmedtweets) class listener(StreamListener): def __init__(self, api=None): self.api = api or API() self.n = 0 self.m = number def on_data(self, data): all_data = json.loads(data) tweet = all_data["text"] username = all_data["user"]["screen_name"] getlabelid = Label.query.filter_by(label_id=request.form['label']).first() getlabelname = getlabelid.label_name #initialize an empty variable to hold the preprocessed tweets cleantesttweet = Preprocessing(tweet) #load trained classifier & bag of words dest = os.path.join('classifier', 'pkl_objects') clfr = pickle.load(open(os.path.join(dest, 'clfr.pickle'), 'rb')) vectorizer = pickle.load(open(os.path.join(dest, 'vectorizer.pickle'), 'rb')) #predict test tweet label testtweetfeatures = vectorizer.transform(cleantesttweet) result = clfr.predict(testtweetfeatures) #result = 1 ttweets = TestingTweets(label_id=result, tweet_username=username, tweet=tweet) try: db.session.add(ttweets) db.session.commit() # Increment the counter here, as we've truly successfully # stored a tweet. self.n += 1 except IntegrityError: db.session.rollback() except tweepy.error.TweepError: return False # Don't stop the stream, just ignore the duplicate. # print("Duplicate entry detected!") if self.n >= self.m: #print("Successfully stored", self.m, "tweets into database") # Cross the... stop the stream. return False else: # Keep the stream going. return True def on_error(self, status): print(status) auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=[getlabelname], languages=["en"]) label = Label.query.all() tetweet = TestingTweets.query.order_by(TestingTweets.tweet_id.desc()) return render_template('testtweets.html', labels=label, tetweets=tetweet) </code></pre> <p>does anyone can help me solve this problem?</p> |
19,468,850 | 0 | <p>You can accomplish the feat with limma, also. See the example below.</p> <p>The idea is basically exactly the same as in the code you have posted, but it has not been wrapped into a function (and is therefore possibly slightly easier to debug). </p> <p>Do you get it to work with the code below? If not, please post the possible error messages and warnings that you get.</p> <pre><code># Load the library library(limma) # Generate example data set1<-letters[1:5] set2<-letters[4:8] set3<-letters[5:9] # What are the possible letters in the universe? universe <- sort(unique(c(set1, set2, set3))) # Generate a matrix, with the sets in columns and possible letters on rows Counts <- matrix(0, nrow=length(universe), ncol=3) # Populate the said matrix for (i in 1:length(universe)) { Counts[i,1] <- universe[i] %in% set1 Counts[i,2] <- universe[i] %in% set2 Counts[i,3] <- universe[i] %in% set3 } # Name the columns with the sample names colnames(Counts) <- c("set1","set2","set3") # Specify the colors for the sets cols<-c("Red", "Green", "Blue") vennDiagram(vennCounts(Counts), circle.col=cols) </code></pre> <p>The code should give a plot similar to:</p> <p><img src="https://i.stack.imgur.com/lu3rb.jpg" alt="enter image description here"></p> |
15,954,472 | 0 | <p>You have the correct number of dashes, you just aren't printing out the number correctly. Let's examine why that is:</p> <p>Which loop prints out the numbers? The 2nd nested for loop.</p> <p>What does it do? It prints out <code>j</code> where <code>j</code> ranges from <code>1</code> to <code>9</code> and <code>j</code> is incremented by 2 each iteration of the loop. In other words, <code>1, 3, 5, 7, 9</code>, which is confirmed in your output</p> <p>What do you want it to do? Well let's look at the desired output. You want <code>1</code> to be printed <em>once</em> on the <s><em>first</em></s> first line. You want <code>3</code> to be printed <em>three</em> times on the <s><em>third</em></s> next line. You want <code>5</code> to be printed <em>five</em> times on the <s><em>fifth</em></s> next line after that. And so on.</p> <p>Do you notice a pattern? You want that loop we mentioned above to print the <em>same</em> number (<code>1</code>, <code>3</code>, <code>5</code>, ... <code>i</code>) as the number of times (<code>1</code>, <code>3</code>, <code>5</code>, ... <code>i</code>).</p> <p><strong>edit</strong> Whooops I actually misread the output. My answer is still very similar to before, but I lied about which line you are printing what. It's still <code>3</code> <em>three</em> times, <code>5</code> <em>five</em> times but different lines. The easiest way to jump from my solution to the actual one is to notice that on the even lines... you do nothing. You could arguably even write your solution this way.</p> <p>Another tip is that you should just focus on getting the numbers on each line right and the dashes separately. It's likely that you'll screw up the number of dashes when you fix the numbers on each line, but then you'll realize how to fix the dashes easily.</p> |
882,394 | 0 | <p>You <em>might</em> be able to load Flash 8 into Flash 10 but I would be very surprised if the reverse is true.</p> |
12,427,866 | 0 | ASP.NET MVC 3, Ajax.BeginForm, OnBegin and form validation <p>I am using Ajax.BeginForm and wish to pass in parameters to the function called with OnBegin. The following are two code snippets.</p> <pre><code>new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "DataEntrySummary", OnBegin = "ValidateForm(11,55)" } function ValidateForm(minAge, maxAge) {return false;} </code></pre> <p>The parameters are passed in correctly to the ValidateForm function but the function always returns true. </p> <p>If I take the parameters out and use</p> <pre><code>OnBegin = "ValidateForm()" function ValidateForm() {return false;} </code></pre> <p>It works perfectly and returns false. Am I missing something or are parameters not allowed here or ...</p> <p>Puzzled of Oxford - thanks in advance.</p> <p>PS - I cannot use C# Attributes and Unobtrusive validation for very good reasons (these <em>are</em> code snippets).</p> |
1,757,599 | 0 | <p>Are you already doing logging, and would you simply be adding the IP address in to your existing log entries? If so, this wouldn't make a major impact. It's resolving IP addresses to names that would make a performance impact.</p> |
4,088,082 | 0 | Store input from a text field in a PHP variable <p>Store the users input from a text field in a variable. Any ways to do this?</p> |
27,103,390 | 0 | Entity Framework adds Default value by itself <p>i have the following table definition (trimmed):</p> <pre><code>CREATE TABLE `mt_user` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, `dtUpdated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `idUpdatedBy` int(10) unsigned NOT NULL, `dtCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `idCreatedBy` int(10) unsigned NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; </code></pre> <p>As you can see, no default value was assigned to <code>idUpdatedBy</code> and <code>idCreatedBy</code>.</p> <p>When trying to insert a row from workbench, it fails (since i do not provide <code>idCreatedBy</code> or <code>idUpdatedBy</code>). Which is the correct behaviour.</p> <p>On the other hand, if i use a simple form to insert using Entity Framework, the fields are populated with a <code>0</code> value, even though i have not defined a default value (neither in entity framework).</p> <p>i was expecting Entity Framework to fail the insert and throw an error about <code>idUpdatedBy</code>/<code>idCreatedBy</code> not having a value.</p> <p>Could someone explain this behaviour and how to fix it?</p> |
36,041,070 | 0 | Weight search in boolean mode with union mysql <p>I am using this query to search across multiple tables, which is working however I want to weigh matches to the column "title" higher than matches to the column description.</p> <pre><code>SELECT 'about' AS a.about,title,null article ,null description FROM about a WHERE ( MATCH(a.about) AGAINST ('\"$search\"' IN BOOLEAN MODE) ) UNION SELECT 'articles' AS null, b.title,b.article,b.description from articles b WHERE ( MATCH(b.title,b.article,b.description) AGAINST ('\"$search\"' IN BOOLEAN MODE) ) </code></pre> <p>I have tried adding "AS relevance1" to the end of the match as below but it returns no results:</p> <pre><code>SELECT 'about' AS a.about,title,null article ,null description FROM about a WHERE ( MATCH(a.about) AGAINST ('\"$search\"' IN BOOLEAN MODE) ) UNION SELECT 'articles' AS null, b.title,b.article,b.description from articles b WHERE ( MATCH(b.title,b.article,b.description) AGAINST ('\"$search\"' IN BOOLEAN MODE) AS relevence_1, MATCH(b.title,b.article,b.description) AGAINST ('\"$search\"' IN BOOLEAN MODE) AS relevence_2 ) ORDER BY (relevance_1 * 3) + (relevance_2 * 2) DESC </code></pre> |
4,713,895 | 0 | <p>I think that in any case it would be better to use GIN (Guice for GWT) and its @Singleton annotation. But I am not sure it will solve your problem.</p> |
1,915,189 | 0 | <p>Yes. But you need to do an p4 integrate to get the files over. That is what p4v "copy or rename" does. Use the rename option, that also deletes the old files.</p> |
3,972,092 | 0 | SQL Server - can I load MDF without LDF file without losing data? <p>I have a backup database file (i.e. test.mdf), however, I don't have the LDF file. I was told that SQL Server 2008 R2 can load MDF without LDF.</p> <p>Is that true?</p> <p>Thank you</p> |
1,279,406 | 0 | <p>If it is a webapp they need to log into I would just restrict a user from being logged in more than once at a time. Other than that would wouldn't want to restrict their opening of the actual window</p> |
12,800,801 | 0 | <p>Using a HEAD request, you can do something like this:</p> <pre><code>private int getFileSize(URL url) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.getInputStream(); return conn.getContentLength(); } catch (IOException e) { return -1; } finally { conn.disconnect(); } } </code></pre> |
31,067,817 | 0 | <p>It is a bad idea, but if you change the <code>private</code> variable to a <code>public</code> one, you will achieve your goal. You probably should declare the variable as <code>final</code> as well to avoid surprises, but it is not strictly necessary, and doesn't make it a good idea (IMO).</p> <p>For what it is worth, there is no way to implement a singleton that doesn't involve an explicit variable to hold the instance, or an <code>enum</code>.</p> <hr> <p>Here is what Bloch has to say on the tradeoff between the public and private variable approaches:</p> <blockquote> <p>"One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return, say, a unique instance for each thread that invokes it. A second advantage, concerning generic types, is discussed in Item 27. Often neither of these advantages is relevant, and the final-field approach is simpler."</p> </blockquote> <p>My argument is that <em>knowing</em> that you won't need to change your mind in the future involves a degree of prescience. </p> <p>Or to put it another way, you can't <em>know</em> that: you can only predict that. And your prediction can be wrong. And if that prediction does turn out to be wrong, then you have to change every piece of code the accesses the singleton via the public variable.</p> <p>Now if your codebase is small, then the amount of code you need to change is limited. However, if your codebase is large, or if it is not all yours to change, then this this kind of of mistake can have serious consequences.</p> <p>That is why it is a bad idea.</p> |
1,910,301 | 0 | <p>I have recently implemented DAWG for a wordgame playing program. It uses a dictionary consisting of 2,7 million words from Polish language. Source plain text file is about 33MB in size. The same word list represented as DAWG in binary file takes only 5MB. Actual size may vary, as it depends on implementation, so number of vertices - 154k and number of edges - 411k are more important figures.</p> <p>Still, that amount of data is far too big to handle by JavaScript, as stated above. Trying to process several MB of data will hang JavaScript interpreter for a few minutes, effectively hanging whole browser.</p> |
12,483,886 | 0 | <p>Use File System Tasks:</p> <p>Create a variable called RmtArchPath (string)</p> <p>Set its value with the expression:</p> <blockquote> <p>"\\\\Remote_folder\\" + (DT_WSTR,4)YEAR(GETDATE()) + "-" + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-" + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + "\\"</p> </blockquote> <p>Create a file system task. For operation choose Create Directory. For UseDirectoryIfExists choose True. For IsSourcePathVariable choose RmtArchPath.</p> <p>Create a second Variable called SrcFileName (string)</p> <p>Create a ForEachLoop Container. For Collection choose the enumerator "Foreach File Enumerator", set the Folder = \\Remote_Folder, set the files = *.csv. For Variable Mappings set the variable = User::SrcFileName.</p> <p>Connect the File system task to the loop. (from the FS task to the loop for your flow direction).</p> <p>Create a second file system task inside the loop.</p> <p>Choose Move file for the operation. Set IsDestinationPathVariable to True, Set DestinationVariable = RmtArchPath. Set IsSourcePathVariable = True, Set SourceVariable = SrcFileName.</p> |
6,031,856 | 0 | <p>Okay I thought it all over.. and basically if i do understand correct you want the sum for each distinct set. </p> <blockquote> <p>So not 34 + 34 + 34 + 23 + 23 + 23 + 43 + 43 + 43 ... BUT 34 + 23 + 43</p> </blockquote> <p>In order to that you need to trick MySQL with the following query : </p> <pre><code>SELECT SUM(tot.invalid_votes) AS total FROM (SELECT DISTINCT QV, invalid_votes FROM `results`) tot </code></pre> <p>This will return the SUM of the <em>Distinct</em> values based on QV field.</p> <p>Table : </p> <pre><code>QV invalid_votes 0544 5 0544 5 0544 5 0545 6 0545 6 </code></pre> <p>based on the database information you provided i get the following result <strong>11</strong> </p> |
13,135,501 | 0 | <p>You don't have access to the right image as far my knowledge, unless you override the <code>onTouch</code> event. I suggest to use a <code>RelativeLayout</code>, with one <code>editText</code> and one <code>imageView</code>, and set <code>OnClickListener</code> over the image view as below:</p> <pre><code><RelativeLayout android:id="@+id/rlSearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:drawable/edit_text" android:padding="5dip" > <EditText android:id="@+id/txtSearch" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toLeftOf="@+id/imgSearch" android:background="#00000000" android:ems="10"/> <ImageView android:id="@+id/imgSearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:src="@drawable/btnsearch" /> </RelativeLayout> </code></pre> |
13,410,856 | 0 | How to read JSON response from Google web services in Javascript? <p>I am trying to find the distance between two locations. For that I used Google web services. I got a JSON response from that web service, but I am unable to get the distance from that JSON response in a javascript function.</p> <p>See my code below:</p> <pre><code>function myjourneysubdetails(){ var fp = jQuery('#fp').val(); var tp = jQuery('#tp').val(); var city = jQuery('#city').val(); alert(fp); $.ajax({ type : 'GET', url : 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=Silk board&destinations=marathahalli&language=en-US&sensor=false', async: false, success : function(data) { alert("Success"); var locObject = eval('(' + JSON.stringify(data) + ')'); alert("locObject: "+locObject); alert("Destination: "+locObject.destination_addresses); var origins = data.origin_addresses; var destinations = data.destination_addresses; alert('destinations'+destinations); for (var i = 0; i < origins.length; i++) { var results = data.rows[i].elements; for (var j = 0; j < results.length; j++) { var element = results[j]; var distance = element.distance.text; var duration = element.duration.text; var from = origins[i]; var to = destinations[j]; alert('distance'+distance); } } }, error : function(xhr, type) { alert('Internal Error Occoured! '+xhr+' : '+type); } }); } </code></pre> <p>Thanks in advance.</p> |
16,003,170 | 0 | <p>First, you never want to do default initializations in calling code, you can create a constructor for your struct and do it there:</p> <pre><code>struct Neuron { Neuron() : activation(0.0), bias(0.0), incomingWeights(0) {} double activation; double bias; double *incomingWeights; }; </code></pre> <p>Then (since this is C++)</p> <pre><code>for (int i = 0; i < din; i++) { ann.inputLayer[i] = new Neuron[din]; </code></pre> <p>You should use <code>new</code> over <code>malloc</code> in C++, though if you ever did need <code>malloc</code> your statement would need to be fixed, to:</p> <pre><code>ann.inputLayer = (Neuron*)malloc(din * sizeof(Neuron)); </code></pre> |
38,683,420 | 0 | Show hide marker using circle points openlayers 3 <p>How to show hide markers (P icon) using circle points (something like point1.distanceTo(point2))</p> <p>need to show markers If markers comes inside the circle another hide it (currently changing circle radius through slider) </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// we change this on input change var radius = 10; longitude = 400000; latitude = 300000; var styleFunction = function() { return new ol.style.Style({ image: new ol.style.Circle({ radius: radius, stroke: new ol.style.Stroke({ color: [51, 51, 51], width: 2 }), fill: new ol.style.Fill({ color: [51, 51, 51, .3] }) }) }); }; var update = function(value) { // $('#range').val() = value; radius = value; vectorLayer.setStyle(styleFunction); // $('#range').val(value) // document.getElementById('range').value=value; } var feature = new ol.Feature(new ol.geom.Point([longitude, latitude])); var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [feature] }), style: styleFunction }); var rasterLayer = new ol.layer.Tile({ source: new ol.source.TileJSON({ url: 'http://api.tiles.mapbox.com/v3/mapbox.geography-class.json', crossOrigin: '' }) }); // icon marker start here var iconFeature5 = new ol.Feature({ geometry: new ol.geom.Point([longitude, latitude]), name: 'Missing Person', population: 4000, rainfall: 500 }); var vectorSource5 = new ol.source.Vector({ features: [iconFeature5] }); var vectorLayer5 = new ol.layer.Vector({ source: vectorSource5 }); var iconStyle5 = new ol.style.Style({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({ anchor: [0.5, 46], anchorXUnits: 'fraction', anchorYUnits: 'pixels', src: 'https://cloud.githubusercontent.com/assets/41094/2833021/7279fac0-cfcb-11e3-9789-24436486a8b1.png' })) }); iconFeature5.setStyle(iconStyle5); // 2nd marker longitude1 = 100000; latitude1 = 100000; var iconFeature1 = new ol.Feature({ geometry: new ol.geom.Point([longitude1, latitude1]), name: 'Missing Person', population: 4000, rainfall: 500 }); var vectorSource1 = new ol.source.Vector({ features: [iconFeature1] }); var vectorLayer1 = new ol.layer.Vector({ source: vectorSource1 }); iconFeature1.setStyle(iconStyle5); var map = new ol.Map({ layers: [rasterLayer,vectorLayer,vectorLayer5,vectorLayer1], target: document.getElementById('map'), view: new ol.View({ center: [400000, 400000], zoom: 4 }) });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body, #map { height: 100%; overflow: hidden; } .input { margin: 5px 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><script src="http://openlayers.org/en/v3.16.0/build/ol.js"></script> <div class="input"> <input type="range" id="range" min="10" max="50" onchange="update(this.value)"> <input type="text" id="range" value="10"> </div> <div id="map" class="map"></div></code></pre> </div> </div> </p> |
21,726,409 | 0 | PostgreSQL - change precision of numeric? <p>I tried to change precision like this:</p> <pre><code>ALTER Table account_invoice ALTER amount_total SET NUMERIC(5); </code></pre> <p>But I get syntax error, so I'm clearly doing something wrong. What is the right syntax to change precision of numeric in PostgreSQL?</p> |
1,360,208 | 0 | <p>For a more complete example that performs key derivation in addition to the AES encryption, see the answer and links posted in <a href="http://stackoverflow.com/questions/1149611/getting-slowaes-and-rijndaelmanaged-class-in-net-to-play-together">Getting AES encryption to work across Javascript and C#</a>. </p> <p><strong>EDIT</strong><br> a side note: <a href="http://www.matasano.com/articles/javascript-cryptography/" rel="nofollow noreferrer">Javascript Cryptography considered harmful.</a> Worth the read.</p> |
26,373,691 | 0 | <p>Turns out I can't upload images to heroku.</p> <p>I have decided to use cloudinary for the time being.</p> <p>I will probably switch to S3 eventually.</p> |
2,057,531 | 0 | <ol> <li>It's a concept available on C++ (but not exclusively)</li> <li>No, it is not available in standard C.</li> <li><strike>See 1 and 2.</strike> See *1 and *2.</li> </ol> |
5,866,775 | 0 | <p>One simple way to solve this is to use some kind of a scheduled (cron...) job to delete any orphaned parents. Rather than doing it when deleting children.</p> |
22,548,875 | 0 | <p>I assume you have implemented a Jingle client. In order to make this work you should make sure that:</p> <ul> <li>Openfire (acting as a Media Proxy as well) is running on a computer with a public IP, so that each client behind any NAT can "talk" to it</li> <li>Your client media engine does support <a href="https://tools.ietf.org/html/rfc4961" rel="nofollow">symmetric RTP</a></li> </ul> <p>To enable Media Proxy in Openfire is simple as going to Openfire server web console (usually at openfirehost:9090/index.jsp), select tab "Media Services", set the option "Enabled" at "Media Proxy Settings" and then click on "Save Settings". </p> <p>PS: My Openfire version is 3.9.1</p> |
35,082,335 | 0 | Looping through dynamic JSON data using javascript <p>I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:</p> <p><a href="https://i.stack.imgur.com/tPCQa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tPCQa.png" alt=""></a></p> <p>This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request</p> <pre><code>$.ajax({ type: "POST", url: "/", dataType:'json', data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree}, success: function(data) { $('#img1').hide(); var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length; for(var i = 0; i < k; i++) { var obj = k[i]; console.log(obj); var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency); console.log(iscsi); } </code></pre> <p>While running above snippet I am getting following error message :</p> <p>data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined</p> |
26,743,684 | 0 | <p>Did you want just the current domain, or the domain with parent domains included?</p> <p>Current Domain Name:</p> <pre class="lang-powershell prettyprint-override"><code>Import-Module ActiveDirectory $name = Get-ADDomain | Select -ExpandProperty NetBIOSName Get-ADObject -Filter 'objectclass -eq "user"' -Properties CN,DisplayName,Discription | select | Export-Csv -NoTypeInformation "c:\" + $name + ".csv" </code></pre> |
15,841,045 | 0 | <p>You want to search and replace with the empty string using this regex:</p> <pre><code>\^([^^]*?)(?=[.,:;?"' ]) </code></pre> <p>You can see which portions you will be replacing, as well as a detailed visual of what's going on with the regex, on <a href="http://www.debuggex.com/?re=%5C%5E%28%5B%5E%5E%5D%2a?%29%28?=%5B.,%3a;?%22%27%20%5D%29&str=I%27m%20baffled%5Ebemused%20by%20his%20decision.%0D%0A%22Why%20are%20you%20so%20mean%5Enasty?%22%20she%20wailed%5Emoaned." rel="nofollow">www.debuggex.com</a>.</p> |
39,687,070 | 0 | id3js in giving RangeError: Offset is outside the bounds of the DataView <p>I'm trying to move bulk mp3 files from one directory to other directory and renaming them on the basis of their name/title/album name. I'm using id3js for finding its id3 values:</p> <p>My code snippet as follows:</p> <pre><code>let files = []; let walker = walk.walk(arg['search'], { followLinks: false }); walker.on('file', (root, stat, next)=>{ if(!strReg.test(""+root)) { let typ = stat.name.split("."); if (stat.name.substring(stat.name.lastIndexOf(".")) == '.mp3') { files.push({nm:stat.name,pth:root + ""+path.sep + stat.name}); } } next(); }); walker.on('end', function() { console.log("files are: ",files); files.forEach((o, i)=> { console.log((i/files.length*100),"% done and Working on :",o.nm); try { id3({file: o.pth, type: id3.OPEN_LOCAL}, function (err, tags) { let itsNm; if (o.nm.indexOf(".com") == -1 && o.nm.indexOf(".in") == -1) { itsNm = o.nm.substring(0, o.nm.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else if (tags.title && tags.title.indexOf(".com") == -1 && tags.title.indexOf(".in") == -1) { itsNm = tags.title.substring(0, tags.title.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else if (tags.album && tags.album.indexOf(".com") == -1 && tags.album.indexOf(".in") == -1) { itsNm = tags.album .substring(0, tags.album .lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else { itsNm = o.nm.substring(0, o.nm.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } fs.createReadStream(o.pth) .pipe(fs.createWriteStream(path.join(arg["out"], itsNm + o.nm.substring(o.nm.lastIndexOf("."))))); }); } catch (e){ console.log(e); } }); }) </code></pre> <p>But it gives following error:</p> <pre><code>frameBit = dv.getUint8(position + i); ^ RangeError: Offset is outside the bounds of the DataView at DataView.getUint8 (native) at D:\projBulderMac\node_modules\id3js\dist\id3.js:928:22 at D:\projBulderMac\node_modules\id3js\dist\id3.js:118:4 at FSReqWrap.wrapper [as oncomplete] (fs.js:576:17) </code></pre> |
4,168,408 | 0 | Can I produce native executables with OCamlBuild which can run in computers which don't have OCaml libraries? <p>I have a large OCaml project which I am compiling with ocamlbuild. Everything works fine, I have a great executable which does everything as I want. The problem is that when I take that native executable "my_prog.native" and run it somewhere else (different machine with same operating system, etc.), the new machine complaints that it can't find camomile (which is used in a Batteries library I'm using). I thought the executable we got from ocamlbuild was standalone and didn't require OCaml or Camomile to be present in the machine we ran it, but that doesn't seem to be the case.</p> <p>Any ideas on how to produce really standalone executables?</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.