input
stringlengths
51
42.3k
output
stringlengths
18
55k
UIRefreshControl not Dissapearing <p>The pull to refresh is not disappearing. There is only 3 rows visible on the screen and after using <code>print(indexPath.row)</code> I can see that it is reloading rows 0,1,2 again but the refresh control is not disappearing.</p> <pre><code>override func viewDidLoad() { super.viewDidLoad() ... refreshControl = UIRefreshControl() refreshControl!.addTarget(self, action: #selector(self.loadData), forControlEvents: UIControlEvents.ValueChanged) refreshControl!.backgroundColor = UIColor.clearColor() refreshControl!.tintColor = UIColor.clearColor() tableView.addSubview(refreshControl!)...} </code></pre> <p>Here is the loadData function:</p> <pre><code>func loadData() { venues = [CKRecord]() let location = locationManager.location let radius = CGFloat(1000) let sort = CKLocationSortDescriptor(key: "Location", relativeLocation: location!) let predicate = NSPredicate(format: "distanceToLocation:fromLocation:(%K,%@) &lt; %f", "Location", location!, radius) let publicData = CKContainer.defaultContainer().publicCloudDatabase let query = CKQuery(recordType: "Venues", predicate: predicate ) query.sortDescriptors = [sort] publicData.performQuery(query, inZoneWithID: nil) { (results:[CKRecord]?, error:NSError?) in if let venues = results { self.venues = venues dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() }) } } } </code></pre>
<p>First, this line is wrong:</p> <pre><code>tableView.addSubview(refreshControl!)...} </code></pre> <p>You do not need to add a refresh control to a table view in iOS 10 as a subview. It has a <code>refreshControl</code> <em>property</em> that you <em>set</em>:</p> <pre><code>tableView.refreshControl = refreshControl </code></pre> <p>Second, you are absolutely right that the refresh control does not disappear by itself. When you've reloaded your data, it is up to <em>you</em> to send the refresh control the <code>endRefreshing()</code> message.</p> <pre><code> dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() self.tableView.refreshControl.endRefreshing() }) </code></pre>
ActiveRecord/Sinatra: separate columns for date and time? <p>How can I get form parameters from the user for date and time separately?</p> <p>For example:</p> <pre><code>class CreatePosts &lt; ActiveRecord::Migration create_table :posts do |t| t.string :title t.text :content t.date :date t.time :time end end </code></pre> <p>I am aware that <code>t.date</code> is the correct syntax, however is <code>t.time</code> correct? I want to take the params for date and time and interpret them with consistency. For example, I always want 01/02/2015 to display as January, 2nd, 2015 and 13:00 to display as 1PM. I am aware I can take the date and manipulate it with <code>@post.date.strftime('%A, %b %d, %Y')</code> but can I do something similar with time?</p>
<p><a href="http://stackoverflow.com/questions/17918117/rails-4-list-of-available-datatypes">Yes there is a <code>time</code> type.</a> But you're thinking about the problem wrong.</p> <p>You should select the database type based on the level of precision that you need to store the timestamp. Not by how you intend to present it. </p> <p>Thats what <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html" rel="nofollow">helper methods</a> are for.</p>
AWK: match characters inside a captured group <p>For example, I have groups of citations within the text like these</p> <pre><code>Lorem ipsum \textbf{dolor} sit amet \cite{a,b,c,d,e}, consectetur adipiscing elit. In molestie urna et dui $\mu=\text{a b c}$ venenatis pretium. Duis sit amet metus orci \cite{a,b,c,d,e}. Nunc non lobortis arcu, sit amet imperdiet diam \cite{b,e,f}. </code></pre> <p>in a latex file. There can be many such paragraphs exist.</p> <p>I want to match all commas <code>,</code> inside the <code>\cite</code> command to replace with another character, let say with <code>.</code> to have all the citations become <code>\cite{a.b.c.d.e}</code>, <code>\cite{b.e.f}</code>, keeping the text the same.</p> <p>So the output should be</p> <pre><code> Lorem ipsum \textbf{dolor} sit amet \cite{a.b.c.d.e}, consectetur adipiscing elit. In molestie urna et dui $\mu=\text{a b c}$ venenatis pretium. Duis sit amet metus orci \cite{a.b.c.d.e}. Nunc non lobortis arcu, sit amet imperdiet diam \cite{b.e.f}. </code></pre>
<p>Your question is unclear but is this what you want?</p> <pre><code>$ awk -F, 'match($0,/\\cite\{([^\}]+)/,a) {$0=a[1]; for (i=1; i&lt;=NF; i++) print NR, i, $i}' file 1 1 a 1 2 b 1 3 c 1 4 d 1 5 e 2 1 b 2 2 e 2 3 f </code></pre> <p>The above uses GNU awk for the 3rd arg to match(). If all you want to do is change the <code>,</code>s to <code>.</code>s that's just:</p> <pre><code>$ awk -F, 'match($0,/(.*\\cite\{)([^\}]+)(.*)/,a) {gsub(/,/,".",a[2]); $0=a[1] a[2] a[3]} 1' file \cite{a.b.c.d.e} \cite{b.e.f} </code></pre> <p>Given your newly posted sample input output:</p> <pre><code>$ awk -v RS='[\\]cite[{][^}]+[}]' '{ORS=gensub(/,/,".","g",RT)} 1' file Lorem ipsum \textbf{dolor} sit amet \cite{a.b.c.d.e}, consectetur adipiscing elit. In molestie urna et dui $\mu=\text{a b c}$ venenatis pretium. Duis sit amet metus orci \cite{a.b.c.d.e}. Nunc non lobortis arcu. sit amet imperdiet diam \cite{b.e.f}. </code></pre> <p>Still using GNU awk, this time for multi-char RS and RT.</p>
Show hidden div permanently throughout website after clicking on a specific <a> href link once <p>i found this <a href="http://stackoverflow.com/questions/31197270/show-hidden-div-permanently-throughout-website-after-clicking-on-a-a-href-link">link</a> of a question like the one i have, the thing is that the solution they give its for clicking any div in the html, and i need something like, when i click the first div, the second div its showed and when i press the second div, the third div its showed, and i need it to keep on localstorage... This is my HTML code:</p> <pre><code>&lt;div id='btn1' class="col-lg-4""&gt; &lt;a id="tema_1 " href="tema.html"&gt;&lt;img id="img_tema1" class="img-circle" src="../assets/img/primer_tema.gif" alt="Generic placeholder image" width="140" height="140"&gt;&lt;/a&gt; &lt;h2&gt;Tema 1&lt;/h2&gt; &lt;/div&gt;&lt;!-- /.col-lg-4 --&gt; &lt;div class="col-lg-4-2"&gt; &lt;a href=""&gt;&lt;img id="img_tema2" class="img-circle2" src="../assets/img/segundo_tema.gif" alt="Generic placeholder image" width="140" height="140"&gt;&lt;/a&gt; &lt;h2&gt;Tema 2&lt;/h2&gt; &lt;/div&gt;&lt;!-- /.col-lg-4-2 --&gt; &lt;div class="col-lg-4-3"&gt; &lt;a href="tema_3.html"&gt;&lt;img id="img_tema3" class="img-circle3" src="../assets/img/tercer_tema.gif" alt="Generic placeholder image" width="140" height="140"&gt;&lt;/a&gt; &lt;h2&gt;Tema 3&lt;/h2&gt; &lt;/div&gt;&lt;!-- /.col-lg-4-3 -- </code></pre> <p>And this is the example of Jquery code that i use:</p> <pre><code>var hide2 = localStorage[location] ? false : true; var hidden2 = document.querySelector('.col-lg-4-2'); if(hide2) { hidden2.style.display = 'none'; document.onclick = function() { localStorage[location] = true; hidden2.style.display = ''; document.onclick = ''; console.log('click'); } } </code></pre> <p>But as i say... it makes that any div that i click, shows the Tema 2, and i need that the only div that can show the Tema 2 is the Tema 1 Div.</p> <p>Excuse my bad english but my mother language its Spanish.</p> <p>Thank you for any help.</p>
<p>I think this might be solved using simple jQuery. I've used the example specified at: <a href="http://stackoverflow.com/questions/31197270/show-hidden-div-permanently-throughout-website-after-clicking-on-a-a-href-link">Previous Similar question</a> and changed it so it will fit your code. It currently works which is fine but I might wanna work around it if you don't like my solution.</p> <pre><code> $(function () { var showLittleHeader = localStorage.getItem('#second-img'); if (showLittleHeader) { $('#second-img').show(); } $('#first-img').on('click', function () { localStorage.setItem('#second-img', 1); $('#second-img').show(); }); }); $(function () { var showLittleHeader = localStorage.getItem('#third-img'); if (showLittleHeader) { $('#third-img').show(); } $('#second-img').on('click', function () { localStorage.setItem('#third-img', 1); $('#third-img').show(); }); }); </code></pre> <p>Look at this JS Fiddle and see if it does the job for you:</p> <p><a href="https://jsfiddle.net/DTcHh/26039/" rel="nofollow">Updated Solution with Local Storage</a></p>
Mysql : show 0 and transaction type when no result found <p><strong>Table structure:</strong> <br/></p> <pre><code>reference|transaction|member|summary|amount|action_by|created_at(unix timestamp) </code></pre> <p>My current Sql is :</p> <pre><code>select COALESCE(sum(`amount`) , 0) as `amount` , `transaction` from `transactions` where `transaction` IN ('payment', 'deposit', 'withdraw') and `created_at` &gt;= unix_timestamp(DATE_SUB(NOW(), INTERVAL 15 DAY)) group by transaction </code></pre> <p>Let's say there are no records found for payment. I still want to get it on the result. Right now the current result is: <br/></p> <pre><code>100 | deposit 200 | withdraw </code></pre> <p>What result i need is : <br/></p> <pre><code>100 | deposit 200 | withdraw 0 | payment </code></pre> <p>I tried several things but I couldn't produce the desired result. Please help, i'm beginner in sql. Thanks in advance.</p>
<p>you need have a separate table with each unique <code>transaction</code> value. This can be done either with a separate table or you can use a derived table as below: </p> <pre><code>SELECT COALESCE(sum(`amount`),0) as amount, der.transaction_type FROM (SELECT 'payment' as transaction_type UNION SELECT 'deposit' UNION SELECT 'withdraw') der LEFT JOIN `transactions` t on t.transaction=der.transaction_type AND `transaction` AND `created_at` &gt;= unix_timestamp(DATE_SUB(NOW(), INTERVAL 15 DAY)) group by der.transaction_type </code></pre> <p>This will be show but if your table doesn't have a lot of rows in it then it shouldn't be too big of a deal. It'll perform MUCH better if you have a dedicated table and indexes on the columns</p>
How to know the set for IP address from C in linux is successful or fail <p>I use this code to setup the IP address</p> <pre><code>int set_ip(const char *name, const char *ip) { struct ifreq ifr; struct sockaddr_in *addr; int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); strncpy(ifr.ifr_name, name, IFNAMSIZ); ifr.ifr_addr.sa_family = AF_INET; addr = (struct sockaddr_in*)&amp;ifr.ifr_addr; /* inet_pton() returns 1 on success */ /* network address was successfully converted */ int s; s = inet_pton(AF_INET, ip, &amp;addr-&gt;sin_addr); if (s &lt;= 0) { if (s == 0) fprintf(stderr, "Set IP %s not in presentation format\n", ip); else perror ("inet_pton"); exit (EXIT_FAILURE); } ioctl(fd, SIOCSIFADDR, &amp;ifr); ioctl(fd, SIOCGIFFLAGS, &amp;ifr); strncpy(ifr.ifr_name, name, IFNAMSIZ); ifr.ifr_flags |= (IFF_UP | IFF_RUNNING); ioctl(fd, SIOCSIFFLAGS, &amp;ifr); return 0; } </code></pre> <p>The code is modified from here <a href="http://stackoverflow.com/q/6652384/3309645">How to set the IP address from C in linux</a>.</p> <p>My question is</p> <p>How to know the ip address change successfully or not? Because the return value of ioctl always be 0.</p> <pre><code>$ uname -a Linux DMA1 4.4.0-38-generic #57-Ubuntu SMP Tue Sep 6 15:42:33 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux </code></pre> <p>I have googled for hours but not found any solutions. So I post my question in here to ask experts in SO. Thanks in advance</p>
<p>Thank you all, below is the solution suggested by you experts:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;ifaddrs.h&gt; #include &lt;string.h&gt; #include &lt;arpa/inet.h&gt; #include &lt;net/if.h&gt; #include &lt;net/route.h&gt; // struct rtentry #include &lt;sys/ioctl.h&gt; #include &lt;sys/socket.h&gt; #include &lt;sys/types.h&gt; #include &lt;unistd.h&gt; int set_addr (const char *name, const char *ip, unsigned long request) { struct ifreq ifr; struct sockaddr_in *addr; int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); strncpy(ifr.ifr_name, name, IFNAMSIZ); ifr.ifr_addr.sa_family = AF_INET; addr = (struct sockaddr_in*)&amp;ifr.ifr_addr; // inet_pton() returns 1 on success // network address was successfully converted int s; s = inet_pton(AF_INET, ip, &amp;addr-&gt;sin_addr); if (s &lt;= 0) { if (s == 0) fprintf(stderr, "Set IP %s not in presentation format\n", ip); else perror ("inet_pton"); exit (EXIT_FAILURE); } if (ioctl(fd, request, &amp;ifr) != 0) { // SIOCSIFADDR perror ("ioctl"); exit (EXIT_FAILURE); } ioctl(fd, SIOCGIFFLAGS, &amp;ifr); strncpy(ifr.ifr_name, name, IFNAMSIZ); ifr.ifr_flags |= (IFF_UP | IFF_RUNNING); ioctl(fd, SIOCSIFFLAGS, &amp;ifr); return 0; } </code></pre> <p>Don't forget to grant your program with root privilege using following commands in your Makefile or command line:</p> <pre><code>$ sudo chown root your_program $ sudo comod a+xs your_program </code></pre> <p>Otherwise, you will get a error message <code>ioctl: Operation not permitted</code></p>
Dynamically display "Next" or "Submit" in Gravity Forms <p>I am creating a form with conditional logic: Option 1: a user will put in just their basic information. Option 2: if they select a checkbox then they will fill in a series of questions in addition to the basic information. I would like that all the questions that will be presented in option 2 to be on page two of the form which will only display accordingly. All this works, the issue is that the "Submit" button is on page two not page one, so in option 1 the user does not see a "Submit" button only a "Next" button. [The next will submit the form but my concern is the text and styling of the button]. I need conditional logic on the Submit button so if option 1 is chosen the button will display a Submit button and if they choose option 2 it will display a next button. </p>
<p>Based on the checkbox state, you can change the button's text (its value).<br> Since you showed no code, here's an minimal example.</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>$("#more").on("click",function(){ if ( $(this).prop("checked") ){ $("#next").val("Next"); }else{ $("#next").val("Submit"); } }); $("#next").on("click",function(){ if( $(this).val() == "Submit" ){ alert("Submit the form now."); }else{ alert("Ask the other questions."); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="checkbox" id="more"&gt; Check to answer additionnal question&lt;br&gt; &lt;br&gt; &lt;input type="button" id="next" value="Submit"&gt;</code></pre> </div> </div> </p>
confused generating fibonacci sequence <p><strong>(i) When I run below code,</strong> </p> <pre><code>var fib = []; for(var i=1; i&lt;=10; i++){ if (i === 1) { fib[0] = 0; } else if (i == 2) { fib[1] = 1; } else { fib[i] = fib[i-2] + fib[i-3]; console.log(fib[i]); } } Output: 0 1 undefined 1 NaN NaN </code></pre> <p><strong>(ii) When I run below code,</strong></p> <pre><code>function generateFib(num) { var fib = []; for(var i=1; i &lt;= num; i++) { if (i === 1) { fib.push(0); } else if (i == 2) { fib.push(1); } else { fib.push(fib[i - 2] + fib[i - 3]); } } return fib; } generateFib(10); Output: 0 1 1 2 3 5 </code></pre> <p>I am confused between two code could you please explain me, thank you.</p>
<p>Follow the loops iterations one by one</p> <p>in the third iteration,</p> <p><code>fib[2] = fib[2-2] + fib[2-3];</code> is <code>fib[2] = fib[0] + fib[-1];</code></p> <p><code>fib[2] = 0 + undefined;</code></p> <p><code>fib[2] = undefined;</code></p> <p>in the fourth iteration,</p> <p><code>fib[3] = fib[3-2] + fib[3-3];</code> is <code>fib[3] = fib[1] + fib[0];</code></p> <p><code>fib[3] = 1 + 0;</code></p> <p>in the fifth iteration,</p> <p><code>fib[4] = fib[4-2] + fib[4-3];</code> is <code>fib[4] = fib[2] + fib[1];</code></p> <p><code>fib[4] = undefined + 1;</code></p> <p><code>fib[4] = NaN;</code></p> <p>You can figure out the rest. </p> <p>Btw you could use a debugger with breakpoints.</p> <p>It would be really useful in this situation. </p>
Split string every 20 characters and then print each section to console <p>Okay so, I am trying to do something for a larger project and I need to split a string every 20 characters and then print each section to console with a delay of 1 second between each input I tried to do:</p> <pre><code>if (x==true){ String[] Text = JOptionPane.showInputDialog("Input string").split(null, 20); for (int i = 0; i &lt; Text.length; i++) { String splitText = (Text[ i ]); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(splitText); } } </code></pre> <p>But it didn't work (I'm not very experienced with java, sorry.)<br> Does anyone have any idea of what would work?<br> (if you could rewrite my code to something that works and explain it that would be fantastic but any help is appreciated).</p>
<p>The method split can not achieve your goal.You can read split method api. Splits this string around matches of the given regular expression. The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string. The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. The string "boo:and:foo", for example, yields the following results with these parameters: Regex Limit Result </p> <pre><code>: 2 { "boo", "and:foo" } : 5 { "boo", "and", "foo" } : -2 { "boo", "and", "foo" } o 5 { "b", "", ":and:f", "", "" } o -2 { "b", "", ":and:f", "", "" } o 0 { "b", "", ":and:f" } </code></pre> <p>If I do this,I will use code blow:</p> <pre><code>String input = JOptionPane.showInputDialog("Input string"); int count = input.length() / 20 + 1; for(int i = 0;i &lt; count;i++) { System.out.println(input.substring(i * 20, (i + 1) * 20 &gt;= input.length() ? input.length() : (i + 1) * 20)); } </code></pre>
Node.js Http post request on aws lambda Socket Hang up <pre><code>var http = require('http'); exports.handler = function(event, context) { var headers = { 'content-type': 'application/x-www-form-urlencoded' } var options = { host: 'stage.wings.com', path:'/test-lambda', form: { 'days':'3' }, headers:headers }; console.log(options); var req = http.request(options, function(response) { // Continuously update stream with data var body = ''; response.on('data', function(d) { body += d; }); response.on('end', function() { // Data reception is done, do whatever with it! var parsed = JSON.parse(body); console.log("success"); console.log(parsed); }); }); // Handler for HTTP request errors. req.on('error', function (e) { console.error('HTTP error: ' + e.message); completedCallback('API request completed with error(s).'); }); }; </code></pre> <p>my node version : v0.10.25 If i execute on file it gives HTTP error: socket hang up From aws lambda if i run this function it throws error</p> <p>Lambda error:2016-10-09T23:11:17.200Z 89f2146f-8e75-11e6-9219-b9b32aa0a768 Error: socket hang up at createHangUpError (_http_client.js:200:15) at Socket.socketOnEnd (_http_client.js:285:23) at emitNone (events.js:72:20) at Socket.emit (events.js:166:7) at endReadableNT (_stream_readable.js:905:12) at nextTickCallbackWith2Args (node.js:437:9) at process._tickDomainCallback (node.js:392:17)</p>
<p>There is a timeout time for aws-lambda, it will hang up after at most 300 seconds.</p> <p>Here is little more about it. <a href="http://docs.aws.amazon.com/lambda/latest/dg/limits.html" rel="nofollow">http://docs.aws.amazon.com/lambda/latest/dg/limits.html</a></p> <p>you can use <code>context.getRemainingTimeInMillis();</code> which will return you remaining time of your lambda so you can flush your data. If this is intended to be run longer than five minutes, then you can implement some kind of grace-full shutdown and flush your data before that.</p>
only able to check first element of my array <p>I am having some issues with getting my array to iterate through in my for loop. The point of this function is to check if the number has already been placed into the array somewhere else so no duplicates can appear. when I run through the function it only iterates through the first element of the function and stops.</p> <pre><code>bool check(int wins[], int number) { for (int i = 0; i &lt;= arraySize; ++i) if (number == wins[i]) { return true; } else if (number != wins[i]) { return false; } } </code></pre> <p>I really appreciate the help.</p>
<p>Your indentation is misleading. Here what is happening: </p> <pre><code>bool check(int wins[], int number) { for (int i = 0; i &lt;= arraySize; ++i) if (number == wins[i]) { return true; } else if (number != wins[i]) { return false; } } </code></pre> <p>So in first iteration, you, either number is equal to the element or it's different, but in both case you return and the function is finished ! </p> <p>If you want to search your item, you have to do a slight change: </p> <pre><code>bool check(int wins[], int number) { for (int i = 0; i &lt; arraySize; ++i) // assuming that arraySize is some const size of the array if (number == wins[i]) // if number is found { return true; // return immediately } // if you arrive here, the loop finished without a match return false; } </code></pre>
Removing Odds from a LinkedList recursively using index <p>I am having a little bit of difficulties with the Recursive concept.</p> <p>Given a LinkedList with Integer values </p> <pre><code>L1 = (2-&gt;1-&gt;4-&gt;6-&gt;3) L2= (1-&gt;9-&gt;6-&gt;3) </code></pre> <p>The function should remove the Odd numbers from the linkedlist starting at the integer N and returns a reference to the new head</p> <p>i.e </p> <pre><code>L1.deleteOdd(2) = &gt; (2-&gt;4-&gt;6) L2.deleteOdd(1) = &gt; (6) </code></pre> <p>I implemented a normal iterative function that does the job, here it is</p> <pre><code>public node deleteOdd(int n) { node head = this.head; if (head == null) return head; while (head != null) { if (head.data == n) { node head2 = head; while (head2.next != null) { if (head2.next.data % 2 != 0) { head2.next = head2.next.next; } else { head2 = head2.next; } } if (head.data % 2 != 0) { return head.next; } return head; } head = head.next; } return head; } </code></pre> <p>Now I am trying to do a recursive function, I tried doing something but it seems like I am missing something.</p> <p>My recursive function is </p> <pre><code>public node DeleteOddR(int n) { node head = this.head; if (head == null) return head; if (head != null) { if (head.data == n) { node head2 = head; if (head2.next.data % 2 != 0) { head2.next = head2.next.next; } else { head2 = head2.next; } if (head.data % 2 != 0) { return DeleteOddR(head.next.data); } else { head.next = DeleteOddR(head.next.data); return head; } } else { head = head.next; } } return head; } </code></pre> <p>The results is </p> <pre><code> node f = l1.DeleteOddR(2); display(f); // Gives- &gt;2-&gt;3-&gt;4-&gt;6 </code></pre> <p>I would appreciate helps..</p>
<p>I write one may meet your requirement .<br> Save the previous node and recurse using it . </p> <pre><code>public class LinkedList{ public static void main(String[] args) { LinkedList node0 = new LinkedList(0); LinkedList node1 = new LinkedList(1); LinkedList node2 = new LinkedList(2); LinkedList node3 = new LinkedList(3); LinkedList node4 = new LinkedList(4); LinkedList node5 = new LinkedList(5); LinkedList node6 = new LinkedList(6); LinkedList node7 = new LinkedList(7); LinkedList node8 = new LinkedList(8); node0.setNext(node1); node1.setNext(node2); node2.setNext(node3); node3.setNext(node4); node4.setNext(node5); node5.setNext(node6); node6.setNext(node7); node7.setNext(node8); node0.removeOddFromVale(3, false); System.out.println(); } public void removeOddFromVale(int value,boolean start){ LinkedList head = this; LinkedList prev = this; if(!start){ while(head != null){ if(head.value == value){ start = true; break; } prev = head; head = head.next; } } if(prev != null &amp;&amp; head != null){ if(prev == head){ head = head.next; } if (head != null) { if (head.value % 2 == 0) { prev.next = head.next; } else { prev = prev.next; head = head.next; } if (prev != null) { prev.removeOddFromVale(value, true); } } } } private LinkedList next; private int value; public LinkedList(int value){ this.value = value; } public LinkedList getNext() { return next; } public void setNext(LinkedList next) { this.next = next; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } } </code></pre>
export or download gridview with custom table schema C# <p><a href="http://i.stack.imgur.com/gmPQj.png" rel="nofollow">My Gridview Header</a> I have question ..So i have Grid where the data are binding from SQL..And i will export/download file to .XML files..its success but the header table XML files are not same with "Schema" on Grid..ex= i have field 'Actual Duty On Time In' on grid but on exporting file .XML field header name changes to 'Actual_Duty_On_Time_In'...<a href="http://i.stack.imgur.com/myyCN.png" rel="nofollow">My Table .XML Header</a></p> <p>The question is.. can i customize the "Schema" in C#...so the .XM file are same with grid schema?</p> <p>This is my code</p> <pre><code>GetData(); DataSet ds = new DataSet(); DataTable dtxml = ((DataView)GVHostDtl.DataSource).Table; ds.Tables.Add(dtxml); ds.WriteXml(Server.MapPath("~/" + xmlFileName)); </code></pre>
<p>For this purpose I always use this method and works just fine : </p> <pre><code>private void ExportGridToXML() { SaveFileDialog SaveXMLFileDialog = new SaveFileDialog(); SaveXMLFileDialog.Filter = "Xml files (*.xml)|*.xml"; SaveXMLFileDialog.FilterIndex = 2; SaveXMLFileDialog.RestoreDirectory = true; SaveXMLFileDialog.InitialDirectory = "C:\\"; SaveXMLFileDialog.FileName = "myXml"; SaveXMLFileDialog.Title = "XML Export"; if (SaveXMLFileDialog.ShowDialog() == DialogResult.OK) { DataSet ds = new DataSet(); DataTable dtxml = (DataTable)ViewState["Data"]; ds.Tables.Add(dtxml); ds.WriteXml(File.OpenWrite(SaveXMLFileDialog.FileName)); } XMLFileThread.Abort(); } </code></pre>
UILabel has internal padding from programmatic constraints <p>So, I don't know why this is happening, but here is a pic depicting it.</p> <p><a href="http://i.stack.imgur.com/mi5lw.png" rel="nofollow"><img src="http://i.stack.imgur.com/mi5lw.png" alt="enter image description here"></a></p> <p>If you look at the UILabel with green background, there is padding above and below it, but I don't know why that is.</p> <p>This is how I create it:</p> <pre><code>var bodyLabel: ActiveLabel = { let label = ActiveLabel() label.translatesAutoresizingMaskIntoConstraints = false label.isUserInteractionEnabled = false label.backgroundColor = .green label.numberOfLines = 0 label.textColor = .darkGray label.font = UIFont.systemFont(ofSize: MessageTableViewCell.defaultFontSize()) label.enabledTypes = [.mention] label.mentionColor = .gray //Figure this out return label }() </code></pre> <p>The fact that it is an ActiveLabel is not the reason why this is happening.</p> <p>Here are all the constraints it is involved in:</p> <pre><code>self.contentView.addSubview(self.thumbnailView) self.contentView.addSubview(self.titleLabel) self.contentView.addSubview(self.bodyLabel) self.contentView.addSubview(self.likeView) let views = ["thumbnailView" : self.thumbnailView, "titleLabel" : self.titleLabel, "bodyLabel" : self.bodyLabel, "likeView" : self.likeView] as [String : Any] let metrics = ["tumbSize" : Constants.kMessageTableViewCellAvatarHeight, "padding" : 15, "right" : 10, "left" : 5] self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[thumbnailView(tumbSize)]-right-[titleLabel(&gt;=0)]-right-|", options: [], metrics: metrics, views: views)) self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-left-[thumbnailView(tumbSize)]-right-[bodyLabel(&gt;=0)]-right-|", options: [], metrics: metrics, views: views)) self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-right-[thumbnailView(tumbSize)]-(&gt;=0)-|", options: [], metrics: metrics, views: views)) if self.reuseIdentifier == Constants.MessageCellIdentifier { self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-right-[titleLabel(20)]-left-[bodyLabel(&gt;=0@999)]-left-|", options: [], metrics: metrics, views: views)) } else { self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[titleLabel]|", options: [], metrics: metrics, views: views)) } </code></pre> <p>I noticed that when I remove the constraint in the if statement, that obviously the views get into awkward positions, but I do notice that it no longer has that green padding. I'm really not sure what is causing this padding.</p> <p>This is what <a href="https://github.com/slackhq/SlackTextViewController/blob/master/Examples/Messenger-Shared/MessageTableViewCell.m" rel="nofollow">the code is based on.</a></p>
<p>Well, you're adding that padding by wrapping that body label with the <code>left</code> value.</p> <p>So instead of: <code> V:|-right-[titleLabel(20)]-left-[bodyLabel(&gt;=0@999)]-left-| </code></p> <p>Do something like: <code> V:|-right-[titleLabel(20)][bodyLabel(&gt;=0@999)]| </code></p> <p>That will remove both top and bottom padding. I hope that helps!</p>
Kivy: how to reference widgets from python code? <p>Basic Kivy question. Given this kv file:</p> <pre><code>BoxLayout: MainMenu: MyCanvasWidget: &lt;MainMenu&gt;: Button: on_press: root.do_action() </code></pre> <p>How do I call a method of MyCanvasWidget (for drawing something) from the do_action method when the button in MainMenu is pressed?</p>
<pre><code>BoxLayout: MainMenu: do_action: mycanvas.method MyCanvasWidget: id: mycanvas &lt;MainMenu&gt;: Button: on_press: root.do_action() </code></pre> <p>Got some inspiration from <a href="http://stackoverflow.com/questions/39807997/how-to-access-some-widget-attribute-from-another-widget-in-kivy?rq=1">How to access some widget attribute from another widget in Kivy?</a></p>
Create a table by merging many files <p>This seemed like such an easy task, yet I am boggled.</p> <p>I have text files, each named after a type of tissue (e.g. <code>cortex.txt</code>, <code>heart.txt</code>)</p> <p>Each file contains two columns, and the column headers are <code>gene_name</code> and <code>expression_value</code></p> <p>Each file contains around 30K to 40K rows</p> <p>I need to merge the files into one file with 29 columns, with headers</p> <pre><code>genename, tissue1, tissue2, tissue3, etc. to tissue28 </code></pre> <p>So that each row contains one gene and its expression value in the 28 tissues</p> <p>The following code creates an array containing a list of every gene name in every file:</p> <pre><code>my @list_of_genes; foreach my $input_file ( @input_files ) { print $input_file, "\n"; open ( IN, "outfiles/$input_file"); while ( &lt;IN&gt; ) { if ( $_ =~ m/^(\w+\|ENSMUSG\w+)\t/) { # check if the gene is already in the gene list my $count = grep { $_ eq $1 } @list_of_genes; # if not in list, add to the list if ( $count == 0 ) { push (@list_of_genes, $1); } } } close IN; } </code></pre> <p>The next bit of code I was hoping would work, but the regex only recognises the first gene name.</p> <p><em>Note: I am only testing it on one test file called "tissue1.txt".</em></p> <p>The idea is to create an array of all the file names, and then take each gene name in turn and search through each file to extract each value and write it to the outfile in order along the row.</p> <pre><code>foreach my $gene (@list_of_genes) { # print the gene name in the first column print OUT $gene, "\t"; # use the gene name to search the first element of the @input_file array and dprint to the second column open (IN, "outfiles/tissue1.txt"); while ( &lt;IN&gt; ) { if ($_ =~ m/^$gene\t(.+)\n/i ) { print OUT $1; } } print OUT "\n"; } </code></pre> <p>EDIT 1: Thank you Borodin. The output of your code is indeed a list of every gene name with a all expression values in each tissue.</p> <p>e.g. Bcl20|ENSMUSG00000000317,0.815796340254127,0.815796340245643</p> <p>This is great much better than I managed thank you. Two additional things are needed.</p> <p>1) If a gene name is not found in the a .txt file then a value of 0 should be recorded</p> <p>e.g. Ht4|ENSMUSG00000000031,4.75878049632381, 0</p> <p>2) I need a comma separated header row so that the tissue from which each value comes remains associated with the value (basically a table) - the tissue is the name of the text file </p> <p>e.g. From 2 files heart.txt and liver.txt the first row should be:</p> <p>genename|id,heart,liver</p> <p>where genename|id is always the first header</p>
<p>That's a <em>lot</em> of code to implement the simple idiom of using a hash to enforce uniqueness!</p> <p>It's looking like you want an array of <em>expression values</em> for each different <code>ENSMUSG</code> string in all <code>*.txt</code> files in your <code>outfiles</code> directory.</p> <p>If the files you need are the only ones in the <code>outfles</code> directory, then the solution looks like this. I've used <code>autodie</code> to check the return status of all Perl IO operations (<code>chdir</code>, <code>open</code>, <code>print</code> etc.) and checked only that the <code>$gene</code> value contains <code>|ENSMUSG</code>. You may not need even this check if your input data is well-behaved.</p> <p>Please forgive me if this is bugged, as I have no access to a Perl compiler at present. I have checked it by sight and it looks fine.</p> <pre><code>use strict; use warnings 'all'; use autodie; chdir '/path/to/outfiles'; my %data; while ( my $file = glob '*.txt' ) { open my $fh, '&lt;', $file; while ( &lt;$fh&gt; ) { my ($gene, $value) = split; next unless $gene =~ /\|ENSMUSG/; push @{ $data{$gene} }, $value; } } print join(',', $_, @{ $data{$_} }), "\n" for keys %data; </code></pre>
how to get multiple values of drop down from a loop? <pre><code>&lt;?php // this is where selecting of number of rooms in database $sql = mysqli_query($con, 'SELECT * FROM roomtype'); $get_room1 = mysqli_query ($con, "SELECT * from room where status='Activated' and type_id=2"); $get_room2 = mysqli_query ($con, "SELECT * from room where status='Activated' and type_id=3"); $get_room3 = mysqli_query ($con, "SELECT * from room where status='Activated' and type_id=4"); $get_room4 = mysqli_query ($con, "SELECT * from room where status='Activated' and type_id=5"); $standard = mysqli_num_rows($get_room1); $deluxe = mysqli_num_rows($get_room2); $family = mysqli_num_rows($get_room3); $regular = mysqli_num_rows($get_room4); // this is the loop for the drop down and it will display the number of rooms available while($row = mysqli_fetch_array($sql)) { $a=$row['type_id']; $b = $row['rmtype']; $_SESSION['room_type'] = $row['rmtype']; echo '&lt;div style="height: 300px;"&gt;'; echo '&lt;div style="float: left; width: 100px; margin-top: 15px; margin-left: 60px;"&gt;'; echo "&lt;img width=250 height=200 alt='Unable to View' src='" . $row["image"] . "'&gt;"; echo '&lt;/div&gt;'; echo '&lt;div class="well" style="float: right; width: 780px; margin-top: 5px;"&gt;'; echo '&lt;div style="float: right;"&gt;'; echo '&lt;/div&gt;'; echo '&lt;br /&gt;'; echo "&lt;label style='margin-left: px;'&gt;Number of rooms:"; echo "&lt;select name='select_no_rooms[]' value='" .$row['rmtype']." ' /&gt;"; echo "&lt;option&gt; &lt;/option&gt;"; if ($row['rmtype']=="Standard Room") { for ($x = 1; $x&lt;=$standard; $x++){ echo "&lt;option name='standard'&gt;$x&lt;/option&gt;";} } if ($row['rmtype']=="Deluxe Room") { for ($x = 1; $x&lt;=$deluxe; $x++){ echo "&lt;option name='deluxe'&gt;$x&lt;/option&gt;";} } if ($row['rmtype']=="Family Room") { for ($x = 1; $x&lt;=$family; $x++){ echo "&lt;option name='family'&gt;$x&lt;/option&gt;";} } if ($row['rmtype']=="Regular Room") { for ($x = 1; $x&lt;=$regular; $x++){ echo "&lt;option name='regular'&gt;$x&lt;/option&gt;";} } echo "&lt;/select&gt;"; } ?&gt; </code></pre> <p>This is the design of drop down,</p> <p><a href="http://i.stack.imgur.com/TBgBv.png" rel="nofollow"><img src="http://i.stack.imgur.com/TBgBv.png" alt="enter image description here"></a></p>
<p>add <code>[ ]</code> tag to name tag, so you will get your value in array.</p> <pre><code>&lt;option name='deluxe[]'&gt;$x&lt;/option&gt; </code></pre>
How to avoid re-importing modules and re-defining large object every time a script runs <p>This must have an answer but I cant find it. I am using a quite large python module called quippy. With this module one can define an intermolecular potential to use as a calculator in ASE like so: </p> <pre><code>from quippy import * from ase import atoms pot=Potential("Potential xml_label=gap_h2o_2b_ccsdt_3b_ccsdt",param_filename="gp.xml") some_structure.set_calculator(pot) </code></pre> <p>This is the beginning of a script. The problem is that the <code>import</code> takes about 3 seconds and <code>pot=Potential...</code> takes about 30 seconds with 100% cpu load. (I believe it is due to parsing a large ascii xml-file.) If I would be typing interactively I could keep the module imported and the potential defined, but when running the script it is done again on each run. </p> <p>Can I save the module and the potential object in memory/disk between runs? Maybe keep a python process idling and keeping those things in memory? Or run these lines in the interpreter and somehow call the rest of the script from there? </p> <p>Any approach is fine, but some help is be appreciated!</p>
<p>You can either use raw files or modules such as <code>pickle</code> to store data easily.</p> <pre><code>import cPickle as pickle from quippy import Potential try: # try previously calculated value with open('/tmp/pot_store.pkl') as store: pot = pickle.load(store) except OSError: # fall back to calculating it from scratch pot = quippy.Potential("Potential xml_label=gap_h2o_2b_ccsdt_3b_ccsdt",param_filename="gp.xml") with open('/tmp/pot_store.pkl', 'w') as store: pot = pickle.dump(pot, store) </code></pre> <p>There are various optimizations to this, e.g. checking whether your pickle file is older than the file generating it's value.</p>
R:How to create a boxplot with different types of data? <p>I am trying to get a picture like this: <a href="http://i.stack.imgur.com/fZYso.png" rel="nofollow"><img src="http://i.stack.imgur.com/fZYso.png" alt="enter image description here"></a></p> <p>In the picture, the parameters (a, b, and c of the triangle distribution ), their distributions, and confidence intervals of the parameters are based on the original datasets, and simulated ones are generated by parametric and nonparametric bootstrap. How to draw a picture like this in R? Can you give a simple example like this? Thank you very much!</p> <p>Here is my code.</p> <pre><code>x1&lt;-c(1300,541,441,35,278,167,276,159,126,170,251.3,155.84,187.01,850) x2&lt;-c(694,901,25,500,42,2.2,7.86,50) x3&lt;-c(2800,66.5,420,260,50,370,17) x4&lt;-c(12,3.9,10,28,84,138,6.65) y1&lt;-log10(x1) y2&lt;-log10(x2) y3&lt;-log10(x3) y4&lt;-log10(x4) #Part 1 (Input the data) In this part, I have calculated the parameters (a and b) and the confidence interval (a and b ) by MLE and PB-MLE with different data sets(x1 to x4) #To calculate the parameters (a and b) with data sets x1 y.n&lt;-length(y1) y.location&lt;-mean(y1) y.var&lt;-(y.n-1)/y.n*var(y1) y.scale&lt;-sqrt(3*y.var)/pi library(stats4) ll.logis&lt;-function(location=y.location,scale=y.scale){-sum(dlogis(y1,location,scale,log=TRUE))} fit.mle&lt;-mle(ll.logis,method="Nelder-Mead") a1_mle&lt;-coef(fit.mle)[1] b1_mle&lt;-coef(fit.mle)[2] summary(a1_mle)# To calculate the parameters (a) summary(b1_mle)# To calculate the parameters (b) confint(fit.mle)# To calculate the confidence interval (a and b ) by MLE # load fitdistrplus package for using fitdist function library(fitdistrplus) # fit logistic distribution using MLE method x1.logis &lt;- fitdist(y1, "logis", method="mle") A&lt;- bootdist(x1.logis, bootmethod="param", niter=1001) summary(A) # To calculate the parameters (a and b ) and the confidence interval (a and b ) by parametric bootstrap a &lt;- A$estim a1&lt;-c(a$location) b1&lt;-c(a$scale) #To calculate the parameters (a and b) with data sets x2 y.n&lt;-length(y2) y.location&lt;-mean(y2) y.var&lt;-(y.n-1)/y.n*var(y2) y.scale&lt;-sqrt(3*y.var)/pi library(stats4) ll.logis&lt;-function(location=y.location,scale=y.scale){-sum(dlogis(y2,location,scale,log=TRUE))} fit.mle&lt;-mle(ll.logis,method="Nelder-Mead") a2_mle&lt;-coef(fit.mle)[1] b2_mle&lt;-coef(fit.mle)[2] summary(a2_mle)# To calculate the parameters (a) summary(b2_mle)# To calculate the parameters (b) confint(fit.mle)# To calculate the confidence interval (a and b ) by MLE x2.logis &lt;- fitdist(y2, "logis", method="mle") B&lt;- bootdist(x2.logis, bootmethod="param", niter=1001) summary(B) b &lt;- B$estim a2&lt;-c(b$location) b2&lt;-c(b$scale) #To calculate the parameters (a and b) with data sets x3 y.n&lt;-length(y3) y.location&lt;-mean(y3) y.var&lt;-(y.n-1)/y.n*var(y3) y.scale&lt;-sqrt(3*y.var)/pi library(stats4) ll.logis&lt;-function(location=y.location,scale=y.scale){-sum(dlogis(y3,location,scale,log=TRUE))} fit.mle&lt;-mle(ll.logis,method="Nelder-Mead") a3_mle&lt;-coef(fit.mle)[1] b3_mle&lt;-coef(fit.mle)[2] summary(a3_mle)# To calculate the parameters (a) summary(b3_mle)# To calculate the parameters (b) confint(fit.mle)# To calculate the confidence interval (a and b ) by MLE x3.logis &lt;- fitdist(y3, "logis", method="mle") C &lt;- bootdist(x3.logis, bootmethod="param", niter=1001) summary(C) c&lt;- C$estim a3&lt;-c(c$location) b3&lt;-c(c$scale) #To calculate the parameters (a and b) with data sets x4 y.n&lt;-length(y4) y.location&lt;-mean(y4) y.var&lt;-(y.n-1)/y.n*var(y4) y.scale&lt;-sqrt(3*y.var)/pi library(stats4) ll.logis&lt;-function(location=y.location,scale=y.scale){-sum(dlogis(y4,location,scale,log=TRUE))} fit.mle&lt;-mle(ll.logis,method="Nelder-Mead") a4_mle&lt;-coef(fit.mle)[1] b4_mle&lt;-coef(fit.mle)[2] summary(a4_mle)# To calculate the parameters (a) summary(b4_mle)# To calculate the parameters (b) confint(fit.mle)# To calculate the confidence interval (a and b ) by MLE x4.logis &lt;- fitdist(y4, "logis", method="mle") D &lt;- bootdist(x4.logis, bootmethod="param", niter=1001) summary(D) d &lt;- D$estim a4&lt;-c(d$location) b4&lt;-c(d$scale) </code></pre> <p><a href="https://i.stack.imgur.com/HDok7.png" rel="nofollow"><img src="https://i.stack.imgur.com/HDok7.png" alt="enter image description here"></a></p>
<h1>UPDATE</h1> <p>Here's my attempt. It's sloppy but I think it does what you want to do. It would be great if other people can provide a better solution or make suggestions/comments.</p> <pre><code>x1&lt;-c(1300,541,441,35,278,167,276,159,126,170,251.3,155.84,187.01,850) x2&lt;-c(694,901,25,500,42,2.2,7.86,50) x3&lt;-c(2800,66.5,420,260,50,370,17) x4&lt;-c(12,3.9,10,28,84,138,6.65) y1&lt;-log10(x1) y2&lt;-log10(x2) y3&lt;-log10(x3) y4&lt;-log10(x4) library(stats4) library(fitdistrplus) library(reshape2) library(ggplot2) library(gridExtra) </code></pre> <p>First, put everything in a function so that you don't have to repeat yourself:</p> <pre><code>tmp &lt;- function(y){ y.n &lt;-length(y) y.location &lt;-mean(y) y.var&lt;-(y.n-1)/y.n*var(y) y.scale&lt;-sqrt(3*y.var)/pi ll.logis&lt;-function(location, scale){-sum(dlogis(y, location, scale,log=TRUE))} fit.mle&lt;-mle(ll.logis, start = list(location = y.location, scale = y.scale), method="Nelder-Mead") a_mle &lt;-coef(fit.mle)[1] # mean a b_mle &lt;-coef(fit.mle)[2] # mean b mle &lt;- confint(fit.mle) mle_df &lt;- as.data.frame(cbind(c("a", "b"), c(a_mle, b_mle), mle)) mle_df &lt;- setNames(mle_df, c("par","mean", "lower", "upper")) mle_df$method &lt;- "MLE" x.logis &lt;- fitdist(y, "logis", method="mle") A &lt;- bootdist(x.logis, bootmethod="param", niter=1001) a &lt;- A$estim a_pbmle &lt;-c(a$location) b_pbmle &lt;-c(a$scale) pbmle_df &lt;- data.frame(a_pbmle, b_pbmle) pbmle_df &lt;- setNames(pbmle_df, c("a", "b")) pbmle_df$method &lt;- "PB_MLE" return(list(MLE = mle_df, PBMLE = pbmle_df)) } </code></pre> <p>Then, using <code>lapply</code> you can apply function to <code>y1, y2, y3, y4</code> without writing down the same thing four times:</p> <pre><code>tmplist &lt;- list(y1, y2, y3, y4) tmplist2 &lt;- lapply(tmplist, tmp) </code></pre> <p>This part is sloppy but this is all I could think of:</p> <pre><code>mL &lt;- melt(tmplist2) mL$par[is.na(mL$par)] &lt;- mL$variable[is.na(mL$par)] mL &lt;- mL[,-6] for(i in 2:4){ mL[,i] &lt;- as.numeric(as.character(mL[,i])) } mL_a &lt;- subset(mL, par == "a") mL_b &lt;- subset(mL, par == "b") </code></pre> <p>Then, you graph it with this:</p> <pre><code>g1 &lt;- ggplot(mL_a) + geom_boxplot(aes(method, value)) + geom_point(aes(method, y = mean)) + geom_errorbar(aes(method, ymin = lower, ymax = upper)) + facet_grid(L1~.) + ylab("a") + coord_flip() g2 &lt;- g1 %+% mL_b + ylab("b") g1.a &lt;- g1 + theme(strip.text.y = element_blank()) g2.a &lt;- g2 + theme(axis.text.y = element_blank(), axis.ticks.y = element_blank(), axis.title.y = element_blank()) grid.arrange(g1.a, g2.a, nrow = 1, widths = c(1.2, 1)) </code></pre> <p>And you get </p> <p><a href="https://i.stack.imgur.com/ZTOoH.png" rel="nofollow"><img src="https://i.stack.imgur.com/ZTOoH.png" alt="result3"></a></p> <h1>OLD ANSWER</h1> <p>Oh.. I started working on this before you posted the data so I worked with a fake example that I made up. Here's my code:</p> <pre><code>sL &lt;- list() for(i in c("FW&amp;SW", "FW", "FW|S")){ sL[[i]] &lt;- rbind(data.frame(name = "MLE", a = runif(10, -2, 0), b = runif(10, 3, 5), c = runif(10, -1, 2)), data.frame(name = "P-B MLE", a = runif(10, -2, 0), b = runif(10, 3, 5), c = runif(10, -1, 2)), data.frame(name = "NP-B MLE", a = runif(10, -2, 0), b = runif(10, 3, 5), c = runif(10, -1, 2))) } library(reshape2) library(ggplot2); theme_set(theme_bw()) library(gridExtra) library(grid) mL &lt;- melt(sL) mL$L1 &lt;- factor(mL$L1, levels = c("FW|S", "FW", "FW&amp;SW")) g1 &lt;- ggplot(subset(mL, variable == "a"), aes(name, value)) + geom_boxplot() + coord_flip() + facet_grid(L1~.) + theme(panel.margin=grid::unit(0,"lines"), axis.title.y = element_blank(), plot.margin = unit(c(1,0.1,1,0), "cm")) g2 &lt;- g1 %+% subset(mL, variable == "b") g3 &lt;- g1 %+% subset(mL, variable == "c") text1 &lt;- textGrob("FW|S", gp=gpar(fontsize=12, fontface = "bold")) text2 &lt;- textGrob("FW", gp=gpar(fontsize=12)) text3 &lt;- textGrob("FW&amp;SW", gp=gpar(fontsize=12)) g1.a &lt;- g1 + ylab("a") + scale_y_continuous(breaks = c(-1.5, -1, -.5)) + theme(strip.text.y = element_blank()) g2.a &lt;- g2 + ylab("b") + scale_y_continuous(breaks = c(3.5, 4, 4.5)) + theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank(), strip.text.y = element_blank()) g3.a &lt;- g3 + ylab("c") + scale_y_continuous(breaks = c(-0.5, 0.5, 1.5)) + theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank()) grid.arrange(g1.a, g2.a, g3.a, nrow = 1, widths = c(1.5, 1, 1.1)) </code></pre> <p><a href="http://i.stack.imgur.com/UPMX8.png" rel="nofollow"><img src="http://i.stack.imgur.com/UPMX8.png" alt="result"></a></p> <p>Let me try working with the data that you provided...</p> <h1>EDIT (old edit with old data)</h1> <p>With the data you provided, I would just do this:</p> <pre><code>m &lt;- confint(fit.mle) MLE &lt;- as.data.frame(cbind(c(a,b),m)) PBMLE &lt;- as.data.frame(summary(b1)$CI) sL &lt;- list(MLE, PBMLE) methods &lt;- c("MLE", "P-B MLE") myList &lt;- lapply(1:2, function(i){ x &lt;- sL[[i]] colnames(x) &lt;- c("Median", "low","high") x &lt;- cbind(pars = c("a", "b"), method = methods[i], x) }) df &lt;- do.call("rbind", myList) ggplot(df, aes(x = method, y = Median)) + geom_point(size = 4) + geom_errorbar(aes(ymax = high, ymin = low)) + facet_wrap(~pars, scale = "free") + xlab("") + ylab("") </code></pre> <p><a href="http://i.stack.imgur.com/6xylk.png" rel="nofollow"><img src="http://i.stack.imgur.com/6xylk.png" alt="result 2"></a></p> <p>which is a lot simpler than what I have above. You should look into <code>facet_wrap</code> and <code>grid_arrange</code>.</p>
What is the Visual basic version of Signalr Proxy.On Method <p>What is the Visual basic equivalent of this code for a Signalr Proxy Hub?</p> <pre><code> proxy.On&lt;ChatMessage&gt;("broadcastMessage", OnMessage); </code></pre> <p>I have Tried..</p> <pre><code> proxy.On(Of ChatMessage)("broadcastMessage", OnMessage) </code></pre> <p>But Get an error stating: Expression does not produce a value.</p> <p>Also Tried..</p> <pre><code>proxy.On(Of ChatMessage)("broadcastMessage", Sub() OnMessage()) </code></pre> <p>But it never calls my method because it takes a parameter of ChatMessage Object.</p> <pre><code>Private Sub OnMessage(Msg As ChatMessage) Dim NewMsg As ChatMessage = Msg End Sub </code></pre> <p>Any help would be much appreciated.</p>
<p>Need to use 'addressOf' in place of 'Sub()' for this line.</p> <pre><code>proxy.On(Of ChatMessage)("broadcastMessage", Sub() OnMessage()) </code></pre> <p>Like...</p> <pre><code>proxy.On(Of ChatMessage)("broadcastMessage", AddressOf OnMessage) </code></pre>
GitLabCE mishandles results of multiple external Jenkins jobs - a bug or not supported? <p>I wish to replicate a workflow on GitLabCE that I also use successfully with GitHub. I am using GitLabCE 8.11.5.</p> <p>I have Jenkins working with the <a href="https://github.com/jenkinsci/gitlab-plugin" rel="nofollow">GitLab-plugin</a> via a webhook for each job. Normally, when a Merge Request is created, or updated, a Jenkins job is triggered by the hook and the MR will <em>wait</em> for that job to complete before allowing a reviewer to complete the merge.</p> <p>What I want to achieve is for this mechanism to work for several <em>parallel</em> and independent Jenkins jobs. For example, one job to compile the source, one to run static analysis on the source, another to build docs. The way I have it set up, using a separate webhook configuration for each job, results in all the jobs being triggered correctly, but there's an issue with the way GitLab handles each job's result which can (and does) result in premature merge.</p> <h2>Example</h2> <p>With GitLab's current behaviour, it is not clear to a reviewer that subsequent results may be pending, as this example shows. An premature merge is a likely result.</p> <p>For simplicity I have only <em>two</em> jobs working in the following discussion. The jobs run in parallel however the second is faster to complete than the first, and when it reports its status to GitLab, <strong>GitLab treats this as a "retry" of the first job, and incorrectly allows the MR to be merged early</strong>. When the second job completes, the result appears in the MR's Discussion, however by then the MR may have already been merged. What I would expect to see is GitLab waiting for <em>both</em> jobs to complete, and only allowing the merge once <em>both</em> are successful.</p> <h3>MR Created</h3> <p>A simple MR is created. GitLab posts to two webhooks, and both Jenkins jobs are run in parallel.</p> <p>However the Builds tab shows only one entry. The hyperlink points to the <em>second</em> job:</p> <p><a href="http://i.stack.imgur.com/gJN64.png" rel="nofollow"><img src="http://i.stack.imgur.com/gJN64.png" alt="builds - building"></a></p> <h3>Fastest Job Complete</h3> <p>Once the second (fastest) job has completed, the Builds tab only shows this - there's no indication here that the first (slower) job is still running:</p> <p><a href="http://i.stack.imgur.com/MHRgz.png" rel="nofollow"><img src="http://i.stack.imgur.com/MHRgz.png" alt="builds one complete"></a></p> <p>Also, the merge button is now green:</p> <p><a href="http://i.stack.imgur.com/AWzls.png" rel="nofollow"><img src="http://i.stack.imgur.com/AWzls.png" alt="merge button"></a></p> <h3>Both Jobs Complete</h3> <p>After both jobs have completed, the Builds tab now shows:</p> <p><a href="http://i.stack.imgur.com/IiLzm.png" rel="nofollow"><img src="http://i.stack.imgur.com/IiLzm.png" alt="builds both complete"></a></p> <p>As you can see, the first job was marked as "retried", although in fact both those hyperlinks (#335, #336) now point to separate <em>and correct</em> Jenkins jobs. However 336 is clearly not a "retry" of 335.</p> <p>The order of this behaviour may be affected by the order I defined the web hooks. I have not investigated this further.</p> <h3>Conclusion</h3> <p>So my question is - does GitLab support multiple independent external builds as part of its MR process? If so, how do I modify the configuration so that GitLab does not treat the result of the second job as the result of the first? Or is this a bug?</p> <p>If GitLab does not support multiple external builds (which would be unfortunate because it works really nicely on GitHub), I could perhaps use Jenkins to trigger all parallel jobs and report back a final status when they have all completed. Does anyone know of a suitable Jenkins plugin and configuration for this workflow?</p> <h3>Disclosure</h3> <p>I have posted a variant of this question to the GitLab troubleshooting forum. I will update both with any responses to ensure consistency for anyone else looking for a similar solution.</p>
<p>Answering my own question:</p> <p>I believe this behaviour is caused by the configuration of the GitLab Plugin in Jenkins. Each job has a "Publish build status to GitLab commit" post-build action. This has a field named "Build name", and if this string is not unique amongst all the builds in the pipeline, GitLab gets confused. By changing these names to unique strings, the Merge button only becomes available once all jobs have completed successfully (provided no votes have been placed).</p> <p>However, I still see only one entry in the Builds tab, until the first job has completed successfully, and then both appear (one as running, one as passed). Once the second job has completed successfully, both appear as passed. However this is minor and does not affect the review or merging process.</p>
How do I mass update a field for models in an array? <p>I’m using Rails 4.2.7. How do I mass update a field of an array of my models without actually saving that information to the database? I tried</p> <pre><code>my_objcts_arr.update_all(my_object: my_object) </code></pre> <p>but this results in the error</p> <pre><code>NoMethodError: undefined method `update_all' for #&lt;Array:0x007f80a81cae50&gt; </code></pre> <p>I realize I could iteraet over the array and update each object individually, but I figure there's a slicker, one-line way in Ruby taht I'm not aware of.</p>
<p><code>update_all</code> needs to be called on a class level active record model/relation, ie User or TaxReturn. Here is one somewhat related <a href="http://stackoverflow.com/questions/4912510/rails-3-activerecord-the-best-way-to-mass-update-a-single-field-for-all-the">SO post showing some examples</a>, and here is <a href="http://apidock.com/rails/v4.2.1/ActiveRecord/Relation/update_all" rel="nofollow">the api doc for update_all</a>. It will send the UPDATE directly to the db (it is an active record method, after all), so it is not what you want.</p> <p>You're best off iterating and updating the value yourself <a href="https://ruby-doc.org/core-2.2.0/Array.html#method-i-collect" rel="nofollow">with collect</a> or something similar, which is only one line.</p> <pre><code>foo = [{:a=&gt;"a", :b=&gt;"b"}, {:a=&gt;"A", :b=&gt;"B:}] // =&gt; [{:a=&gt;"a", :b=&gt;"b"}, {:a=&gt;"A", :b=&gt;"B"}] foo.collect{|x| x[:a]="C"} // =&gt; ["C", "C"] foo // =&gt; [{:a=&gt;"C", :b=&gt;"b"}, {:a=&gt;"C", :b=&gt;"B"}] </code></pre>
How to make OneTimeSetup failures fail tests in TeamCity <p>I have just encountered a scenario where a <code>TestFixture</code>'s <code>OneTimeSetup</code> method has failed, yet TeamCity has reported all the tests as passed.</p> <p>I can see in the log that TC is reporting 14 red lines of text, once for each of the 14 tests in the fixture: </p> <blockquote> <p>[Step 1/1] OneTimeSetUp: &lt;...failure text...></p> </blockquote> <p>The tests are being run with <code>[Parallelizable(ParallelScope.Fixtures)]</code> attribute, which may be related - I don't know.</p> <p>At the end of the log, I can see a summary (not in red) summarising again the 14 failures.</p> <blockquote> <p>[11:26:48][Step 1/1] Errors and Failures</p> <p>[11:26:48][Step 1/1] </p> <p>[11:26:48][Step 1/1] 1) Failed : blah blah blah ...</p> </blockquote> <p>BUT the build does not fail, and in fact the tests do run successfully.</p> <p>We are using TeamCity 10.0.2 (build 42234) and "NUnit 3.0" (as per TC setting - we are using 3.2.1 in our actual project)</p>
<p>There was a bug in NUnit 3.2.1, where failures in a <code>OneTimeSetUp</code> didn't actually fail the test suite - meaning tools such as TeamCity would have no way to detect the failure.</p> <p>This was fixed in NUnit 3.4 - upgrading to the latest NUnit should solve your problem. The GitHub issue, for reference: <a href="https://github.com/nunit/nunit/issues/1379" rel="nofollow">https://github.com/nunit/nunit/issues/1379</a></p>
Javascript: Adding a property to an array of objects <p>I have an array of objects as follows:</p> <pre><code>var myarray=[{"name":"John","address":"home"},{"name":"Peter","address":"home"}] </code></pre> <p>and I would like to run a function to add a property to the array as follows:</p> <pre><code>[{"name":"John","address":"home","collection":"friend"}, {"name":"Peter","address":"home","collection":"friend"}] </code></pre> <p>I have tried doing this:</p> <pre><code>myarray=myarray.map(function (err, myarray){ myarray.collection="friend"; return myarray; } console.log(myarray) </code></pre> <p>But the console continues to return this:</p> <pre><code>[{0},{1}] </code></pre> <p>Can anyone help me? Thank you</p>
<p>Your code is not adding the property to the contents of the array. The values of the array are given as the first parameter to the callback function (the second parameter is an index, and not the array itself—that's the third parameter). Simply assign the new property to the first parameter of the callback function, rather than the second one.</p> <p><em>Edit</em> - As @zerkms points out, however, if you're looking to update the current array rather than generate a new array, <code>map</code> is probably not best solution here. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" rel="nofollow"><code>forEach</code></a> provides a method for iterating over the current array, and modifying each of its values (which is what you're doing). This would looks omething like this:</p> <pre><code>myarray.forEach(function(value) { value.collection = "friend"; }); </code></pre> <hr> <p>As you'll notice in the documentation for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="nofollow"><code>.map</code></a>, the callback function returns the new value that will appear in the new array that is generated by <code>map</code>; if you're changing the current array in place (i.e. by modifying the properties of its contents), there's no need to return anything.</p> <pre><code>myarray.map(function(value) { value.collection = "friend"; }); </code></pre> <p>Also note that both <code>map</code> and <code>forEach</code> are methods, so you need to close the method invocation with <code>)</code>.</p>
Does OpenCV with CUDA require SSE4.2 on Windows? <p>I can't find any good information on compiling OpenCV. I've tried nearly everything and I'm stuck. My question is, does OpenCV require SSE4.2. That is the only thing I can think of.</p>
<p>OpenCV will optionally compile for whatever level of SSE is detected by cmake. This is independent of building CUDA support</p>
Google Drive API PHP: Files.get returns null value <p>I am creating an application that integrates with Google Drive API (version 3) in order for it to find a file inside a named folder by way of user input and then to get the web content link for that file. My application is contacting a service account where my application's files will be stored and getting the link. The only problem is when I use the code shown below, it returns the output shown below which is all NULL except for a few fields. What am I doing wrong?</p> <p><strong>Code that is causing the problem:</strong></p> <pre><code>&lt;?php require_once("./vendor/autoload.php"); putenv('GOOGLE_APPLICATION_CREDENTIALS=service-account.json'); $client = new Google_Client(); $client-&gt;useApplicationDefaultCredentials(); $client-&gt;setScopes(implode(' ', array(Google_Service_Drive::DRIVE))); $service = new Google_Service_Drive($client); $optParams = array("q" =&gt; "'0BxNR85wn9MERczRqbkU0LTBQdUk' in parents"); $results = $service-&gt;files-&gt;listFiles($optParams); if(count($results-&gt;getFiles()) == 0){ echo "No files found."; }else{ echo "Files found.&lt;br&gt;"; foreach($results-&gt;getFiles() as $file){ if($file-&gt;getId() != "0B4C3vGWHN-Wgc3RhcnRlcl9maWxl"){ echo $file-&gt;getId() . "&lt;br&gt;"; $content = $service-&gt;files-&gt;get($file-&gt;getId()); $filedata = $service-&gt;files-&gt;get($file-&gt;getId()); echo "&lt;pre&gt;"; var_dump($filedata); echo "&lt;/pre&gt;"; } } } ?&gt; </code></pre> <p><strong>The codes output:</strong></p> <pre><code>Files found. 1L61iP4mrc0HyVmHhLB4TFz-1revFg2l6cdPQDh7OLUY object(Google_Service_Drive_DriveFile)#68 (56) { ["collection_key":protected]=&gt; string(6) "spaces" ["appProperties"]=&gt; NULL ["capabilitiesType":protected]=&gt; string(42) "Google_Service_Drive_DriveFileCapabilities" ["capabilitiesDataType":protected]=&gt; string(0) "" ["contentHintsType":protected]=&gt; string(42) "Google_Service_Drive_DriveFileContentHints" ["contentHintsDataType":protected]=&gt; string(0) "" ["createdTime"]=&gt; NULL ["description"]=&gt; NULL ["explicitlyTrashed"]=&gt; NULL ["fileExtension"]=&gt; NULL ["folderColorRgb"]=&gt; NULL ["fullFileExtension"]=&gt; NULL ["headRevisionId"]=&gt; NULL ["iconLink"]=&gt; NULL ["id"]=&gt; string(44) "1L61iP4mrc0HyVmHhLB4TFz-1revFg2l6cdPQDh7OLUY" ["imageMediaMetadataType":protected]=&gt; string(48) "Google_Service_Drive_DriveFileImageMediaMetadata" ["imageMediaMetadataDataType":protected]=&gt; string(0) "" ["isAppAuthorized"]=&gt; NULL ["kind"]=&gt; string(10) "drive#file" ["lastModifyingUserType":protected]=&gt; string(25) "Google_Service_Drive_User" ["lastModifyingUserDataType":protected]=&gt; string(0) "" ["md5Checksum"]=&gt; NULL ["mimeType"]=&gt; string(36) "application/vnd.google-apps.document" ["modifiedByMeTime"]=&gt; NULL ["modifiedTime"]=&gt; NULL ["name"]=&gt; string(17) "Untitled document" ["originalFilename"]=&gt; NULL ["ownedByMe"]=&gt; NULL ["ownersType":protected]=&gt; string(25) "Google_Service_Drive_User" ["ownersDataType":protected]=&gt; string(5) "array" ["parents"]=&gt; NULL ["permissionsType":protected]=&gt; string(31) "Google_Service_Drive_Permission" ["permissionsDataType":protected]=&gt; string(5) "array" ["properties"]=&gt; NULL ["quotaBytesUsed"]=&gt; NULL ["shared"]=&gt; NULL ["sharedWithMeTime"]=&gt; NULL ["sharingUserType":protected]=&gt; string(25) "Google_Service_Drive_User" ["sharingUserDataType":protected]=&gt; string(0) "" ["size"]=&gt; NULL ["spaces"]=&gt; NULL ["starred"]=&gt; NULL ["thumbnailLink"]=&gt; NULL ["trashed"]=&gt; NULL ["version"]=&gt; NULL ["videoMediaMetadataType":protected]=&gt; string(48) "Google_Service_Drive_DriveFileVideoMediaMetadata" ["videoMediaMetadataDataType":protected]=&gt; string(0) "" ["viewedByMe"]=&gt; NULL ["viewedByMeTime"]=&gt; NULL ["viewersCanCopyContent"]=&gt; NULL ["webContentLink"]=&gt; NULL ["webViewLink"]=&gt; NULL ["writersCanShare"]=&gt; NULL ["internal_gapi_mappings":protected]=&gt; array(0) { } ["modelData":protected]=&gt; array(0) { } ["processed":protected]=&gt; array(0) { } } 0BxNR85wn9MERUjRaYURVdXVhMlk object(Google_Service_Drive_DriveFile)#79 (56) { ["collection_key":protected]=&gt; string(6) "spaces" ["appProperties"]=&gt; NULL ["capabilitiesType":protected]=&gt; string(42) "Google_Service_Drive_DriveFileCapabilities" ["capabilitiesDataType":protected]=&gt; string(0) "" ["contentHintsType":protected]=&gt; string(42) "Google_Service_Drive_DriveFileContentHints" ["contentHintsDataType":protected]=&gt; string(0) "" ["createdTime"]=&gt; NULL ["description"]=&gt; NULL ["explicitlyTrashed"]=&gt; NULL ["fileExtension"]=&gt; NULL ["folderColorRgb"]=&gt; NULL ["fullFileExtension"]=&gt; NULL ["headRevisionId"]=&gt; NULL ["iconLink"]=&gt; NULL ["id"]=&gt; string(28) "0BxNR85wn9MERUjRaYURVdXVhMlk" ["imageMediaMetadataType":protected]=&gt; string(48) "Google_Service_Drive_DriveFileImageMediaMetadata" ["imageMediaMetadataDataType":protected]=&gt; string(0) "" ["isAppAuthorized"]=&gt; NULL ["kind"]=&gt; string(10) "drive#file" ["lastModifyingUserType":protected]=&gt; string(25) "Google_Service_Drive_User" ["lastModifyingUserDataType":protected]=&gt; string(0) "" ["md5Checksum"]=&gt; NULL ["mimeType"]=&gt; string(10) "image/jpeg" ["modifiedByMeTime"]=&gt; NULL ["modifiedTime"]=&gt; NULL ["name"]=&gt; string(76) "Copy of 3f86195896e5d28d5e9492eb0415544049c4a49467d3534d3fa2e5d52a2636e0.jpg" ["originalFilename"]=&gt; NULL ["ownedByMe"]=&gt; NULL ["ownersType":protected]=&gt; string(25) "Google_Service_Drive_User" ["ownersDataType":protected]=&gt; string(5) "array" ["parents"]=&gt; NULL ["permissionsType":protected]=&gt; string(31) "Google_Service_Drive_Permission" ["permissionsDataType":protected]=&gt; string(5) "array" ["properties"]=&gt; NULL ["quotaBytesUsed"]=&gt; NULL ["shared"]=&gt; NULL ["sharedWithMeTime"]=&gt; NULL ["sharingUserType":protected]=&gt; string(25) "Google_Service_Drive_User" ["sharingUserDataType":protected]=&gt; string(0) "" ["size"]=&gt; NULL ["spaces"]=&gt; NULL ["starred"]=&gt; NULL ["thumbnailLink"]=&gt; NULL ["trashed"]=&gt; NULL ["version"]=&gt; NULL ["videoMediaMetadataType":protected]=&gt; string(48) "Google_Service_Drive_DriveFileVideoMediaMetadata" ["videoMediaMetadataDataType":protected]=&gt; string(0) "" ["viewedByMe"]=&gt; NULL ["viewedByMeTime"]=&gt; NULL ["viewersCanCopyContent"]=&gt; NULL ["webContentLink"]=&gt; NULL ["webViewLink"]=&gt; NULL ["writersCanShare"]=&gt; NULL ["internal_gapi_mappings":protected]=&gt; array(0) { } ["modelData":protected]=&gt; array(0) { } ["processed":protected]=&gt; array(0) { } } 0BxNR85wn9MERWUR1TEh6ckROUGM object(Google_Service_Drive_DriveFile)#74 (56) { ["collection_key":protected]=&gt; string(6) "spaces" ["appProperties"]=&gt; NULL ["capabilitiesType":protected]=&gt; string(42) "Google_Service_Drive_DriveFileCapabilities" ["capabilitiesDataType":protected]=&gt; string(0) "" ["contentHintsType":protected]=&gt; string(42) "Google_Service_Drive_DriveFileContentHints" ["contentHintsDataType":protected]=&gt; string(0) "" ["createdTime"]=&gt; NULL ["description"]=&gt; NULL ["explicitlyTrashed"]=&gt; NULL ["fileExtension"]=&gt; NULL ["folderColorRgb"]=&gt; NULL ["fullFileExtension"]=&gt; NULL ["headRevisionId"]=&gt; NULL ["iconLink"]=&gt; NULL ["id"]=&gt; string(28) "0BxNR85wn9MERWUR1TEh6ckROUGM" ["imageMediaMetadataType":protected]=&gt; string(48) "Google_Service_Drive_DriveFileImageMediaMetadata" ["imageMediaMetadataDataType":protected]=&gt; string(0) "" ["isAppAuthorized"]=&gt; NULL ["kind"]=&gt; string(10) "drive#file" ["lastModifyingUserType":protected]=&gt; string(25) "Google_Service_Drive_User" ["lastModifyingUserDataType":protected]=&gt; string(0) "" ["md5Checksum"]=&gt; NULL ["mimeType"]=&gt; string(10) "image/jpeg" ["modifiedByMeTime"]=&gt; NULL ["modifiedTime"]=&gt; NULL ["name"]=&gt; string(68) "3f86195896e5d28d5e9492eb0415544049c4a49467d3534d3fa2e5d52a2636e0.jpg" ["originalFilename"]=&gt; NULL ["ownedByMe"]=&gt; NULL ["ownersType":protected]=&gt; string(25) "Google_Service_Drive_User" ["ownersDataType":protected]=&gt; string(5) "array" ["parents"]=&gt; NULL ["permissionsType":protected]=&gt; string(31) "Google_Service_Drive_Permission" ["permissionsDataType":protected]=&gt; string(5) "array" ["properties"]=&gt; NULL ["quotaBytesUsed"]=&gt; NULL ["shared"]=&gt; NULL ["sharedWithMeTime"]=&gt; NULL ["sharingUserType":protected]=&gt; string(25) "Google_Service_Drive_User" ["sharingUserDataType":protected]=&gt; string(0) "" ["size"]=&gt; NULL ["spaces"]=&gt; NULL ["starred"]=&gt; NULL ["thumbnailLink"]=&gt; NULL ["trashed"]=&gt; NULL ["version"]=&gt; NULL ["videoMediaMetadataType":protected]=&gt; string(48) "Google_Service_Drive_DriveFileVideoMediaMetadata" ["videoMediaMetadataDataType":protected]=&gt; string(0) "" ["viewedByMe"]=&gt; NULL ["viewedByMeTime"]=&gt; NULL ["viewersCanCopyContent"]=&gt; NULL ["webContentLink"]=&gt; NULL ["webViewLink"]=&gt; NULL ["writersCanShare"]=&gt; NULL ["internal_gapi_mappings":protected]=&gt; array(0) { } ["modelData":protected]=&gt; array(0) { } ["processed":protected]=&gt; array(0) { } } </code></pre> <p>Right now it is just a bunch of test code to see what that files get method is going to return, which at the moment is a lot of null, so right now don't expect much functionality. The code below isn't supposed to download anything yet, it's just the debugging. So, what I need to know is, how can I access the webContentLink property of the 3 files this application has found from the API?</p>
<p>Please <a href="https://developers.google.com/drive/v3/web/migration" rel="nofollow">read</a> this Drive API V3 migration documentation.</p> <blockquote> <p>Full resources are no longer returned by default. Use the fields query parameter to request specific fields to be returned. If left unspecified only a subset of commonly used fields are returned.</p> </blockquote>
AsyncTestCompleter Browserify Angular2 HTTP Mock Test <p>I am about to get started with Angular 2 tests, I am pretty new to Angular 2 and got stuck with testing.</p> <p>I am following the testing guide: <a href="https://angular.io/docs/ts/latest/guide/testing.html" rel="nofollow">https://angular.io/docs/ts/latest/guide/testing.html</a></p> <pre><code> &gt; TimesheetCrusher@0.0.5 test C:\Users\Toby\WebstormProjects\timesheetCrusher &gt; tsc &amp;&amp; concurrently "tsc -w" "karma start karma.conf.js" [1] 10 10 2016 09:11:27.801:DEBUG [plugin]: Loading inlined plugin (defining framework:jasmine). [1] 10 10 2016 09:11:27.807:DEBUG [plugin]: Loading inlined plugin (defining launcher:Chrome, launcher:ChromeCanary, launcher:Dartium, test). [1] 10 10 2016 09:11:27.808:DEBUG [plugin]: Loading inlined plugin (defining reporter:html). [1] 10 10 2016 09:11:27.808:DEBUG [plugin]: Loading inlined plugin (defining bro, framework:browserify, preprocessor:browserify, preprocessor:browserify-bundle, preprocess). [1] 10 10 2016 09:11:27.808:DEBUG [plugin]: Loading inlined plugin (defining launcher:Chrome_travis_ci). [1] 10 10 2016 09:11:27.823:DEBUG [framework.browserify]: created browserify bundle: C:\Users\Toby\AppData\Local\Temp\a3ebde98982e7b28c9d1624786c469a4.browserify [1] 10 10 2016 09:11:27.856:DEBUG [framework.browserify]: no matching preprocessed file was found, defaulting to prepend [1] 10 10 2016 09:11:27.857:DEBUG [framework.browserify]: add bundle to config.files at position 0 [1] 10 10 2016 09:11:27.875:DEBUG [web-server]: Instantiating middleware [1] 10 10 2016 09:11:27.907:DEBUG [reporter]: Trying to load reporter: html [1] 10 10 2016 09:11:27.909:DEBUG [reporter]: Trying to load color-version of reporter: html (html_color) [1] 10 10 2016 09:11:27.909:DEBUG [reporter]: Couldn't load color-version. [1] 10 10 2016 09:11:29.104:WARN [watcher]: Pattern "C:/Users/Toby/WebstormProjects/timesheetCrusher/systemjs.config.extras.js" does not match any file. [1] 10 10 2016 09:11:29.118:WARN [watcher]: Pattern "C:/Users/Toby/WebstormProjects/timesheetCrusher/dist/src/**/*.html" does not match any file. [1] 10 10 2016 09:11:29.123:WARN [watcher]: Pattern "C:/Users/Toby/WebstormProjects/timesheetCrusher/dist/src/**/*.css" does not match any file. [1] 10 10 2016 09:11:29.522:DEBUG [framework.browserify]: building bundle [1] 10 10 2016 09:11:29.921:DEBUG [framework.browserify]: updating dist\test\backand\backand-rest.service.spec.js in bundle [1] 10 10 2016 09:11:30.627:DEBUG [framework.browserify]: bundling [0] 9:11:30 AM - Compilation complete. Watching for file changes. [1] 10 10 2016 09:11:31.762:ERROR [framework.browserify]: bundle error [1] 10 10 2016 09:11:31.762:ERROR [framework.browserify]: [1] C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\@angular\core\testing\async_test_completer.js:11 [1] export var AsyncTestCompleter = (function () { [1] ^ [1] ParseError: 'import' and 'export' may appear only with 'sourceType: module' [1] 10 10 2016 09:11:31.800:WARN [karma]: Port 9876 in use [1] 10 10 2016 09:11:31.801:INFO [karma]: Karma v1.3.0 server started at http://localhost:9877/ [1] 10 10 2016 09:11:31.802:INFO [launcher]: Launching browser Chrome with unlimited concurrency [1] 10 10 2016 09:11:31.833:INFO [launcher]: Starting browser Chrome [1] 10 10 2016 09:11:31.833:DEBUG [temp-dir]: Creating temp dir at C:\Users\Toby\AppData\Local\Temp\karma-98045299 [1] 10 10 2016 09:11:31.834:DEBUG [launcher]: C:\Program Files (x86)\Google\Chrome\Application\chrome.exe --user-data-dir=C:\Users\Toby\AppData\Local\Temp\karma-98045299 --no-default-browser-check --no-first-run --disable-default-apps --disable-popup-blocking --disable-translate --disable-background-timer-throttling http://localhost:9877/?id=98045299 [1] 10 10 2016 09:11:33.249:DEBUG [web-server]: serving: C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\karma\static/client.html [1] 10 10 2016 09:11:33.278:DEBUG [web-server]: serving: C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\karma\static/karma.js [1] 10 10 2016 09:11:33.463:DEBUG [karma]: A browser has connected on socket /#xhFGIxQD4-dw1xNtAAAA [1] 10 10 2016 09:11:33.467:DEBUG [web-server]: serving: C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\karma\static/favicon.ico [1] 10 10 2016 09:11:33.483:DEBUG [web-server]: upgrade /socket.io/?EIO=3&amp;transport=websocket&amp;sid=xhFGIxQD4-dw1xNtAAAA [1] 10 10 2016 09:11:33.484:DEBUG [proxy]: NOT upgrading proxyWebSocketRequest /socket.io/?EIO=3&amp;transport=websocket&amp;sid=xhFGIxQD4-dw1xNtAAAA [1] 10 10 2016 09:11:33.524:INFO [Chrome 53.0.2785 (Windows 10 0.0.0)]: Connected on socket /#xhFGIxQD4-dw1xNtAAAA with id 98045299 [1] 10 10 2016 09:11:33.525:DEBUG [launcher]: Chrome (id 98045299) captured in 1.722 secs [1] 10 10 2016 09:11:33.544:DEBUG [middleware:karma]: custom files null null [1] 10 10 2016 09:11:33.544:DEBUG [middleware:karma]: Serving static request /context.html [1] 10 10 2016 09:11:33.557:DEBUG [web-server]: serving: C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\karma\static/context.html [1] 10 10 2016 09:11:33.571:DEBUG [web-server]: serving: C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\karma\static/context.js [1] 10 10 2016 09:11:33.583:DEBUG [middleware:source-files]: Requesting /absoluteC:/Users/Toby/AppData/Local/Temp/a3ebde98982e7b28c9d1624786c469a4.browserify?59c06c9eba4f4adc27dc229cfaebba395247ee16 / [1] 10 10 2016 09:11:33.583:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/AppData/Local/Temp/a3ebde98982e7b28c9d1624786c469a4.browserify [1] 10 10 2016 09:11:33.585:DEBUG [web-server]: serving (cached): C:/Users/Toby/AppData/Local/Temp/a3ebde98982e7b28c9d1624786c469a4.browserify [1] 10 10 2016 09:11:33.589:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/boot.js?945a38bf4e45ad2770eb94868231905a04a0bd3e / [1] 10 10 2016 09:11:33.589:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/karma-jasmine/lib/boot.js [1] 10 10 2016 09:11:33.590:DEBUG [middleware:source-files]: Requesting /base/node_modules/karma-jasmine/lib/adapter.js?1e4f995124c2f01998fd4f3e16ace577bf155ba9 / [1] 10 10 2016 09:11:33.590:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/karma-jasmine/lib/adapter.js [1] 10 10 2016 09:11:33.592:DEBUG [middleware:source-files]: Requesting /base/node_modules/systemjs/dist/system.src.js?ce47c157d0451bc324d5039dfc7b04fa1cf0925d / [1] 10 10 2016 09:11:33.593:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/systemjs/dist/system.src.js [1] 10 10 2016 09:11:33.595:DEBUG [middleware:source-files]: Requesting /base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?391e45351df9ee35392d2e5cb623221a969fc009 / [1] 10 10 2016 09:11:33.595:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/jasmine-core/lib/jasmine-core/jasmine.js [1] 10 10 2016 09:11:33.595:DEBUG [middleware:source-files]: Requesting /base/node_modules/core-js/client/shim.js?23bcf04b0fcefe4c6fe3d641e6c1c6fd2a525332 / [1] 10 10 2016 09:11:33.595:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/core-js/client/shim.js [1] 10 10 2016 09:11:33.596:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/karma-jasmine/lib/boot.js [1] 10 10 2016 09:11:33.597:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/karma-jasmine/lib/adapter.js [1] 10 10 2016 09:11:33.598:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/systemjs/dist/system.src.js [1] 10 10 2016 09:11:33.601:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/jasmine-core/lib/jasmine-core/jasmine.js [1] 10 10 2016 09:11:33.603:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/core-js/client/shim.js [1] 10 10 2016 09:11:33.607:DEBUG [middleware:source-files]: Requesting /base/node_modules/reflect-metadata/Reflect.js?dda56e9eda58525388f2f12f0e03222eea4db7ec / [1] 10 10 2016 09:11:33.608:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/reflect-metadata/Reflect.js [1] 10 10 2016 09:11:33.608:DEBUG [middleware:source-files]: Requesting /base/node_modules/zone.js/dist/zone.js?c35727d0e64913b5669320b167e496fc94fc6928 / [1] 10 10 2016 09:11:33.609:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/zone.js [1] 10 10 2016 09:11:33.609:DEBUG [middleware:source-files]: Requesting /base/node_modules/zone.js/dist/long-stack-trace-zone.js?190d11155f82a27dfb07231dd5d843be81752df0 / [1] 10 10 2016 09:11:33.609:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/long-stack-trace-zone.js [1] 10 10 2016 09:11:33.611:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/reflect-metadata/Reflect.js [1] 10 10 2016 09:11:33.612:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/zone.js [1] 10 10 2016 09:11:33.614:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/long-stack-trace-zone.js [1] 10 10 2016 09:11:33.615:DEBUG [middleware:source-files]: Requesting /base/node_modules/zone.js/dist/proxy.js?13037d720197b33695136adbb068be1826fe1bda / [1] 10 10 2016 09:11:33.615:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/proxy.js [1] 10 10 2016 09:11:33.616:DEBUG [middleware:source-files]: Requesting /base/node_modules/zone.js/dist/sync-test.js?e9499c7853b5f42755015c38ee71b41d2b3a4c2a / [1] 10 10 2016 09:11:33.616:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/sync-test.js [1] 10 10 2016 09:11:33.619:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/proxy.js [1] 10 10 2016 09:11:33.626:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/sync-test.js [1] 10 10 2016 09:11:33.629:DEBUG [middleware:source-files]: Requesting /base/node_modules/zone.js/dist/jasmine-patch.js?18f8bcddbcafc03a52e8f190726a85581b4a3c10 / [1] 10 10 2016 09:11:33.629:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/jasmine-patch.js [1] 10 10 2016 09:11:33.631:DEBUG [middleware:source-files]: Requesting /base/node_modules/zone.js/dist/async-test.js?dfbb53d215a0f5fe064360706cf52ba5c0f40c30 / [1] 10 10 2016 09:11:33.632:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/async-test.js [1] 10 10 2016 09:11:33.632:DEBUG [middleware:source-files]: Requesting /base/node_modules/zone.js/dist/fake-async-test.js?0337d6818a2aefcefb40ab4e513943f5ff3e9fb0 / [1] 10 10 2016 09:11:33.632:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/fake-async-test.js [1] 10 10 2016 09:11:33.632:DEBUG [middleware:source-files]: Requesting /base/karma-test-shim.js?a8b46428653c0dfd7ef5d35dfe6b8633a9821984 / [1] 10 10 2016 09:11:33.633:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/karma-test-shim.js [1] 10 10 2016 09:11:33.635:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/jasmine-patch.js [1] 10 10 2016 09:11:33.638:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/async-test.js [1] 10 10 2016 09:11:33.639:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/node_modules/zone.js/dist/fake-async-test.js [1] 10 10 2016 09:11:33.646:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/karma-test-shim.js [1] 10 10 2016 09:11:33.647:DEBUG [middleware:source-files]: Requesting /base/dist/test/backand/backand-rest.service.spec.js?0d2f3c79f250240de04a539f2d50e1d95d102562 / [1] 10 10 2016 09:11:33.647:DEBUG [middleware:source-files]: Fetching C:/Users/Toby/WebstormProjects/timesheetCrusher/dist/test/backand/backand-rest.service.spec.js [1] 10 10 2016 09:11:33.649:DEBUG [web-server]: serving (cached): C:/Users/Toby/WebstormProjects/timesheetCrusher/dist/test/backand/backand-rest.service.spec.js [1] Chrome 53.0.2785 (Windows 10 0.0.0) ERROR [1] Uncaught Error: bundle error (see logs) [1] at C:/Users/Toby/AppData/Local/Temp/a3ebde98982e7b28c9d1624786c469a4.browserify:1 [1] [1] [1] 10 10 2016 09:11:33.683:DEBUG [karma]: Run complete, exiting. [1] 10 10 2016 09:11:33.720:DEBUG [launcher]: Disconnecting all browsers [1] 10 10 2016 09:11:33.721:DEBUG [framework.browserify]: cleaning up [1] 10 10 2016 09:11:33.789:ERROR [karma]: [TypeError: Cannot read property 'end' of undefined] [1] TypeError: Cannot read property 'end' of undefined [1] at C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\karma-htmlfile-reporter\index.js:121:44 [1] at C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\karma\lib\helper.js:144:7 [1] at FSReqWrap.oncomplete (fs.js:82:15) [1] 10 10 2016 09:11:33.838:DEBUG [launcher]: Disconnecting all browsers [1] 10 10 2016 09:11:33.838:DEBUG [framework.browserify]: cleaning up [1] 10 10 2016 09:11:33.933:DEBUG [launcher]: Process Chrome exited with code 0 [1] 10 10 2016 09:11:33.934:DEBUG [temp-dir]: Cleaning temp dir C:\Users\Toby\AppData\Local\Temp\karma-98045299 [1] 10 10 2016 09:11:34.039:DEBUG [launcher]: Finished all browsers </code></pre> <p>Here is the test:</p> <pre><code>import {BaseRequestOptions, Http, Response, BaseResponseOptions, Headers} from '@angular/http'; import {ReflectiveInjector} from '@angular/core'; import {MockBackend} from '@angular/http/testing'; import {inject} from '@angular/core/testing'; import {AsyncTestCompleter} from '@angular/core/testing/async_test_completer'; it('should get some data', inject([AsyncTestCompleter], (async) =&gt; { var connection; var injector = ReflectiveInjector.resolveAndCreate([ MockBackend, {provide: Http, useFactory: (backend, options) =&gt; { return new Http(backend, options); }, deps: [MockBackend, BaseRequestOptions]}]); var http = injector.get(Http); var backend = injector.get(MockBackend); //Assign any newly-created connection to local variable backend.connections.subscribe(c =&gt; connection = c); http.request('data.json').subscribe((res) =&gt; { expect(res.text()).toBe('awesome'); async.done(); }); var options = new BaseResponseOptions(); var res = new Response(options.merge({ body: 'awesome', headers: new Headers({framework: 'angular'}) })); connection.mockRespond(res); })); </code></pre> <p>The problem seems to be:</p> <pre><code>[1] 10 10 2016 09:11:31.762:ERROR [framework.browserify]: bundle error [1] 10 10 2016 09:11:31.762:ERROR [framework.browserify]: [1] C:\Users\Toby\WebstormProjects\timesheetCrusher\node_modules\@angular\core\testing\async_test_completer.js:11 [1] export var AsyncTestCompleter = (function () { [1] ^ [1] ParseError: 'import' and 'export' may appear only with 'sourceType: module </code></pre> <p>'</p> <p>Here is my package.json:</p> <pre><code>{ "name": "TimesheetCrusher", "version": "0.0.5", "description": "TimesheetCrusher", "scripts": { "typings-install": "typings install", "postinstall": "npm run typings-install", "build": "webpack --inline --colors --progress --display-error-details --display-cached", "watch": "npm run build -- --watch", "server:dev": "webpack-dev-server --progress --profile --colors --display-error-details --display-cached --content-base src/", "server": "webpack-dev-server --inline --colors --progress --display-error-details --display-cached --port 3000 --content-base src", "start": "npm run server", "test": "tsc &amp;&amp; concurrently \"tsc -w\" \"karma start karma.conf.js\"", "tsc": "tsc", "tsc:w": "tsc -w", "report": "lite-server -c bs-config.report.json", "clean": "rimraf public/* ", "cleanNodeModules" : "rimraf node_modules/*" }, "contributors": [ "Rob Wormald &lt;robwormald@gmail.com&gt;", "PatrickJS &lt;github@gdi2290.com&gt;" ], "license": "MIT", "devDependencies": { "compression-webpack-plugin": "0.3.0", "copy-webpack-plugin": "1.1.1", "browserify" : "13.1.0", "html-webpack-plugin": "2.8.1", "awesome-typescript-loader": "1.1.1", "webpack-merge": "^0.14.0", "css-loader": "0.23.1", "es6-promise-loader": "1.0.1", "exports-loader": "0.6.2", "expose-loader": "0.7.1", "file-loader": "0.8.5", "http-server": "0.8.5", "imports-loader": "0.6.5", "json-loader": "0.5.4", "postcss-loader" : "0.10.1", "karma-browserify" : "5.1.0", "ncp": "2.0.0", "node-sass": "3.7.0", "phantomjs-polyfill": "0.0.1", "phantomjs-prebuilt": "2.1.4", "raw-loader": "0.5.1", "reflect-metadata": "0.1.2", "resolve-url-loader": "1.4.3", "rimraf": "2.5.1", "sass-loader": "3.1.2", "source-map-loader": "0.1.5", "style-loader": "0.13.0", "ts-helper": "0.0.1", "ts-loader": "0.8.0", "ts-node": "0.5.5", "tsconfig-lint": "0.5.0", "typedoc": "0.3.12", "typings": "1.0.4", "url-loader": "0.5.7", "webpack": "1.12.13", "webpack-dev-server": "1.14.1", "webpack-md5-hash": "0.0.4", "jasmine-core": "~2.4.1", "karma": "^1.2.0", "karma-chrome-launcher": "^0.2.3", "karma-cli": "^0.1.2", "karma-htmlfile-reporter": "^0.2.2", "karma-jasmine": "^0.3.8", "protractor": "^3.3.0", "rimraf": "^2.5.2", "concurrently": "^2.2.0", "systemjs": "0.19.27" }, "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/core": "2.0.0", "@angular/http": "2.0.0", "@angular/compiler-cli": "0.5.0", "@angular/platform-server": "2.0.0", "@angular/forms": "2.0.0", "@angular/platform-browser": "2.0.0", "typescript": "^1.9.0-dev", "@angular/platform-browser-dynamic": "2.0.0", "@angular/router": "3.0.0", "bootstrap": "4.0.0-alpha.2", "bootstrap-loader": "1.0.9", "autoprefixer": "6.3.1", "ng2-bootstrap": "1.0.16", "ng2-page-scroll": "3.1.0", "font-awesome": "4.5.0", "angular2-template-loader": "^0.4.0", "simple-line-icons": "2.3.2", "glyphicons-halflings": "1.9.0", "core-js": "^2.4.1", "ie-shim": "^0.1.0", "rxjs": "5.0.0-beta.12", "zone.js": "^0.6.23", "jquery": "2.2.0", "tether": "1.1.1" }, "keywords": [ "Angular2", "angular2-seed", "official angular 2 seed", "official angular2 seed" ] } </code></pre> <p>Here is the karma.conf.js:</p> <pre><code>// #docregion module.exports = function (config) { var appBase = 'dist/src/'; // transpiled app JS and map files var appSrcBase = 'src/'; // app source TS files var appAssets = '/base/app/'; // component assets fetched by Angular's compiler var testBase = 'dist/test/'; // transpiled test JS and map files var testSrcBase = 'test/'; // test source TS files config.set({ basePath: '', frameworks: ['jasmine', 'browserify'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-htmlfile-reporter'), require('karma-browserify') ], customLaunchers: { // From the CLI. Not used here but interesting // chrome setup for travis CI using chromium Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'] } }, files: [ // System.js for module loading 'node_modules/systemjs/dist/system.src.js', // Polyfills 'node_modules/core-js/client/shim.js', 'node_modules/reflect-metadata/Reflect.js', // zone.js 'node_modules/zone.js/dist/zone.js', 'node_modules/zone.js/dist/long-stack-trace-zone.js', 'node_modules/zone.js/dist/proxy.js', 'node_modules/zone.js/dist/sync-test.js', 'node_modules/zone.js/dist/jasmine-patch.js', 'node_modules/zone.js/dist/async-test.js', 'node_modules/zone.js/dist/fake-async-test.js', // RxJs {pattern: 'node_modules/rxjs/**/*.js', included: false, watched: false}, {pattern: 'node_modules/rxjs/**/*.js.map', included: false, watched: false}, // Paths loaded via module imports: // Angular itself {pattern: 'node_modules/@angular/**/*.js', included: false, watched: false}, {pattern: 'node_modules/@angular/**/*.js.map', included: false, watched: false}, {pattern: 'systemjs.config.js', included: false, watched: false}, {pattern: 'systemjs.config.extras.js', included: false, watched: false}, 'karma-test-shim.js', // transpiled application &amp; spec code paths loaded via module imports {pattern: appBase + '**/*.js', included: false, watched: true}, {pattern: testBase + '**/*.js', included: true, watched: true}, // Asset (HTML &amp; CSS) paths loaded via Angular's component compiler // (these paths need to be rewritten, see proxies section) {pattern: appBase + '**/*.html', included: false, watched: true}, {pattern: appBase + '**/*.css', included: false, watched: true}, // Paths for debugging with source maps in dev tools {pattern: appSrcBase + '**/*.ts', included: false, watched: false}, {pattern: appBase + '**/*.js.map', included: false, watched: false}, {pattern: testSrcBase + '**/*.ts', included: false, watched: true}, {pattern: testBase + '**/*.js.map', included: false, watched: false} ], // Proxied base paths for loading assets proxies: { // required for component assets fetched by Angular's compiler "/app/": appAssets }, exclude: [], preprocessors: { 'dist/test/**/*.spec.js': ['browserify'] }, reporters: ['progress', 'html'], // HtmlReporter configuration htmlReporter: { // Open this file to see results in browser outputFile: 'test-output/tests.html', // Optional pageTitle: 'Unit Tests', subPageTitle: __dirname }, // Browserify configuration browserify: { debug: true }, port: 9876, colors: true, logLevel: config.LOG_DEBUG, autoWatch: false, browsers: ['Chrome'], singleRun: true }) } </code></pre> <p>So it seems browserify is having trouble with the Async test package.</p> <p>The tooling around Angular 2 is massive and hard to get right at the beginning. Can anyone point me in the right direction?</p> <p>Thank you very much.</p>
<p>I've never used the <code>AsyncTestCompleter</code>, and I've never seen it used anywhere, except in the Angular source tests. I don't know if it's something that's just meant to be used internally or not, but when I tested I got a different error, saying there is no provider for <code>AsyncTestCompleter</code>.</p> <p>For your test though, you don't need to use it. There are other ways to handle async tests. One options is to just use <code>async</code></p> <pre><code>import { async } from '@angular/core/testing' it('...', async(inject([Http], (http) =&gt; { http.request('data.json').subscribe((res) =&gt; { expect(res.text()).toBe('awesome'); }); }))); </code></pre> <p>Here, we don't need to call <code>done</code> anywhere. The test gets wrapped in Zone, and the Zone is aware of all asynchronous tasks, and waits for them to complete before ending the test.</p> <p>Anther option is <code>fakeAsync</code> where we can force the to wait the ending of tasks <em>synchronously</em> by calling <code>tick</code></p> <pre><code>import { fakeAsync, tick } from '@angular/core'; it('...', fakeAsync(inject([Http], (http) =&gt; { let data; http.request('data.json').subscribe((res) =&gt; { data = res.text(); }); tick(); expect(res.text()).toBe('awesome'); }))); </code></pre> <p>The other option is to just use the native Jasmine <code>done</code>. I am not sure how to get it to work with <code>inject</code> though, so you can just get the <code>Http</code> just like you are currently doing from the test bed.</p> <pre><code>it('...', fakeAsync((done) =&gt; { http.request('data.json').subscribe((res) =&gt; { expect(res.text()).toBe('awesome'); done(); }); })); </code></pre> <p>This is all explained in the docs you linked to, in the section <a href="https://angular.io/docs/ts/latest/guide/testing.html#!#component-with-async-service" rel="nofollow">Test a component with an async service</a></p>
Unquoting argument in macro definition hangs function call <p>I've been working through an exercise on macros (Dave Thomas' excellent <a href="https://pragprog.com/book/elixir12/programming-elixir-1-2" rel="nofollow">Programming Elixir 1.2</a>, chapter 21) and I've hit a bit of a bump in my understanding of what's happening. I have two modules, <code>Tracer</code> and <code>Test</code>, where <code>Tracer</code> redefines the <code>def</code> macro to insert call and response logging as follows:</p> <pre><code>defmodule Tracer do def dump_args(args) do args |&gt; Enum.map(&amp;inspect/1) |&gt; Enum.join(",") end def dump_defn(name, args) do "#{name}(#{dump_args(args)})" end defmacro def({name, _, args} = definition, do: content) do IO.puts("Definition: #{inspect definition}") IO.puts("Content: #{inspect content}") quote do Kernel.def unquote(definition) do IO.puts("==&gt; call: #{Tracer.dump_defn(unquote(name), unquote(args))}") result = unquote(content) IO.puts("&lt;== resp: #{inspect result}") result end end end end </code></pre> <p>and <code>Test</code> uses this macro to demonstrate its use:</p> <pre><code>defmodule Test do import Kernel, except: [def: 2] import Tracer, only: [def: 2] def puts_sum_three(a, b, c), do: IO.inspect(a+b+c) def add_list(list), do: Enum.reduce(list, 0, &amp;(&amp;1 + &amp;2)) def neg(a) when a &lt; 0, do: -a end </code></pre> <p>When executing this, the first two functions work as expected:</p> <pre><code>iex(3)&gt; Test.puts_sum_three(1,2,3) ==&gt; call: puts_sum_three(1,2,3) 6 &lt;== resp: 6 6 iex(4)&gt; Test.add_list([1,2,3,4]) ==&gt; call: add_list([1, 2, 3, 4]) &lt;== resp: 10 10 </code></pre> <p>However, the third function appears to hang - specifically it hangs at <code>unquote(args)</code>:</p> <pre><code>iex(5)&gt; Test.neg(-1) </code></pre> <p>So my question is, <strong>what causes the call to neg to hang?</strong> While I think I have an idea, I'd like to confirm (or refute) my understanding of why it does so.</p> <p>The <code>when</code> clause in the third function changes the representation of the quoted expression that is passed to the <code>def</code> macro and I have no problems in reworking the macro to handle this. The <code>definition</code> and <code>content</code> passed for <code>neg</code> are:</p> <pre><code>Definition: {:when, [line: 7], [{:neg, [line: 7], [{:a, [line: 7], nil}]}, {:&lt;, [line: 7], [{:a, [line: 7], nil}, 0]}]} Content: {:-, [line: 7], [{:a, [line: 7], nil}]} </code></pre> <p>When we reach the <code>unquote(args)</code> in <code>neg</code>, it is attempting to evaluate the <code>args</code> expression, which I believe is a list containing a call to <code>neg</code> and results in an infinite recursive loop. Is this correct? Any pointers to how I might debug/diagnose this would also be appreciated, as would links to further reading.</p>
<blockquote> <p>When we reach the <code>unquote(args)</code> in <code>neg</code>, it is attempting to evaluate the <code>args</code> expression, which I believe is a list containing a call to <code>neg</code> and results in an infinite recursive loop. Is this correct?</p> </blockquote> <p>Yes, this is what that line compiles to:</p> <pre><code>IO.puts("==&gt; call: #{Tracer.dump_defn(:when, [neg(a), a &lt; 0])}") </code></pre> <p>which results in infinite recursion.</p> <blockquote> <p>Any pointers to how I might debug/diagnose this would also be appreciated, as would links to further reading.</p> </blockquote> <p>One way is to pass the value returned by <code>quote</code> to <code>|&gt; Macro.to_string |&gt; IO.puts</code>. This will print the exact code that was generated by that <code>quote</code> expression. This is exactly what I did to confirm your hypothesis:</p> <pre><code>defmacro def({name, _, args} = definition, do: content) do IO.puts("Definition: #{inspect definition}") IO.puts("Content: #{inspect content}") ast = quote do Kernel.def unquote(definition) do IO.puts("==&gt; call: #{Tracer.dump_defn(unquote(name), unquote(args))}") result = unquote(content) IO.puts("&lt;== resp: #{inspect result}") result end end ast |&gt; Macro.to_string |&gt; IO.puts ast end </code></pre> <p>This prints:</p> <pre><code>Kernel.def(neg(a) when a &lt; 0) do IO.puts("==&gt; call: #{Tracer.dump_defn(:when, [neg(a), a &lt; 0])}") result = -a IO.puts("&lt;== resp: #{inspect(result)}") result end </code></pre> <p>which makes it clear why the function hangs.</p> <hr> <p>One way to fix this would be to extract the actual name/args if the name is <code>:when</code>:</p> <pre><code>... {name, args} = case {name, args} do {:when, [{name, _, args}, _]} -&gt; {name, args} {name, args} -&gt; {name, args} end quote do </code></pre> <p>After this, <code>Test.neg/1</code> works:</p> <pre><code>iex(1)&gt; Test.neg -1 ==&gt; call: neg(-1) &lt;== resp: 1 1 iex(2)&gt; Test.neg -100 ==&gt; call: neg(-100) &lt;== resp: 100 100 ... </code></pre>
Makefile Use Shell to create variables <p>I am using make's shell command to populate some variables, and on output it indicates that they are being set to the values I expect. However when I pass them to my make recipes they all show up empty. I suspect make is doing some odd parsing on tte results. Eg: </p> <pre><code>MyTarget: $(MySources) LINE='$(shell cat $&lt; | grep GIMME_THE_LINE_I_WANT)' CH9=$(shell echo $(LINE) | cut -b9) echo $(CH9) # doesn't print anything </code></pre> <p>I checked my generator commands manually by setting <code>SHELL=sh -XV</code> and when I run identical commands I get the right values, it just looks like bash is 'zeroing' my variables. Any idea what's wrong?</p>
<p>There are several things going on here. The first is that when you have:</p> <pre><code>MyTarget: $(MySources) LINE='$(shell cat $&lt; | grep GIMME_THE_LINE_I_WANT)' </code></pre> <p>You are setting a <em>shell</em> variable called <code>LINE</code>, not a <code>make</code> variable. The build instructions for a target are all shell commands. So after the first line, the shell variable <code>$LINE</code> contains <code>GIMME_THE_LINE_I_WANT</code>. However...</p> <p>...each <em>line</em> in the build instructions for a target runs in a separate shell process. So if you have:</p> <pre><code>mytarget: MYVAR=foo echo $$MYVAR </code></pre> <p>You'll see no output, because <code>$MYVAR</code> isn't set in the context of the second command. Also note the use of <code>$$</code> here, because otherwise the <code>$</code> would be interpreted by Make (that is, writing <code>$MYVAR</code> would actually be the make expression <code>$M</code> followed by the text <code>YVAR</code>). You can resolve this by logically joining your lines into a single shell script, like this:</p> <pre><code>mytarget: MYVAR=foo; \ echo $$MYVAR </code></pre> <p>The <code>\</code> is Makefile syntax that extends a single logical line over multiple physical lines, and of course <code>;</code> is simply shell syntax for combining multiple commands on one line.</p> <p>With all this in mind, we could rewrite your target like this:</p> <pre><code>MyTarget: $(MySources) LINE=$$(cat $&lt; | grep GIMME_THE_LINE_I_WANT); \ CH9=$$(echo $$LINE | cut -b9); \ echo $$CH9 </code></pre> <p>Notice that since we are <em>already</em> running a shell script I'm not using Make's <code>$(shell ...)</code> construct, and that I'm making sure to escape all of the <code>$</code> characters to ensure that the shell, not Make, is handling variable expansion.</p> <p>Taking it just a little further, you don't need to use <code>cat</code> in that script; you could simply write:</p> <pre><code>MyTarget: $(MySources) LINE=$$(grep GIMME_THE_LINE_I_WANT $&lt;); \ CH9=$$(echo $$LINE | cut -b9); \ echo $$CH9 </code></pre> <p>Or:</p> <pre><code>MyTarget: $(MySources) CH9=$$(grep GIMME_THE_LINE_I_WANT $&lt; | cut -b9); \ echo $$CH9 </code></pre> <p>(NB: While not germane to this solution, it's although worth noting that each invocation of <code>$(shell ...)</code> is also run in a separate process, so a variable set in one won't be available in another.)</p>
Firebase and Swift 3 <p>I have searched around and have not found the particular answer that I am seeking for. I just went and updated my App to a Swift 3 Language from swift 2. It obviously threw out a host of errors which I went through and fixed to the best of my abilities and now I do not have any errors. I can run the app but I cant tell if anything else is working because the Login or Auth sections of the app are not working. I know that I can just bypass to test but I have been working on it a lot and trying to get this feature to work that worked well before the language was changed..</p> <p>Very simple my question is this: I upgraded to Swift 3. Do I need to upgrade the cocoa pods to support the change in language? If not is it just an issue with the way that my code is and because of the change to swift 3 that i need to keep tinkering with?</p> <p>Thanks for any help</p>
<p>sorry posted that about 12 hours to early. After doing a lot of research it looks like I found the answer. have not tested yet but I think I am getting the same errors in the compiler. </p> <p><strong>"We've noticed what seems to be an issue with the latest iOS 10 simulators (up to beta 6 at the time of this writing) that causes Firebase Auth to throw an error due it to not being able to write values to the keychain. This issue does not affect real devices." This is from a Firebase Blog</strong></p>
trouble importing components in react <p>Hi I'm having trouble importing components from one jsx into another. I'm using a <code>django framework</code> to serve my webfiles and I've downloaded all the necessary tools (npm, webpack, webpack-bundle-tracker, babel loader, django-webpack loader). <code>Webpack</code> does a good job taking all of the seperate javascript files and turning them into a bundle in which my local django server can then render. The issue lies in when I try to <code>import a component from one jsx into another jsx</code>. There aren't any errors that I see but the javascript that I'm trying to import doesn't load on django.</p> <p>Example: <code>File:index.js</code></p> <pre><code>var React = require('react') var ReactDOM = require('react-dom') var Body = require('./app.js') ReactDOM.render(&lt;Body message="Welcome to my website"/&gt;, document.getElementById('app1')) </code></pre> <p>Import file (which is in the same directory as index.js): <code>File:app.js</code></p> <pre><code>var React = require('react') var Body = React.createClass({ getInitialState: function() { return { bodymessage: this.props.message } }, render: function() { return ( &lt;h1&gt; {this.state.bodymessage} &lt;/h1&gt; ) } }) module.exports = Body; </code></pre> <p>Is there something wrong with my configuration?</p> <p>Here's my webpack.config.js file :</p> <pre><code>var path = require('path') var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './assets/js/index', output: { path: path.resolve('./assets/bundles/'), filename: '[name]-[hash].js', }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }) ], module: { loaders: [ {test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: ['react'] } } ] }, resolve: { modulesDirectories: ['node_modules', 'bower_components'], extensions: ['', '.js', '.jsx'] } } </code></pre>
<p>Try replace this </p> <pre><code> loader: 'babel-loader', </code></pre> <p>with </p> <pre><code> loader: 'babel', </code></pre> <p>in you webpack config</p> <p>PS: this shouldve been a comment but not enough rep</p>
CSV: Change One Field Column <p>I have file named <code>test.csv</code> which has 85 fields?</p> <p>I have to read that file, change 1 column &amp; save it again.</p> <p>I have below code.</p> <pre><code>$file_name = "test.csv"; $infos = array(); if (($handle = fopen($file_name, "r")) !== FALSE) { while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { //echo "&lt;pre&gt;"; //print_r($data); $cleanURL = cleanUrl($data[6]); $infos[] = $data[0] . ',' . $data[1] . ',' . $data[2] . ',' . $data[3] . ',' . $data[4] . ',' . $data[5] . ',' . $data[6] . ',' . $data[7] . ',' . $data[8] . ',' . $data[9] . ',' . $data[10] . ',' . $data[11] . ',' . $data[12] . ',' . $data[13] . ',' . $data[14] . ',' . $data[15] . ',' . $data[16] . ',' . $cleanURL . ',' . $data[18] . ',' . $data[19] . ',' . $data[20] . ',' . $data[21] . ',' . $data[22] . ',' . $data[23] . ',' . $data[24] . ',' . $data[25] . ',' . $data[26] . ',' . $data[27] . ',' . $data[28] . ',' . $data[29] . ',' . $data[30] . ',' . $data[31] . ',' . $data[32] . ',' . $data[33] . ',' . $data[34] . ',' . $data[35] . ',' . $data[36] . ',' . $data[37] . ',' . $data[38] . ',' . $data[39] . ',' . $data[40] . ',' . $data[41] . ',' . $data[42] . ',' . $data[43] . ',' . $data[44] . ',' . $data[45] . ',' . $data[46] . ',' . $data[47] . ',' . $data[48] . ',' . $data[48] . ',' . $data[50] . ',' . $data[51] . ',' . $data[52] . ',' . $data[53] . ',' . $data[54] . ',' . $data[55] . ',' . $data[56] . ',' . $data[57] . ',' . $data[58] . ',' . $data[59] . ',' . $data[60] . ',' . $data[61] . ',' . $data[62] . ',' . $data[63] . ',' . $data[64] . ',' . $data[65] . ',' . $data[66] . ',' . $data[67] . ',' . $data[68] . ',' . $data[69] . ',' . $data[70] . ',' . $data[71] . ',' . $data[72] . ',' . $data[73] . ',' . $data[74] . ',' . $data[75] . ',' . $data[76] . ',' . $data[77] . ',' . $data[78] . ',' . $data[79] . ',' . $data[80] . ',' . $data[81] . ',' . $data[82] . ',' . $data[83] . ',' . $data[84] . ',' . $data[85]; //echo $data[6].'-&gt;'.cleanUrl($data[6]); //print_r($data[17]); } fclose($handle); } $fp = fopen('write.csv', 'w'); foreach ($infos as $info) { fputcsv($fp, array($info), ',', ' '); } function cleanUrl($str, $replace = array(), $delimiter = '-') { setlocale(LC_ALL, 'en_US.UTF8'); if (!empty($replace)) { $str = str_replace((array) $replace, ' ', $str); } $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str); $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean); $clean = strtolower(trim($clean, '-')); $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean); return $clean; } </code></pre> <p>Is there any sorter way, so i don't need to write 85 columns in <code>#info</code> array? Because i'm going to change only 1 column &amp; write it again.</p> <p>If i have <strong>Date</strong> 10/10/2016, 10:15 AM.</p> <p>then it separates both in different column.</p> <p><code>fputcsv($fp, array($info), ',', ' ');</code> here may be issue.</p>
<p>less looping, should a little more efficient</p> <pre><code>&lt;?php $file_name = "test.csv"; $infos = array(); if (($handle = fopen($file_name, "r")) !== FALSE) { $fp = fopen('write.csv', 'w'); while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { $data[17] = cleanUrl($data[6]); fputcsv($fp, array($data), ',', ' '); fclose($handle); } } function cleanUrl($str, $replace = array(), $delimiter = '-') { setlocale(LC_ALL, 'en_US.UTF8'); if (!empty($replace)) { $str = str_replace((array) $replace, ' ', $str); } $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str); $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean); $clean = strtolower(trim($clean, '-')); $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean); return $clean; } </code></pre>
python XML get text inside <p>...</p> tag <p>I guys, I have an xml structure which looks somewhat like this.</p> <pre><code>&lt;abstract&gt; &lt;p id = "p-0001" num = "0000"&gt; blah blah blah &lt;/p&gt; &lt;/abstract&gt; </code></pre> <p>I would like to extract the <code>&lt;p&gt;</code> tag inside the <code>&lt;abstract&gt;</code> tag only.</p> <p>I tried:</p> <pre><code>import xml.etree.ElementTree as ET xroot = ET.parse('100/A/US07640598-20100105.XML').getroot() for row in xroot.iter('p'): print row.text </code></pre> <p>This get all the <code>&lt;p&gt;</code> tag in my xml which is not a good idea.</p> <p>Is there anyway i can extract the text inside </p> <p>My desire output would be extracting "blah blah blah"</p>
<p>You can use an <em>XPath expression</em> to search for <code>p</code> elements specifically inside the <code>abstract</code>:</p> <pre><code>for p in xroot.xpath(".//abstract//p"): print(p.text.strip()) </code></pre> <p>Or, if using <code>iter()</code> you may have a nested loop:</p> <pre><code>for abstract in xroot.iter('abstract'): for p in abstract.iter('p'): print(p.text.strip()) </code></pre>
google charts api get chart without element argument? <p>I'm using a tool that creates google charts behind a facade. Works well, but now I'm adding diff charts.</p> <p>Diff charts require access to chart.computeDiff(...) but this requires a chart, which in turn as far as I can see (for some reason) requires an argument referencing an html element. This doesn't conform to the flow of the tool I'm using.</p> <p>Is there any other way to get access to the chart methods, or some other place to get access to computeDiff?</p> <p>The tool uses </p> <pre><code> this.wrapper = new google.visualization.ChartWrapper(chartConfig); </code></pre> <p>for instance, but </p> <pre><code> let chart = this.wrapper.getChart() just returns null </code></pre> <p>Any tips would be appreciated. </p>
<p>never mind, i took computeDiff from the appropriate prototypes:</p> <pre><code>let computeDiff = google.visualization[this.wrapper.getChartType()].prototype.computeDiff let chartDiff = computeDiff(oldData,newData) return chartDiff </code></pre> <p>seems to work</p>
PHP - What is this if statement meaning? <p>I use PHP around 3 months see many syntax.<br> but cannot understand what is this mean. </p> <pre><code>if($foo = 'somevalue') //or if($foo = $somevalue) { } </code></pre> <p>I see only if($foo) this mean if($foo == TRUE). or if($foo ==,>,&lt; somevalue)<br> but in this case, if$foo hold some value???</p>
<p>You are just simultaneously <strong>assigning</strong> a value to <code>$foo</code> and evaluating it in the <code>if</code> statement. So if the value of <code>$foo</code> corresponds to <code>false</code>, then code inside the <code>if</code> statement would not execute. As an example:</p> <pre><code>if ($foo = 12) { // foo's value is now 12 // code here would execute } echo $foo; // 12 if ($foo = 0) { // foo's value is now 0 // would not execute } echo $foo; // 0 </code></pre>
Conditionally toggle `preventDefault` on form submissions in Elm <p>Is there a way to conditionally toggle <code>preventDefault</code> on form submissions? I've tried using <code>onWithOptions</code>, below, but it seems only the first setting is used, even though I can see it change using <code>Debug.log</code>, when there is a name on the model.</p> <pre><code>, onWithOptions "submit" (if model.name == "" then (Debug.log "prevent" { preventDefault = True, stopPropagation = True }) else (Debug.log "allow" { preventDefault = False, stopPropagation = False }) ) (Json.succeed FormSubmit) </code></pre> <h2>Updated with findings from answer</h2> <p>As stated by @Tosh, hiding the button resolves the issue:</p> <pre><code>, button [ onPreventClickHtml FormSubmit , Html.Attributes.hidden (model.name == "" |&gt; not) ] [ text " prevent" ] , button [ onClick FormSubmit , Html.Attributes.hidden (model.name == "") ] [ text "allow" ] </code></pre> <p>Where <code>onPreventClickHtml</code> is:</p> <pre><code>onPreventClickHtml : Msg -&gt; Attribute Msg onPreventClickHtml msg = onWithOptions "click" { preventDefault = True, stopPropagation = True } (Json.succeed msg) </code></pre> <p>Conditionally displaying the button <strong><em>does not</em></strong> work:</p> <pre><code>, (if model.name == "" then button [ onPreventClickHtml FormSubmit ] [ text " prevent" ] else button [ type' "submit", onClick FormSubmit ] [ text "allow" ] ) </code></pre> <p>I'm using elm-mdl and so found implementing the solution more challenging because from my experience creating a custom <em>onclick</em> requires types which are not exposed by elm-mdl, and so need to be duplicated.</p> <pre><code>, if model.name == "" then Material.Options.nop else Material.Options.css "visibility" "hidden" , onPreventClick FormSubmit , if model.name == "" then Material.Options.css "visibility" "hidden" else Material.Options.nop , Button.onClick FormSubmit onPreventClick : Msg -&gt; Property Msg onPreventClick message = Material.Options.set (\options -&gt; { options | onClick = Just (onPreventClickHtml message) }) -- Duplicated from elm-mdl type alias Property m = Material.Options.Property (Config m) m -- Duplicated from elm-mdl type alias Config m = { ripple : Bool , onClick : Maybe (Attribute m) , disabled : Bool , type' : Maybe String } </code></pre> <p>Another approach, which worked for my scenario, was changing the button type:</p> <pre><code>, if model.name == "" then Button.type' "reset" else Button.type' "submit" </code></pre>
<p>One simple workaround suggestion until someone can show us how to solve it.</p> <p>How about create two buttons (with different options as you've shown) and depending on the condition show only one of them? You can use <code>Html.Attributes.hide</code> for that.</p>
how to fix this kind of git conflict: .merge_file_a <p>I am working on an android project but i got this kind of conflict. I never met this before any clue which one should i keep?</p> <pre><code>&lt;&lt;&lt; .merge_file_a36756 @Inject TPOmnitureReporter reporter; private TPCardAdapter adapter; ======= private TPAdapter adapter; &gt;&gt;&gt;&gt;&gt;&gt;&gt; .merge_file_a32544 </code></pre> <p><strong>EDIT</strong></p> <p>My question is i am not quite sure which part of code is mine. Usually it should be <code>&lt;&lt;&lt; HEAD</code> is my code. But it is <code>.merge_file_a</code> now.</p>
<p>You have to resolve a merge conflict, you have to decide which one you want to keep. Once you choose you can change the file, add and commit it. </p> <p>Looks like one of you wanted to add : </p> <pre><code> @Inject TripPlannerOmnitureReporter reporter; private TripPlannerCardAdapter adapter; </code></pre> <p>An the other one something else. If it was you then you can choose alone, if not then you should ask your teammate. </p>
I cannot add in my ArrayList [Android] <p>In my class I created a <code>variable</code> named <code>taskArray</code> and initialized it in my <code>onCreate</code> like this </p> <pre><code> public class ActivityOne extends Activity { ArrayList&lt;WorkTask&gt; taskArray = null; @Override protected void onCreate(Bundle savedState) { taskArray = new ArrayList&lt;WorkTask&gt;(); final GetTasks getTasks = new GetTasks(); getTasks.execute(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if ( getTasks.getStatus() == AsyncTask.Status.RUNNING ) { getTasks.cancel(true); Toast.makeText(ActivityOne.this, "Connection Timeout", Toast.LENGTH_SHORT).show(); } } }, 60000 ); } </code></pre> <p>And then in my <code>AsyncTask</code> in <code>doInBackground</code> I'm adding the data on the <code>branchesArray</code> but It doesn't add. Before it is working correctly, but now it doesn't. My code looks like this </p> <pre><code> public final class GetTasks extends AsyncTask&lt;Void, Void, Employee&gt; { protected Employee doInBackground(Void... params) { try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(URL_STRING); HttpResponse response = httpclient.execute(httpget); str = EntityUtils.toString(response.getEntity()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try{ JSONObject jsonObject = new JSONObject(str); JSONObject data = jsonObject.getJSONObject("DATA"); //Employee info empObj = new Employee(); empObj.setId(data.getInt("id")); empObj.setName(data.getString("name").toString()); JSONArray jArray = data.getJSONArray("worktask"); for (int i = 0, count = jArray.length(); i &lt; count; i++) { JSONObject jObj = jArray.getJSONObject(i); WorkTask workTask = new WorkTask(); workTask.setId(jObj.getInt("id")); workTask.setTaskName(jObj.getInt("task_name")); taskArray.add(workTask); } }catch (JSONException e){ e.printStackTrace(); return null; } return empObj; } </code></pre> <p>Here is my model <code>WorkTask</code> </p> <pre><code>public class WorkTask implements Serializable { private int id; private String taskName; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getTaskName() { return taskName; } public void setTaskName(int taskName) { this.taskName = taskName; } </code></pre>
<p>I think you write more information about your code.</p> <p>It can occurred by <code>count</code> is zero that means <code>jArray</code> is empty list.</p> <p>Frist, you check your json data about <code>worktask</code>.</p>
Ruby - Array of hashes - Nested HTML menu from hash values without writing duplicates <p>I have a relatively large hash where the values for all keys within are array of hashes (see below for sample layout). I have spent the last 4.5 hours attempting to write out HTML for my Rails application and I am seriously about to cry as I've gone round in circles with nothing really to show for it!</p> <p>Any help is <em>greatly</em> appreciated and thank you in advance for your time!</p> <p><strong>Specific Problems Encountered</strong></p> <ol> <li>Chapters/verses appear for books that they do not align to.</li> <li>I'm also not able to de-duplicate entries, so 'Chapter 4', for example, is appearing multiple times (instead of it appearing once, with mulitple chapter/verse references nested beneath)</li> </ol> <p><strong>Desired Solution Criteria</strong> </p> <ol> <li><p>The HTML needs to be written in 3 layers/nested (1st layer/div containing Book Name (e.g. Genesis, Exodus, Leviticus), 2nd layer/div containing chapter and 3rd layer/div containing verse) </p></li> <li><p>Chapters and verses must align (e.g. Exodus 2:7 should not be written to the Genesis chapter 2 menu).</p></li> <li><p>Book names should be written in the order of <code>hsh</code>'s keys (e.g. Genesis followed by Exodus followed by Leviticus as opposed to alphabetical order)</p></li> </ol> <p><strong>Data Format:</strong></p> <pre><code>hsh = { :genesis =&gt; [ {:id =&gt; 1, :verse =&gt; 'Genesis 4:12'}, {:id =&gt; 1, :verse =&gt; 'Genesis 4:23-25'}, {:id =&gt; 2, :verse =&gt; 'Genesis 6:17'} ], :exodus =&gt; [ {:id =&gt; 5, :verse =&gt; 'Exodus 2:7'}, {:id =&gt; 3, :verse =&gt; 'Exodus 2:14-15'}, {:id =&gt; 4, :verse =&gt; 'Exodus 12:16'} ], :leviticus =&gt; [ {:id =&gt; 2, :verse =&gt; 'Leviticus 11:19-21'}, {:id =&gt; 7, :verse =&gt; 'Leviticus 15:14-31'}, {:id =&gt; 7, :verse =&gt; 'Leviticus 19:11-12'} ] } </code></pre> <p><strong>Desired Output HTML</strong> [Shortened for Brevity]</p> <pre><code>&lt;div class="submenu"&gt; &lt;a href="#"&gt;Genesis&lt;/a&gt; &lt;div class="lvl-2"&gt; &lt;div&gt; &lt;div class="submenu"&gt; &lt;a&gt;Chapter 4&lt;/a&gt; &lt;div class="lvl-3"&gt; &lt;div&gt; &lt;a onclick="load('1')"&gt;&lt;span&gt;ID 1&lt;/span&gt; Verse 12&lt;/a&gt; &lt;a onclick="load('1')"&gt;&lt;span&gt;ID 1&lt;/span&gt; Verse 23-25&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="submenu"&gt; &lt;a&gt;Chapter 6&lt;/a&gt; &lt;div class="lvl-3"&gt; &lt;div&gt; &lt;a onclick="load('2')"&gt;&lt;span&gt;ID 2&lt;/span&gt; Verse 17&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="submenu"&gt; &lt;a href="#"&gt;Exodus&lt;/a&gt; &lt;div class="lvl-2"&gt; &lt;div&gt; &lt;div class="submenu"&gt; &lt;a&gt;Chapter 2&lt;/a&gt; &lt;div class="lvl-3"&gt; &lt;div&gt; &lt;a onclick="load('5')"&gt;&lt;span&gt;ID 5&lt;/span&gt; Verse 7&lt;/a&gt; &lt;a onclick="load('3')"&gt;&lt;span&gt;ID 3&lt;/span&gt;Verse 14-15&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="submenu"&gt; &lt;a&gt;Chapter 12&lt;/a&gt; &lt;div class="lvl-3"&gt; &lt;div&gt; &lt;a onclick="load('4')"&gt;&lt;span&gt;ID 4&lt;/span&gt; Verse 16&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ## Shortened for brevity (Leviticus references excluded) &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>Code</strong></p> <pre><code>final_html = String.new hsh.each do |book, verse_array| verse_array.each do |reference| book = reference[:verse].split(' ').first # =&gt; "Genesis" full_verse = reference[:verse].split(' ').last # =&gt; "4:12" chapter = full_verse.split(':').first # =&gt; "4" verse = full_verse.split(':').first # =&gt; "12" # Failing Miserably at appending the right HTML to the final_html string here... # final_html &lt;&lt; "&lt;div class=\"submenu\"&gt;" # final_html &lt;&lt; ... # final_html &lt;&lt; ... end end </code></pre> <p>Finally, note that there are no duplicate chapter/verse combinations (e.g. Genesis 4:12 will never appear a second time). It's also worth noting that both chapters and verses need to be sorted numerically and ascending.</p>
<p>As is often the case with such problems, it becomes much easier to solve once you've put the data into a "shape" that closely resembles your desired output. Your output is a nested tree structure, so your data should be, too. Let's do that first. Here's your data:</p> <pre><code>data = { genesis: [ { id: 1, verse: "Genesis 4:12" }, { id: 1, verse: "Genesis 4:23-25" }, { id: 2, verse: "Genesis 6:17" } ], exodus: [ { id: 5, verse: "Exodus 2:7" }, # ... ], # ... } </code></pre> <p>And, setting aside the HTML for now, here's the structure we want:</p> <pre class="lang-none prettyprint-override"><code>Genesis Chapter 4 ID 1 - Verse 12 ID 1 - Verse 23-25 Chapter 6 ID 2 - Verse 17 Exodus Chapter 2 ID 5 - Verse 7 ... ... </code></pre> <p>The first thing I notice about your data is that it has a level of nesting you don't need. Since the <code>:verse</code> values contain the book name, we don't the keys from the outer hash (<code>:genesis</code> et al) and we can just flatten all of the inner hashes into a single array:</p> <pre><code>data.values.flatten # =&gt; [ { id: 1, verse: "Genesis 4:12" }, # { id: 1, verse: "Genesis 4:23-25" }, # { id: 2, verse: "Genesis 6:17" } # { id: 5, verse: "Exodus 2:7" }, # # ... ] </code></pre> <p>Now we need a method to extract the book, chapter, and verse from the <code>:verse</code> strings. You can use <code>String#split</code> if you want, but a Regexp is a good choice too:</p> <pre><code>VERSE_EXPR = /(.+)\s+(\d+):(.+)$/ def parse_verse(str) m = str.match(VERSE_EXPR) raise "Invalid verse string!" if m.nil? book, chapter, verse = m.captures { book: book, chapter: chapter, verse: verse } end flat_data = data.values.flatten.map do |id:, verse:| { id: id }.merge(parse_verse(verse)) end # =&gt; [ { id: 1, book: "Genesis", chapter: "4", verse: "12" }, # { id: 1, book: "Genesis", chapter: "4", verse: "23-25" }, # { id: 2, book: "Genesis", chapter: "6", verse: "17" }, # { id: 5, book: "Exodus", chapter: "2", verse: "7" }, # # ... ] </code></pre> <p>Now it's easy to group the data by book:</p> <pre><code>books = flat_data.group_by {|book:, **| book } # =&gt; { "Genesis" =&gt; [ # { id: 1, book: "Genesis", chapter: "4", verse: "12" }, # { id: 1, book: "Genesis", chapter: "4", verse: "23-25" }, # { id: 2, book: "Genesis", chapter: "6", verse: "17" } # ], # "Exodus" =&gt; [ # { id: 5, book: "Exodus", chapter: "2", verse: "7" }, # # ... # ], # # ... # } </code></pre> <p>...and within each book, by chapter:</p> <pre><code>books_chapters = books.map do |book, verses| [ book, verses.group_by {|chapter:, **| chapter } ] end # =&gt; [ [ "Genesis", # { "4" =&gt; [ { id: 1, book: "Genesis", chapter: "4", verse: "12" }, # { id: 1, book: "Genesis", chapter: "4", verse: "23-25" } ], # "6" =&gt; [ { id: 2, book: "Genesis", chapter: "6", verse: "17" } ] # } # ], # [ "Exodus", # { "2" =&gt; [ { id: 5, book: "Exodus", chapter: "2", verse: "7" }, # # ... ], # # ... # } # ], # # ... # ] </code></pre> <p>You'll notice that since we called <code>map</code> on <code>books</code> our final result is an Array, not a Hash. You could call <code>to_h</code> on it to make it a Hash again, but for our purposes it's not necessary (iterating over an Array of key-value pairs works the same as iterating over a Hash).</p> <p>It looks a little messy, but you can see that the structure is there: Verses nested within chapters nested within books. Now we just need to turn it into HTML.</p> <blockquote> <p>An aside, for the sake of our friends with disabilities: The correct HTML element to use for nested tree structures is <code>&lt;ul&gt;</code> or <code>&lt;ol&gt;</code>. If you have some requirement to use <code>&lt;div&gt;</code>s instead you can, but otherwise use the right element for the job—users who use accessibility devices will thank you. (Many articles have been written on styling such trees, so I won't go into it, but for a start you can hide the bullets with <code>list-style-type: none;</code>.)</p> </blockquote> <p>I don't have a Rails app at my disposal, so to generate the HTML I'll just use ERB from the Ruby standard library. It will look more-or-less identical in Rails except for how you pass the variable to the view.</p> <pre><code>require "erb" VIEW = &lt;&lt;END &lt;ul&gt; &lt;% books.each do |book_name, chapters| %&gt; &lt;li&gt; &lt;a href="#"&gt;&lt;%= book_name %&gt;&lt;/a&gt; &lt;ul&gt; &lt;% chapters.each do |chapter, verses| %&gt; &lt;li&gt; &lt;a href="#"&gt;Chapter &lt;%= chapter %&gt;&lt;/a&gt; &lt;ul&gt; &lt;% verses.each do |id:, verse:, **| %&gt; &lt;li&gt; &lt;a onclick="load(&lt;%= id %&gt;)"&gt;ID &lt;%= id %&gt;: Verse &lt;%= verse %&gt;&lt;/a&gt; &lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; END def render(books) b = binding ERB.new(VIEW, nil, "&lt;&gt;-").result(b) end puts render(books_chapters) </code></pre> <p>And here's the result as an HTML snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Genesis&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Chapter 4&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a onclick="load(1)"&gt;ID 1: Verse 12&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a onclick="load(1)"&gt;ID 1: Verse 23-25&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Chapter 6&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a onclick="load(2)"&gt;ID 2: Verse 17&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Exodus&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Chapter 2&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a onclick="load(5)"&gt;ID 5: Verse 7&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a onclick="load(3)"&gt;ID 3: Verse 14-15&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Chapter 12&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a onclick="load(4)"&gt;ID 4: Verse 16&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Leviticus&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Chapter 11&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a onclick="load(2)"&gt;ID 2: Verse 19-21&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Chapter 15&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a onclick="load(7)"&gt;ID 7: Verse 14-31&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#"&gt;Chapter 19&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a onclick="load(7)"&gt;ID 7: Verse 11-12&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p>Finally, here it is in action on repl.it: <a href="https://repl.it/Duhm" rel="nofollow">https://repl.it/Duhm</a></p>
Blank Page While Exporting as PDF in SSRS Matrix Report <p>I have created an SSRS Matrix report which shows 3 pages in output but when i export the report as a PDF, it shows 6 pages. One page is blank, although i selected the option ConsumeContainerWhiteSpace as True but still it is giving me a blank page as well the output pages are more than what is being shown in preview. I am using VS2013, kindly suggest.</p>
<p>As some comments have already suggested you will need to do a bit of trial and error with your page layout, page size and report contents to ensure that there is no white space pushing onto other pages.</p> <p>The easiest way I have found to do this is to use the <code>Print Layout</code> option when previewing the report in Report Builder (In the middle of the Ribbon when viewing the report preview), which previews the report as it would be exported to actual pages. If it is still not obvious as to why the blank pages are there, you can set different background colours to your report items and report itself to see which colours show on the 'blank' pages. This will show you whether it is a report item or the report page layout that needs to be adjusted.</p>
Unable to get growl notifications during test executions <p>I am trying to explore a feature of adding growl notifications to the tests. This enables the messages to be added on the screen while test execution.</p> <p>I am trying this approach by following steps specified in : <a href="http://elementalselenium.com/tips/53-growl" rel="nofollow">http://elementalselenium.com/tips/53-growl</a></p> <p>Machine: windows 10 Selenium version : 2.53 Browser : Firefox 49</p> <p>Below is script which i am using:</p> <pre><code>public class GrowlTest { static String JGROWL_SCRIPT = "http://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.2.12/jquery.jgrowl.min.js"; static String JQUERY_SCRIPT = "http://code.jquery.com/jquery-1.11.1.min.js"; static String JGROWL_STYLE = "http://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.2.12/jquery.jgrowl.min.css"; static FirefoxDriver driver; public static void main(String [] args) throws InterruptedException { driver =new FirefoxDriver(); driver.manage().window().maximize(); //waitForJStoLoad(); driver.manage().deleteAllCookies(); growlNotification(driver,"hi this is inital test..", "try"); driver.get("http://www.amazon.com"); Thread.sleep(10000); System.out.println("waiting for popup to come.."); driver.findElement(By.xpath("//*[contains(text(),'Stay')]")).click(); System.out.println("clicked on pop up..now waiting for notification..."); Thread.sleep(10000); System.out.println("wait is completed.."); growlNotification(driver,"Hi First try","first:"); Thread.sleep(2000); growlNotification(driver,"Hi second try","second:"); Thread.sleep(2000); growlNotification(driver,"Hi third try","third:"); Thread.sleep(2000); growlNotification(driver,"Hi fourth try","fourth:"); Thread.sleep(2000); driver.quit(); try { Thread.sleep(5000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } private static void growlNotification(WebDriver driver, String msg, String header) throws InterruptedException { FirefoxDriver js=(FirefoxDriver) driver; js.executeScript("if (!window.jQuery) {var jquery = document.createElement('script'); jquery.type = 'text/javascript';jquery.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js';document.getElementsByTagName('head')[0].appendChild(jquery)}"); //TODO Add check for existing jQuery on page js.executeScript( "var jq = document.createElement('script'); jq.type = 'text/javascript'; jq.src = '" + JQUERY_SCRIPT + "'; document.getElementsByTagName('head')[0].appendChild(jq);" ); js.executeScript( "$.getScript(\"" + JGROWL_SCRIPT + "\");" ); js.executeScript( "var lnk = document.createElement('link'); lnk.rel = 'stylesheet'; lnk.href = '" + JGROWL_STYLE + "'; lnk.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(lnk);" ); js.executeScript( "$.jGrowl('" + msg + "', { header: '" + header + "' });" ); } } </code></pre> <p>On executing this i get below error:</p> <blockquote> <p>waiting for popup to come.. clicked on pop up..now waiting for notification... wait is completed.. Exception in thread "main" org.openqa.selenium.WebDriverException: $.jGrowl is not a function Command duration or timeout: 17 milliseconds Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40' System info: host: 'mkarthik-WX-1', ip: '192.168.0.106', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_73' Driver info: org.openqa.selenium.firefox.FirefoxDriver Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=40.0, platform=WINDOWS, nativeEvents=false, acceptSslCerts=true, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}] Session ID: 8249259c-1211-4472-b52f-fc0471061816 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206) at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678) at org.openqa.selenium.remote.RemoteWebDriver.executeScript(RemoteWebDriver.java:577) at com.tests.GrowlTest.growlNotification(GrowlTest.java:74) at com.tests.GrowlTest.main(GrowlTest.java:38) Caused by: org.openqa.selenium.WebDriverException: $.jGrowl is not a function Build info: version: '2.53.0', revision: '35ae25b', time: '2016-03-15 16:57:40' System info: host: 'mkarthik-WX-1', ip: '192.168.0.106', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_73'</p> </blockquote> <p>However, the same script works when i execute the below code :</p> <pre><code>package com.tests; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import com.google.common.base.Predicate; public class GrowlTest { static String JGROWL_SCRIPT = "http://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.2.12/jquery.jgrowl.min.js"; static String JQUERY_SCRIPT = "http://code.jquery.com/jquery-1.11.1.min.js"; static String JGROWL_STYLE = "http://cdnjs.cloudflare.com/ajax/libs/jquery-jgrowl/1.2.12/jquery.jgrowl.min.css"; static FirefoxDriver driver; public static void main(String [] args) throws InterruptedException { driver =new FirefoxDriver(); driver.manage().window().maximize(); //waitForJStoLoad(); driver.manage().deleteAllCookies(); growlNotification(driver,"hi this is inital test..", "try"); driver.get("http://www.amazon.in"); Thread.sleep(10000); System.out.println("waiting for popup to come.."); driver.findElement(By.xpath("//*[contains(text(),'Stay')]")).click(); System.out.println("clicked on pop up..now waiting for notification..."); Thread.sleep(10000); System.out.println("wait is completed.."); growlNotification(driver,"Hi First try","first:"); Thread.sleep(2000); growlNotification(driver,"Hi second try","second:"); Thread.sleep(2000); growlNotification(driver,"Hi third try","third:"); Thread.sleep(2000); growlNotification(driver,"Hi fourth try","fourth:"); Thread.sleep(2000); driver.quit(); try { Thread.sleep(5000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } private static void growlNotification(WebDriver driver, String msg, String header) throws InterruptedException { FirefoxDriver js=(FirefoxDriver) driver; js.executeScript("if (!window.jQuery) {var jquery = document.createElement('script'); jquery.type = 'text/javascript';jquery.src = 'https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js';document.getElementsByTagName('head')[0].appendChild(jquery)}"); //TODO Add check for existing jQuery on page js.executeScript( "var jq = document.createElement('script'); jq.type = 'text/javascript'; jq.src = '" + JQUERY_SCRIPT + "'; document.getElementsByTagName('head')[0].appendChild(jq);" ); js.executeScript( "$.getScript(\"" + JGROWL_SCRIPT + "\");" ); js.executeScript( "var lnk = document.createElement('link'); lnk.rel = 'stylesheet'; lnk.href = '" + JGROWL_STYLE + "'; lnk.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(lnk);" ); js.executeScript( "$.jGrowl('" + msg + "', { header: '" + header + "' });" ); } } </code></pre> <p>Kindly help and suggest what needs to be done.</p> <p>Thanks and regards, Karthik</p>
<p>My best guess is that you need to sleep for a bit in-between js.executeScript() calls to give the javascript that you are calling time to load. If you look, the script you say works has a variety of sleep's between operations, likely to allow for things to load and process.</p>
Compare columns between two data frames R <p>I have two data frames:</p> <pre><code>c1 &lt;- c("chr1:981994","chr1:1025751","chr2:6614300", "chr2:6784300") c2 &lt;- c("G/A","C/T","A/T", "T/G") df1 &lt;- data.frame(c1,c2) a &lt;- c("chr1:981994","chr1:1000000","chr2:6614300", "chr2:6784300") b &lt;- c("G/G","C/C","A/A", "T/T") c &lt;- c("G/G","C/C","A/T", "T/T") d &lt;- c("G/A","C/T","A/T", "T/G") df2 &lt;- data.frame(a, b, c, d) </code></pre> <p>I would like to compare the two data frames and if data in column 1 matches, then compare columns b, c and d against column c2 and if at least TWO columns or more from dataframe 2 (a, b, c and/or d) are different to c2 in dataframe 1 then output this row into a new data frame. So for this example the first and last row of data frame 2 would be outputted as both column 1 entries match and columns b and c are different to c2.</p> <p>I am very new to R, I tried to look at the compare function but got a little overwhelmed. Would very much appreciate any help.</p>
<p>Thanks for the reproducible example. First, you can merge with <code>merge</code>. Have a look at <code>?merge</code> for other configuration options - you can specify the column to merge on using <code>by.x</code> and <code>by.y</code></p> <pre><code>df3 = merge(df1, df2, by.x='c1', by.y='a') # c1 c2 b c d # 1 chr1:981994 G/A G/G G/G G/A # 2 chr2:6614300 A/T A/A A/T A/T # 3 chr2:6784300 T/G T/T T/T T/G </code></pre> <p>Note that the non-matching rows in <code>df1</code> and <code>df2</code> are left out here. Then you can just filter out the rows where <code>c2</code> matches exactly one of columns b,c, d (then by definition it will not match the other two).</p> <p>There are lots of ways to do this, e.g. </p> <pre><code>as.character(df3$c2) == df3[, c('b', 'c', 'd')] # b c d # [1,] FALSE FALSE TRUE # [2,] FALSE TRUE TRUE # [3,] FALSE FALSE TRUE </code></pre> <p>rows with only one TRUE are the ones you want.</p> <pre><code>df3[rowSums(as.character(df3$c2) == df3[, c('b', 'c', 'd')]) == 1, ] </code></pre> <p>Or you could simply loop over all the rows, or use something like <code>apply</code>:</p> <pre><code>apply(df3, 1, function (row) { sum(row['c2'] == row[c('b', 'c', 'd')]) == 1 }) # [1] TRUE FALSE TRUE df3[.Last.value, ] </code></pre>
What is the correct way to get Currency Symbol in Android? <p>This code is working fine but if I change my device langauge this is also show Rs so what the correct way to get currency symbol ?</p> <pre><code>public void displayTotlaPrice() { TextView totalPriceTextView = (TextView) findViewById(R.id.total_Price); totalPriceTextView.setText("Rs" + displayCalculatePrice()); } </code></pre>
<p>Store below variable in <code>string.xml</code></p> <pre><code>&lt;string name="Rs"&gt;\u20B9&lt;/string&gt; </code></pre> <p>Now call it as below wherever you want to display <code>Rs</code> symbol,</p> <pre><code>textView.setText(getResources().getString(R.string.Rs) + "500"); </code></pre>
Odd behavior from canvas drawing other players using socket server <p>I'm trying how to learn how to create a multiplayer game using socket.io. I currently have a server storing all player's locations and sending every player their location, then sending the player everyone else's locations. I am getting those numbers as far as I know they are perfect. I have cross checked each of the locations and they are all like they are supposed to be. For some reason though, I have noticed when drawing the players to the canvas I get some weird behaviors. Here are some examples of what happens. Top left is the player's coordinates and the numbers under that are the other player's coordinates: <a href="http://i.stack.imgur.com/zEa7m.png" rel="nofollow"><img src="http://i.stack.imgur.com/zEa7m.png" alt="enter image description here"></a> From this picture you can see that I can only see one of the players. And the player is towards the bottom left. This would be fine by itself. The other player could be far off in the would and not on the screen.</p> <p><a href="http://i.stack.imgur.com/nlX3T.png" rel="nofollow"><img src="http://i.stack.imgur.com/nlX3T.png" alt="enter image description here"></a> In this picture you can see the same thing as the first picture but there is another cube. Now this makes NO sense. The cube should be the lower left cube and the view should be shifted down to adjust for the cube's y being lower.</p> <p><a href="http://i.stack.imgur.com/YL2kQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/YL2kQ.png" alt="enter image description here"></a> Now this picture is where things make no sense to me. You can only see the last cube and the blue cube is still displaying above and towards the left of the last cube when this cube should BE the last cube.</p> <p>Here is the code I am using. This might not make any sense to you as this is my first try and needs major improvement. Here is the code for the server:</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>var express = require('express'); var app = express(); var serv = require('http').Server(app); var speed = 10 app.get('/', function(req, res) { res.sendFile(__dirname + "/client/index.html"); }); app.use('client', express.static(__dirname + '/client')) app.use(express.static(__dirname + '/client')); serv.listen(2000); characterList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", ".", ",", ":", ";", "!", "@", "#", "$", "%", "^", "&amp;", "*", "(", ")", "-", "_", "[", "]", "(", ")", "&lt;", "&gt;", "|"] var players = [] var connections = [] var io = require('socket.io')(serv, {}); io.sockets.on('connection', function(socket) { var address = socket.request.connection.remoteAddress; players.push({ position: { x: Math.round(Math.random() * 1000), y: Math.round(Math.random() * 1000) } }) connections.push(socket.id) socket.on('request', function(data) { length = data.length if (data.request == 'sessionID') { socket.emit('sendSessionID', { id: socket.id }); } if (data.request == 'players') { var otherPlayers = []; for (var i = 0; i &lt; players.length; i++) { if (connections[i] != data.id) { otherPlayers.push(players[i]) } else { socket.emit('packet', { packetType: 'self', player: players[i] }); console.log[i] } } socket.emit('sendPlayers', { Players: otherPlayers }); } }); socket.on('moveEvent', function(data) { var player = players[find(connections, data.id)] if (data.direction == "x+") { player.position.x = player.position.x + speed } if (data.direction == "y+") { player.position.y = player.position.y + speed } if (data.direction == "x-") { player.position.x = player.position.x - speed } if (data.direction == "y-") { player.position.y = player.position.y - speed } }); function find(arrayName, string) { for (var i = 0; i &lt; arrayName.length; i++) { if (string == arrayName[i]) { return i; } } return null; } function findKey(key) { for (var i = 0; i &lt; arrayName.length; i++) { if (string == arrayName[i].ip) { return i; } } return null; } socket.on('disconnect', function() { var address = socket.request.connection.remoteAddress; players.splice(find(connections, this.id), 1) connections.splice(find(connections, this.id), 1) }); });</code></pre> </div> </div> </p> <p>Here is the code for the Client using a single canvas element on the screen:</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>$(function() { var socket = io(); var sesID = "" var players = [] var player = {} var game = document.getElementById('game') var gamectx = game.getContext('2d'); var GameY = 0; var GameX = 0; var w = false; var a = false; var s = false; var d = false; socket.emit('request', { request: "sessionID" }); socket.on('sendSessionID', function(data) { sesID = data.id }); socket.on('sendPlayers', function(data) { players = data.Players }); socket.on('packet', function(data) { if (data.packetType == 'self') { GameX = data.player.position.x; GameY = data.player.position.y; player = data.player; } }); setInterval(function() { console.log(players.length) if (w == true) { socket.emit('moveEvent', { direction: "y+", id: sesID }) } if (a == true) { socket.emit('moveEvent', { direction: "x+", id: sesID }) } if (s == true) { socket.emit('moveEvent', { direction: "y-", id: sesID }) } if (d == true) { socket.emit('moveEvent', { direction: "x-", id: sesID }) } gamectx.canvas.width = window.innerWidth; gamectx.canvas.height = window.innerHeight; gamectx.clearRect(0, 0, game.width, game.height); socket.emit('request', { request: "players", id: sesID }); for (var i = 0; i &lt; players.length; i++) { gamectx.fillStyle = "#ff0000" gamectx.fillRect(players[i].position.x + GameX, players[i].position.y + GameY, 100, 100) console.log('drew player at ', players[i].position.x + GameX, players[i].position.y + GameY, 100, 100) } gamectx.fillStyle = "#0000ff" gamectx.fillRect(window.innerWidth / 2 - 50, window.innerHeight / 2 - 50, 100, 100); gamectx.font = "48px sans-serif"; gamectx.strokeText("x: " + GameX + ", y: " + GameY, 10, 50); var playersList = "" for (var i = 0; i &lt; players.length; i++) { playersList += "x: " + players[i].position.x + ", y: " + players[i].position.y + ", " } gamectx.font = "30px sans-serif"; gamectx.strokeText(playersList, 10, 100); }, 30); $(document).keydown(function(e) { if (e.which == 65) { a = true; } if (e.which == 68) { d = true; } if (e.which == 87) { w = true; } if (e.which == 83) { s = true } }); $(document).keyup(function(e) { console.log(e.which) if (e.which == 65) { a = false; } if (e.which == 68) { d = false; } if (e.which == 87) { w = false; } if (e.which == 83) { s = false } }); });</code></pre> </div> </div> </p> <p>Here is the html code if needed:</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-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;div id="location-div"&gt; &lt;/div&gt; &lt;canvas id="game"&gt;&lt;/canvas&gt; &lt;head&gt; &lt;script src="https://cdn.socket.io/socket.io-1.4.5.js"&gt;&lt;/script&gt; &lt;script src="js/jquery-3.1.1.min.js"&gt;&lt;/script&gt; &lt;script src="js/game.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="css/index.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Thanks for your help in advance if this makes any sense to anyone!</p>
<h2>All is relative.</h2> <p>In 1D x &amp; canvas center cc = 100. </p> <p>You draw players <code>gameX + x</code> you draw self at <code>cc==100</code> So if self is 150 and player is 200 you draw player at <code>150+200=350</code> but self is drawn at cc making the player <code>350-cc = 250</code> pixels right of self. The player should be 50 pixel right of self <code>canvas.width/2 + 50</code>. </p> <p>To fix draw players at the center of canvas (cc or origin) plus difference between self and player. </p> <pre><code>ctx.drawRect((canvas.width / 2) + (player.x - self.x), ... </code></pre> <p><strong>BTW</strong></p> <p>To make a character array</p> <pre><code>charArr = "0123456789abcdefghijklmnopqrstuvwxyz.,:;!@#$%^&amp;*()-_[]()&lt;&gt;|".split(""); </code></pre> <p>Saves you much typing next time you need such an array.</p> <p>Never rely on data continuity</p> <p>Sending movement only and relying on each client to maintain correct position is never going to work, miss one packet on one machine and every one will have the wrong view. Send absolute position at time (time stamped) plus current delta. Not as a string but encode into smallest packet you can send. </p> <p>Use player's last delta to update position if next packet is late. Revert to actual position when packet does arrive. Allow interaction rollback if you get missing packets late. Ie don't kill player if position was guessed from previous delta and new position proves the hit was a miss. </p> <p>What does now mean?</p> <p>Remember the speed of light is limited, you update at 30ms (3/100th second) this gives light (@~300,000,000mps) time to move 9,000,000m or 9000km, just enough time to move across a country and back, add packet switching, client processing, response transmission delay, etc, for world wide games expect min ping time 150ms + (or limit game to low ping (local) only) We all have different nows, code multiplayer with that in mind.</p>
Closing a react bootstrap modal with escape key <p>I have 6 buttons which, when clicked, activate a modal. This is written in React. </p> <pre><code>//Since I have 6 different modals, giving each of them an id would distinguish them onCloseModal(id) { this.setState({ open: false, modalShown: id }) } render() { return ( &lt;Modal onHide={this.onCloseModal.bind(this, item.id)} keyboard={true}&gt; &lt;Modal.Header closeButton={true} onHide={this.onCloseModal.bind(this)}&gt; &lt;/Modal.Header&gt; &lt;/Modal&gt; ) } </code></pre> <p>I have <code>keyboard={true}</code>, which according to the documentation at <a href="https://react-bootstrap.github.io/components.html#modals-props" rel="nofollow">https://react-bootstrap.github.io/components.html#modals-props</a>, pressing the Escape key would exit the modal. It isn't working however. I believe that I have everything set up because each of my buttons has a unique ID - why isn't the escape key responding?</p> <p>Here's an image of the modal in action.</p> <p><a href="http://i.stack.imgur.com/LriZ3.png" rel="nofollow"><img src="http://i.stack.imgur.com/LriZ3.png" alt="enter image description here"></a></p>
<p>It appears that your component state isn't properly representing the state of the modals. I wrote you <a href="http://jsbin.com/xomegeh/edit?js,output" rel="nofollow">an example</a> (which might not be best practice?) that shows how you can handle the state in a more specified way.</p> <pre><code>onCloseModal() { this.setState({ modalShown: 0 }) } onShowModal(id) { this.setState({ modalShown: id }) } checkModal(id) { if (id == this.state.modalShown) { return true; } else { return false; } } &lt;Modal show={this.checkModal(item.id)} onHide={this.onCloseModal.bind(this)}&lt;/Modal&gt; </code></pre>
Removing Blank Strings from a Spark Dataframe <p>Attempting to remove rows in which a Spark dataframe column contains blank strings. Originally did <code>val df2 = df1.na.drop()</code> but it turns out many of these values are being encoded as <code>""</code>.</p> <p>I'm stuck using Spark 1.3.1 and also cannot rely on DSL. (Importing spark.implicit_ isn't working.)</p>
<p>Removing things from a dataframe requires <code>filter()</code>.</p> <pre><code>newDF = oldDF.filter("colName != ''") </code></pre> <p>or am I misunderstanding your question?</p>
Angularjs How to Toggle div's in ng-repeat? <p>I am working in angularjs and I need to toggle div in <code>ng-repeat</code> but its not working fine. jQuery click is also not working on this. On click of <code>pregroupMem()</code> anchor tag I am calling this function. and data id coming from this function and I am using this as <code>membersList</code> in <code>listdiv</code> div. I need to toggle this div on click of "custom-cn" anchor tag.There are multiple lists and in each of these lists there are there multiple <code>listdivs</code> . I need to toggle the particular div on the click of anchor tag of list. </p> <pre><code>This is my js to get all groups of members. localStorageService.set('grpOpen', grps.openGroups); localStorageService.bind($scope, 'grpOpen'); grs.init = init; function init() { getMyData(); } $scope.data = null; DataService.getMyData().then(function successCallback(response) { $scope.data = response.data.results; $scope.grpOpen.length = 0; $scope.grpOpen.push({'data': response.data.results}); },function errorCallback(response) { }); </code></pre> <p>This is js to get all members list of a group.I have updated this according to your </p> <pre><code>$scope.open = -1; $scope.pregroupMem = function(index,id,e){ $rootScope.membersList = ''; // $rootScope.membersList.length = 0; $scope.loading= true; DataService.getGrpMem(id).success(function (data) { $rootScope.membersList = data.results; $scope.data[index].shown = !$scope.data[index].shown; if( $scope.open &gt;= 0 &amp;&amp; $scope.data[$scope.open] ){ $scope.data[$scope.open].shown = !$scope.data[$scope.open].shown; } if( $scope.open !== index ){ $scope.data[index].shown = !$scope.data[index].shown; } $scope.open = index; }).catch(function (err) { // Log error somehow. }) .finally(function () { // Hide loading spinner whether our call succeeded or failed. $scope.loading = false; }); } &lt;ul&gt; &lt;li ng-repeat="groupsw in grpOpen[0].data track by $index"&gt; &lt;a ng-click="pregroupMem($index,groupsw.grpId,$event)" class="custom-cn" href="javascript:;"&gt;{{ groupsw.grpName }}&lt;/a&gt; &lt;div class="listdiv"&gt; &lt;ul class="userlist"&gt; &lt;li ng-repeat="mymembers in membersList"&gt; &lt;a class="add_user" href="javascript:;"&gt;&lt;i class="fa fa-user-plus"&gt;&lt;/i&gt;&lt;/a&gt; &lt;div class="userlist"&gt; &lt;span class="usnermalissval" ng-if="mymembers.Name != null"&gt;{{mymembers.Name}}&lt;/span&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre>
<p>You can do it in following way:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>angular .module('app', []) .controller('MyController', function($scope) { $scope.data = [ {grpId: 1, grpName: 'One'}, {grpId: 2, grpName: 'Two'}, {grpId: 3, grpName: 'Three'}, {grpId: 4, grpName: 'Four'}, {grpId: 5, grpName: 'Five'} ] $scope.open = -1; $scope.pregroupMem = function(index, id, e) { e.preventDefault(); if( $scope.open &gt;= 0 &amp;&amp; $scope.data[$scope.open] ){ $scope.data[$scope.open].shown = !$scope.data[$scope.open].shown; } if( $scope.open !== index ){ $scope.data[index].shown = !$scope.data[index].shown; } $scope.open = index; } })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="app"&gt; &lt;ul ng-controller="MyController"&gt; &lt;li ng-repeat="groupsw in data"&gt; &lt;a ng-click="pregroupMem($index, groupsw.grpId, $event)" class="custom-cn" href="javascript:;"&gt;{{ groupsw.grpName }}&lt;/a&gt; &lt;div class="listdiv" ng-show="groupsw.shown"&gt; &lt;ul class="userlist"&gt; This is a child div of grpId: {{groupsw.grpId}} &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
SQLAlchemy not finding Postgres table connected with postgres_fdw <p>Please excuse any terminology typos, don't have a lot of experience with databases other than SQLite. I'm trying to replicate what I would do in SQLite where I could ATTACH a database to a second database and query across all the tables. I wasn't using SQLAlchemy with SQLite</p> <p>I'm working with SQLAlchemy 1.0.13, Postgres 9.5 and Python 3.5.2 (using Anaconda) on Win7/54. I have connected two databases (on localhost) using postgres_fdw and imported a few of the tables from the secondary database. I can successfully manually query the connected table with SQL in PgAdminIII and from Python using psycopg2. With SQLAlchemy I've tried:</p> <pre><code># Same connection string info that psycopg2 used engine = create_engine(conn_str, echo=True) class TestTable(Base): __table__ = Table('test_table', Base.metadata, autoload=True, autoload_with=engine) # Added this when I got the error the first time # test_id is a primary key in the secondary table Column('test_id', Integer, primary_key=True) </code></pre> <p>and get the error:</p> <pre><code>sqlalchemy.exc.ArgumentError: Mapper Mapper|TestTable|test_table could not assemble any primary key columns for mapped table 'test_table' </code></pre> <p>Then I tried:</p> <pre><code>insp = reflection.Inspector.from_engine(engine) print(insp.get_table_names()) </code></pre> <p>and the attached tables aren't listed (the tables from the primary database do show up). Is there a way to do what I am trying to accomplish?</p>
<p>In order to map a table <a href="http://docs.sqlalchemy.org/en/latest/faq/ormconfiguration.html#how-do-i-map-a-table-that-has-no-primary-key" rel="nofollow">SQLAlchemy needs there to be at least one column denoted as a primary key column</a>. This does not mean that the column need actually be a primary key column in the eyes of the database, though it is a good idea. Depending on how you've imported the table from your foreign schema it may not have a representation of a primary key constraint, or any other constraints for that matter. You can work around this by either <a href="http://docs.sqlalchemy.org/en/latest/core/reflection.html#overriding-reflected-columns" rel="nofollow">overriding the reflected primary key column</a> in the <strong><code>Table</code> instance</strong> (not in the mapped classes body), or better yet tell the mapper what columns comprise the candidate key:</p> <pre><code>engine = create_engine(conn_str, echo=True) test_table = Table('test_table', Base.metadata, autoload=True, autoload_with=engine) class TestTable(Base): __table__ = test_table __mapper_args__ = { 'primary_key': (test_table.c.test_id, ) # candidate key columns } </code></pre> <p>To inspect foreign table names use the <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.base.PGInspector.get_foreign_table_names" rel="nofollow"><code>PGInspector.get_foreign_table_names()</code></a> method:</p> <pre><code>print(insp.get_foreign_table_names()) </code></pre>
Update fb-like-box onclick with jquery <p>I want to update the facebook like box from the form input. After a check button is clicked. The new like box will appear in the div. </p> <p><strong>HTML</strong></p> <pre><code>&lt;input type="text" class="form-control" placeholder="facebook Page URL" id="fbURL" value="cnn"&gt; &lt;button class="btn btn-primary" type="button" id="fbChk"&gt;check&lt;/button&gt; </code></pre> <p><strong>Javascript</strong></p> <pre><code>$('#fbPage').append('&lt;div id="fb-like" class="fb-like-box" data-href="http://www.facebook.com/RTnews" data-width="500" data-show-faces="true" data-stream="false" data-header="true"&gt;&lt;/div&gt;'); $("#fbChk").click(function() { var fbURL = $("#fbURL").val(); $('#fbPage').html('&lt;div id="fb-like" class="fb-like-box" data-href="http://www.facebook.com/'+fbURL+'" data-width="500" data-show-faces="true" data-stream="false" data-header="true"&gt;&lt;/div&gt;'); }); </code></pre> <p>When I run this script. Old facebox disappear without a new on show.</p>
<p>This could easily be done with a frontend framework like react or so, but in jQuery I see two choices, when you click on the button <code>$.hide()</code> the first div and <code>$.append()</code> the second div or you can dispaly the second div and give the prop <code>display: none</code> . When you click the button, you can show the second div with <code>$.show()</code> and hide the first one..or try to use <code>innerHTML()</code> instead of <code>$.html()</code>.</p>
Move wanted data from json to array using <p>Hey I am trying to move wanted data fron json. So the data inside the json are booking data from a hotel, I got it from query to database. Basically, there are multiple data with same date on it. I just want to move data that I want to php array using simple else if statement but I can't make it works.</p> <p>Here is the rule: 1. So 'booked' is more important than 'available'. Even if it is still 'available', if someone 'booked' it. For example April 10th is 'booked' the only data I want is 'April 10th booked' I don't care if it is still available. This rule also applies to 'full'. 'Booked' is more important than 'full'.</p> <ol start="2"> <li>Last rule: 'Booked' is equvalent with 'Missed' and 'Attended'</li> </ol> <p>Here is the json:</p> <pre><code>array(128) { [0]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 08:00" ["end"]=&gt; string(16) "2016-10-03 08:30" ["id_course"]=&gt; string(5) "55508" ["image"]=&gt; string(92) "http://squline.dev/dashboard/media/images/teacher/2dd22e63084c868044b8d8840ad02e35_thumb.jpg" ["className"]=&gt; string(23) "custom-cursor bg-booked" ["title"]=&gt; string(8) "Attended" } [1]=&gt; array(5) { ["start"]=&gt; string(16) "2016-10-03 08:00" ["end"]=&gt; string(16) "2016-10-03 08:30" ["id_course"]=&gt; string(5) "55508" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" } [2]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 08:30" ["end"]=&gt; string(16) "2016-10-03 09:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(23) "custom-cursor bg-booked" ["title"]=&gt; string(8) "Attended" ["image"]=&gt; string(92) "http://squline.dev/dashboard/media/images/teacher/2dd22e63084c868044b8d8840ad02e35_thumb.jpg" } [3]=&gt; array(5) { ["start"]=&gt; string(16) "2016-10-03 08:30" ["end"]=&gt; string(16) "2016-10-03 09:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" } [4]=&gt; array(5) { ["start"]=&gt; string(16) "2016-10-03 09:00" ["end"]=&gt; string(16) "2016-10-03 09:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" } [5]=&gt; array(5) { ["start"]=&gt; string(16) "2016-10-03 09:30" ["end"]=&gt; string(16) "2016-10-03 10:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" } [6]=&gt; array(5) { ["start"]=&gt; string(16) "2016-10-03 10:30" ["end"]=&gt; string(16) "2016-10-03 11:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" } [7]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 17:00" ["end"]=&gt; string(16) "2016-10-03 17:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [8]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 17:30" ["end"]=&gt; string(16) "2016-10-03 18:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [9]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 18:00" ["end"]=&gt; string(16) "2016-10-03 18:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [10]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 18:30" ["end"]=&gt; string(16) "2016-10-03 19:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [11]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 19:00" ["end"]=&gt; string(16) "2016-10-03 19:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [12]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 19:30" ["end"]=&gt; string(16) "2016-10-03 20:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [13]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 20:00" ["end"]=&gt; string(16) "2016-10-03 20:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [14]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 20:30" ["end"]=&gt; string(16) "2016-10-03 21:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [15]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-03 21:00" ["end"]=&gt; string(16) "2016-10-03 21:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [16]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 08:00" ["end"]=&gt; string(16) "2016-10-04 08:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [17]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 08:30" ["end"]=&gt; string(16) "2016-10-04 09:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [18]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 09:00" ["end"]=&gt; string(16) "2016-10-04 09:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [19]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 09:30" ["end"]=&gt; string(16) "2016-10-04 10:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [20]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 10:00" ["end"]=&gt; string(16) "2016-10-04 10:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [21]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 10:30" ["end"]=&gt; string(16) "2016-10-04 11:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [22]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 13:00" ["end"]=&gt; string(16) "2016-10-04 13:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [23]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 13:30" ["end"]=&gt; string(16) "2016-10-04 14:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [24]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 14:00" ["end"]=&gt; string(16) "2016-10-04 14:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [25]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 14:30" ["end"]=&gt; string(16) "2016-10-04 15:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [26]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 15:00" ["end"]=&gt; string(16) "2016-10-04 15:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [27]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 16:00" ["end"]=&gt; string(16) "2016-10-04 16:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [28]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 16:30" ["end"]=&gt; string(16) "2016-10-04 17:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [29]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 17:00" ["end"]=&gt; string(16) "2016-10-04 17:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [30]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 17:30" ["end"]=&gt; string(16) "2016-10-04 18:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [31]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 18:00" ["end"]=&gt; string(16) "2016-10-04 18:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [32]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 18:30" ["end"]=&gt; string(16) "2016-10-04 19:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [33]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 19:00" ["end"]=&gt; string(16) "2016-10-04 19:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [34]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 19:30" ["end"]=&gt; string(16) "2016-10-04 20:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [35]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 20:00" ["end"]=&gt; string(16) "2016-10-04 20:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [36]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 20:30" ["end"]=&gt; string(16) "2016-10-04 21:00" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [37]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-04 21:00" ["end"]=&gt; string(16) "2016-10-04 21:30" ["id_course"]=&gt; string(5) "55520" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [38]=&gt; array(7) { ["start"]=&gt; string(16) "2016-10-05 08:00" ["end"]=&gt; string(16) "2016-10-05 08:30" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(23) "custom-cursor bg-booked" ["title"]=&gt; string(6) "Missed" ["status"]=&gt; bool(false) ["image"]=&gt; string(92) "http://squline.dev/dashboard/media/images/teacher/2dd22e63084c868044b8d8840ad02e35_thumb.jpg" } [39]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 08:00" ["end"]=&gt; string(16) "2016-10-05 08:30" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [40]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 08:30" ["end"]=&gt; string(16) "2016-10-05 09:00" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [41]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 09:00" ["end"]=&gt; string(16) "2016-10-05 09:30" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [42]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 09:30" ["end"]=&gt; string(16) "2016-10-05 10:00" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [43]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 10:30" ["end"]=&gt; string(16) "2016-10-05 11:00" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [44]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 13:00" ["end"]=&gt; string(16) "2016-10-05 13:30" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [45]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 13:30" ["end"]=&gt; string(16) "2016-10-05 14:00" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [46]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 14:00" ["end"]=&gt; string(16) "2016-10-05 14:30" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [47]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 14:30" ["end"]=&gt; string(16) "2016-10-05 15:00" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [48]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 15:00" ["end"]=&gt; string(16) "2016-10-05 15:30" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-full" ["title"]=&gt; string(4) "Full" ["status"]=&gt; bool(false) } [49]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 15:30" ["end"]=&gt; string(16) "2016-10-05 16:00" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } [50]=&gt; array(6) { ["start"]=&gt; string(16) "2016-10-05 16:00" ["end"]=&gt; string(16) "2016-10-05 16:30" ["id_course"]=&gt; string(5) "55510" ["className"]=&gt; string(21) "custom-cursor bg-past" ["title"]=&gt; string(9) "Available" ["status"]=&gt; bool(false) } </code></pre> <p>My attempt to move data that I want to php array:</p> <pre><code>foreach( $class as $key =&gt; $val ) { if ($xcourse_date != $course_date) { $events[] = $event; $count_x_course_date++; } if( $events[$count_x_course_date - 1]['status'] != 'BOOKED' ) { if ( $events[$count_x_course_date - 1]['status'] != 'AVAILABLE' ) { $events[$count_x_course_date - 1] = $event; } } elseif ( $events[$count_x_course_date - 1]['status'] == 'AVAILABLE' ) { $events[$count_x_course_date - 1] = $event; } $xcourse_date = $val['course_date']; $i++; } </code></pre> <p>My question are: 1. What did I do wrong? 2. I use loop to access all the data inside the json, is there any way easier than looping? 3. My logic says I do no wrong in my code, but the result is far from my expectation, can you point out what's wrong with my programming logic?</p>
<p>In your data set from database, </p> <ol> <li>Some of the records doesn't have status field i.e. records 0-6</li> <li>In your condition your're checking <code>$events[$count_x_course_date - 1]['status'] == 'AVAILABLE'</code> which is wrong. Because from the data set, it's saying value is boolean i.e. true/false <code>["status"] =&gt; bool(false)</code>. </li> <li>Actual values which you're checking is in <code>title</code> field i.e. <code>["title"]=&gt; string(9) "Available"</code></li> </ol>
NLTK AssertionError when taking sentences from PlaintextCorpusReader <p>I'm using a PlaintextCorpusReader to work with some files from Project Gutenberg. It seems to handle word tokenization without issue, but chokes when I request sentences or paragraphs.</p> <p>I start by downloading <a href="http://www.gutenberg.org/cache/epub/345/pg345.txt" rel="nofollow">a Gutenberg book (in UTF-8 plaintext)</a> to the current directory. Then:</p> <pre><code>&gt;&gt;&gt; from nltk.corpus import PlaintextCorpusReader &gt;&gt;&gt; r = PlaintextCorpusReader('.','Dracula.txt') &gt;&gt;&gt; r.words() ['DRACULA', 'CHAPTER', 'I', 'JONATHAN', 'HARKER', "'", ...] &gt;&gt;&gt; r.sents() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/lib/python3.5/dist-packages/nltk/util.py", line 765, in __repr__ for elt in self: File "/usr/local/lib/python3.5/dist-packages/nltk/corpus/reader/util.py", line 296, in iterate_from new_filepos = self._stream.tell() File "/usr/local/lib/python3.5/dist-packages/nltk/data.py", line 1333, in tell assert check1.startswith(check2) or check2.startswith(check1) AssertionError </code></pre> <p>I've tried modifying the book in various ways: stripping off the header, removing newlines, adding a period to the end to finish the last "sentence". The error remains. Am I doing something wrong? Or am I running up against some limitation in NLTK?</p> <p>(Running Python 3.5.0, NLTK 3.2.1, on Ubuntu. Problem appears in other Python 3.x versions as well.)</p> <p>EDIT: Introspection shows the following locals at the point of exception.</p> <pre><code>&gt;&gt;&gt; pprint.pprint(inspect.trace()[-1][0].f_locals) {'buf_size': 63, 'bytes_read': 75, 'check1': "\n\n\n CHAPTER I\n\nJONATHAN HARKER'S JOURNAL\n\n(_Kept i", 'check2': '\n' '\n' ' CHAPTER I\n' '\n' "JONATHAN HARKER'S JOURNAL\n" '\n' '(_Kept in shorthand._)', 'est_bytes': 9, 'filepos': 11, 'orig_filepos': 75, 'self': &lt;nltk.data.SeekableUnicodeStreamReader object at 0x7fd2694b90f0&gt;} </code></pre> <p>In other words, check1 is losing an initial newline somehow.</p>
<p>That particular file has a UTF-8 Byte Order Mark (EF BB BF) at the start, which is confusing NLTK. Removing those bytes manually, or copy-pasting the entire text into a new file, fixes the problem.</p> <p>I'm not sure why NLTK can't handle BOMs, but at least there's a solution.</p>
Thread 1 EXC_bad_instruction (code=exc_1386_invop subcode=0x0) <p>I have a problem with this code. Why is it giving me an error "Thread 1 EXC_bad_instruction (code=exc_1386_invop subcode=0x0)" on "let session" line?</p> <pre><code>import Foundation protocol WeatherServiceDelegate{ func setWeather(weather:Weather) } class WeatherService{ var delegate: WeatherServiceDelegate? func getWeather(city: String){ let path = "http://api.openweathermap.org/data/2.5/weather?q=Boston&amp;" let url = URL(string: path) let session = URLSession.shared.dataTask(with: url!) { (data: Data?, respone:URLResponse?,error: Error?) in print("&gt;&gt;&gt;&gt;&gt;\(data)") } session.resume() </code></pre>
<p>The url Creation isn't working if you're getting "found nil while unwrapping"</p> <p>Generally you should stay away from !s as much as possible and cast them with <code>if let</code> or <code>guard let</code>. In this case I'm not sure why it would be failing, but if you isolate the url creation you might be able to figure out the issue.</p>
Jquery Validation Not Working <p>I am very new to Jquery and hope you guys can help me with this jquery validation problem. Been trying to validate the form but it does not validate at all. It accepts anything that I type in the field, regardless of what restrictions I set. Jquery Validation Not Working Properly it means the same jquery work in one page the page name is login.php but same jquery not working in registration form Here is my code: </p> <pre><code>&lt;?php include("config.php"); &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="//code.jquery.com/jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(function() { $("#frmMain").validate({ rules: { txtOwnerName: "required", day: "required", month: "required", year: "required", txtOwnerAddress: "required", location: "required", city: "required", txtOwnerMobileNo: "required", txtOwnerEmail: "required", pincode: "required", txtDriverName: "required", dayone: "required", monthone: "required", yearone: "required", txtDriverAddress: "required", pincodeone: "required", driverlocation: "required", cityone: "required", txtMobileNo: "required", txtVehicleNo: "required", drpVehicleColor: "required", area: "required", }, messages: { txtOwnerName: "Please Enter Owner Full Name", day: "Please Enter Owner DOB Day", month: "Please Enter Owner DOB Month", txtOwnerAddress: "Please Enter Owner Address", location: "Please Enter Owner Location", city: "Please Enter Owner City", txtOwnerMobileNo: "Please Enter Owner Mobile Number", txtOwnerEmail: "Please Enter Owner Email ID", pincode: "Please Enter Owner Address Pincode", txtDriverName: "Please Enter Driver Name", dayone: "Please Enter Driver DOB Day", monthone: "Please Enter Driver DOB Month", yearone: "Please Enter Driver DOB Year", txtDriverAddress: "Please Enter Driver Address", pincodeone: "Please Enter Driver Address Pincode", driverlocation: "Please Enter Driver Location", cityone: "Please Enter Diver City", txtMobileNo: "Please Enter Driver Mobile Number", txtVehicleNo: "Please Enter vehicle Number", drpVehicleColor: "Please Enter Vehicle Color", area: "Please Enter Pick Up Area", year: "Please Enter Driver DOB Year", }, submitHandler: function(form) { form.btnFinalSumit(); } }); }); &lt;/script&gt; &lt;/head&gt; &lt;?php include('include/header.php'); ?&gt; &lt;body&gt; &lt;?php include('include/top.php'); ?&gt; &lt;div id="main"&gt; &lt;?php include('include/sidebar.php'); ?&gt; &lt;br /&gt; &lt;br /&gt; &lt;section id="content"&gt; &lt;?php include('include/topbar.php'); ?&gt; &lt;form id="frmMain" name="frmMain" method="post"&gt; &lt;div class="container"&gt; &lt;div class="panel-body"&gt; &lt;div class="col-md-10" id="dvownerId" runat="server"&gt; &lt;div class="panel"&gt; &lt;div class="panel-heading"&gt; &lt;div class="panel-title"&gt;Owner Fields &lt;/div&gt; &lt;div class="col-offset-4 col-md-6 pull-right"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;table class="table"&gt; &lt;tr&gt; &lt;td&gt; &lt;Label ID="lblOwnerName"&gt;Name:&lt;Label&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="text" name="txtOwnerName" id="txtOwnerName" Class="form-control"&gt; &lt;/td&gt; &lt;td&gt; &lt;Label ID="lblDOB"&gt;Birth Date:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;select name='day' id='day' style="height:30px;" &gt; &lt;option&gt; Day &lt;/option&gt; &lt;option value='1'&gt;1&lt;/option&gt; &lt;option value='2'&gt;2&lt;/option&gt; &lt;option value='3'&gt;3&lt;/option&gt; &lt;option value='4'&gt;4&lt;/option&gt; &lt;option value='5'&gt;5&lt;/option&gt; &lt;/select&gt; &lt;select name="month" id="month" style="height:30px;" &gt; &lt;option&gt; Month &lt;/option&gt; &lt;option value="January"&gt;January&lt;/option&gt; &lt;option value="Febuary"&gt;Febuary&lt;/option&gt; &lt;option value="March"&gt;March&lt;/option&gt; &lt;option value="April"&gt;April&lt;/option&gt; &lt;option value="May"&gt;May&lt;/option&gt; &lt;option value="June"&gt;June&lt;/option&gt; &lt;option value="July"&gt;July&lt;/option&gt; &lt;option value="August"&gt;August&lt;/option&gt; &lt;option value="September"&gt;September&lt;/option&gt; &lt;option value="October"&gt;October&lt;/option&gt; &lt;option value="November"&gt;November&lt;/option&gt; &lt;option value="December"&gt;December&lt;/option&gt; &lt;/select&gt; &lt;select name='year' id='year' style="height:30px;" &gt; &lt;option&gt; Year &lt;/option&gt; &lt;option value='1947'&gt;1947&lt;/option&gt; &lt;option value='1948'&gt;1948&lt;/option&gt; &lt;option value='1949'&gt;1949&lt;/option&gt; &lt;option value='1950'&gt;1950&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label ID="lblOwnerName"&gt;Address:&lt;Label&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="text" name="txtOwnerAddress" id="txtOwnerAddress" Class="form-control"&gt; &lt;/td&gt; &lt;td&gt; &lt;Label ID="lblPinCode"&gt;Location:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;script src="http://maps.google.com/maps/api/js?key=AIzaSyASnC7M4XLFk6pOrmP4eYZoVloXzJxEFac&amp;sensor=false&amp;libraries=places&amp;region=in" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function initialize() { var input = document.getElementById('location'); var autocomplete = new google.maps.places.Autocomplete(input); } google.maps.event.addDomListener(window, 'load', initialize); &lt;/script&gt; &lt;input id="location" type="text" name="location" class="form-control" autocomplete="on"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label ID="lblOwnerName"&gt;City:&lt;Label&gt;&lt;/td&gt; &lt;td&gt; &lt;select id="city" name="city" Class="form-control"&gt; &lt;option&gt;--Select City--&lt;/option&gt; &lt;option&gt;PUNE&lt;/option&gt; &lt;/td&gt; &lt;td&gt; &lt;Label ID="lblPinCode"&gt;Pincode:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;select id="pincode" name="pincode" Class="form-control"&gt; &lt;option&gt;--Select Pincode--&lt;/option&gt; &lt;option value="411001"&gt;411001&lt;/option&gt; &lt;option value="411002"&gt;411002&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label ID="lblMobileNumber"&gt;Mobile No.:&lt;/Label&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="text" name="txtOwnerMobileNo" id="txtOwnerMobileNo" class="form-control"&gt; &lt;/td&gt; &lt;td&gt; &lt;Label ID="lblEmailId"&gt;Email ID:&lt;/Label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" name="txtOwnerEmail" id="txtOwnerEmail" class="form-control"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label ID="lblTypeOfUser"&gt;Type of User&lt;/Label&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="radio" id="chkTypeofUser" name="chkTypeofUser" value='yes' onclick="data_copy()";&gt; Owner&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;input type="radio" id="chkTypeofUser" name="chkTypeofUser" value='no' onclick="data_copy()";&gt; Driver &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-10" id="dvDriverDetails" runat="server"&gt; &lt;div class="panel"&gt; &lt;div class="panel-heading"&gt; &lt;div class="panel-title"&gt;Driver Fields &lt;/div&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;table class="table"&gt; &lt;tr&gt; &lt;td&gt; &lt;Label id="labelDriverName" &gt;Name:&lt;Label&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="text" id="txtDriverName" name="txtDriverName" class="form-control"&gt; &lt;/td&gt; &lt;td&gt; &lt;Label id="LabelDriverBirthDate" &gt;Birth Date:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;select name='dayone' id='dayone' style="height:30px;" &gt; &lt;option&gt; Day &lt;/option&gt; &lt;option value='1'&gt;1&lt;/option&gt; &lt;option value='2'&gt;2&lt;/option&gt;&gt; &lt;/select&gt; &lt;select name="monthone" id="monthone" style="height:30px;" &gt; &lt;option&gt; Month &lt;/option&gt; &lt;option value="January"&gt;January&lt;/option&gt; &lt;option value="Febuary"&gt;Febuary&lt;/option&gt; &lt;option value="March"&gt;March&lt;/option&gt; &lt;/select&gt; &lt;select name='yearone' id='yearone' style="height:30px;" &gt; &lt;option&gt; Year &lt;/option&gt; &lt;option value='1947'&gt;1947&lt;/option&gt; &lt;option value='1948'&gt;1948&lt;/option&gt; &lt;option value='1949'&gt;1949&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label id="LabelAddress" &gt;Address:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" id="txtDriverAddress" name="txtDriverAddress" class="form-control"&gt; &lt;/td&gt; &lt;td&gt; &lt;Label ID="lblPinCode"&gt;Location:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;script src="http://maps.google.com/maps/api/js?key=AIzaSyASnC7M4XLFk6pOrmP4eYZoVloXzJxEFac&amp;sensor=false&amp;libraries=places&amp;region=in" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function initialize() { var input = document.getElementById('driverlocationone'); var autocomplete = new google.maps.places.Autocomplete(input); } google.maps.event.addDomListener(window, 'load', initialize); &lt;/script&gt; &lt;input id="driverlocationone" type="text" name="driverlocationone" class="form-control" autocomplete="on"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label ID="lblOwnerName"&gt;City:&lt;Label&gt;&lt;/td&gt; &lt;td&gt; &lt;select id="cityone" name="cityone" Class="form-control"&gt; &lt;option&gt;--Select City--&lt;/option&gt; &lt;option&gt;PUNE&lt;/option&gt; &lt;/td&gt; &lt;td&gt; &lt;Label ID="lblPinCode"&gt;Pincode:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;select id="pincodeone" name="pincodeone" Class="form-control"&gt; &lt;option&gt;--Select Pincode--&lt;/option&gt; &lt;option value="411001"&gt;411001&lt;/option&gt; &lt;option value="411002"&gt;411002&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label id="LabelMobileNo" &gt;Mobile No.&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" id="txtMobileNo" name="txtMobileNo" class="form-control"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-10" id="dvVehicleDetails" &gt; &lt;div class="panel"&gt; &lt;div class="panel-heading"&gt; &lt;div class="panel-title"&gt;Vehicle Fields &lt;/div&gt; &lt;/div&gt; &lt;div class="panel-body"&gt; &lt;table class="table"&gt; &lt;tr&gt; &lt;td&gt; &lt;Label id="vehicalno" &gt;Vehicle No.:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" name="txtVehicleNo" id="txtVehicleNo" Class="form-control"&gt; &lt;/td&gt; &lt;td&gt; &lt;Label id="Label8" &gt;Vehicle Company:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;?php $mainVehicle = "SELECT * FROM MainVehicle "; $mainVehicleDisplay = sqlsrv_query($conn, $mainVehicle ); ?&gt; &lt;select id="vehicleCompany" name="vehicleCompany" Class="form-control"&gt; &lt;option&gt;---Select---&lt;/option&gt; &lt;?php while($Main = sqlsrv_fetch_array($mainVehicleDisplay)) { ?&gt; &lt;option value="&lt;?php $Main['id']; ?&gt;"&gt;&lt;?php echo $Main['vehicle_company'];?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label id="Label9" &gt;Vehicle Model:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;?php $vehicleModel = "SELECT * FROM Vehicle_Modle where vehicle_id = '1' "; $vehicleModelDisplay = sqlsrv_query($conn,$vehicleModel); ?&gt; &lt;select id="vehicleModel" name="vehicleModel" Class="form-control"&gt; &lt;option&gt;---Select---&lt;/option&gt; &lt;?php while($model = sqlsrv_fetch_array($vehicleModelDisplay)) { ?&gt; &lt;option&gt;&lt;?php echo $model['vehicle_modle_Name']?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt; &lt;Label id="Label0" &gt;Vehicle Category:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;select id="vehicleCategory" name="vehicleCategory" Class="form-control"&gt; &lt;option&gt;---Select---&lt;/option&gt; &lt;option&gt;AAA&lt;/option&gt; &lt;option&gt;BBB&lt;/option&gt; &lt;option&gt;CCC&lt;/option&gt; &lt;option&gt;DDD&lt;/option&gt; &lt;option&gt;EEE&lt;/option&gt; &lt;option&gt;FFF&lt;/option&gt; &lt;option&gt;GGG&lt;/option&gt; &lt;option&gt;HHH&lt;/option&gt; &lt;option&gt;III&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label id="Label1" &gt;Colour:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;select id="drpVehicleColor" name="drpVehicleColor" Class="form-control"&gt; &lt;option value="WHITE"&gt;WHITE&lt;/option&gt; &lt;option value="BLACK"&gt;BLACK&lt;/option&gt; &lt;option value="BLUE"&gt;BLUE&lt;/option&gt; &lt;option value="RED"&gt;RED&lt;/option&gt; &lt;option value="YELLOW"&gt;YELLOW&lt;/option&gt; &lt;option value="GRAY"&gt;GRAY&lt;/option&gt; &lt;option value="SILVER"&gt;SILVER&lt;/option&gt; &lt;option value="BROWN"&gt;BROWN&lt;/option&gt; &lt;option value="GREEN"&gt;GREEN&lt;/option&gt; &lt;option value="ORANGE"&gt;ORANGE&lt;/option&gt; &lt;option value="INDIGO"&gt;INDIGO&lt;/option&gt; &lt;option value="VIOLET"&gt;VIOLET&lt;/option&gt; &lt;option value="GOLD"&gt;GOLD&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt; &lt;Label id="Label2" &gt;Type:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;select id="drpVehicleColor" name="drpVehicleColor" Class="form-control"&gt; &lt;option&gt;AC&lt;/option&gt; &lt;option&gt;Non-AC&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;Label id="LabelAreaOfPickUP" &gt;Area of Pickup:&lt;Label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="radio" name="area" value="All"&gt; All &amp;nbsp; &amp;nbsp; &lt;input type="radio" name="area" value="Near"&gt; Near &lt;/td&gt; &lt;td colspan="2"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt;&lt;td colspan="1"&gt; &lt;input type="submit" name="btnFinalSumit" id="btnFinalSumit" class="form-control" value="Submit"&gt; &lt;/td&gt; &lt;td&gt;&lt;input type="button" name="btnReset" id="btnReset" class="form-control" value="Reset"&gt;&lt;/td&gt;&lt;td colspan="1"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="maincontent"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I have got a form that uses jQuery validate to validate the contents of the form. but it doesn't seem to be working. Can anyone please help?</p>
<p>Refer this example:</p> <pre><code>$('#form_id').validate({ rules:{ uname : { required: true }, email : { required: true, email : true } }, messages:{ uname : { required: "message" }, email : { required: "message", email : "message" } } }); </code></pre> <p>where form_id is form id of the form for which validation is created. Form must contain two fields with name <strong>uname, email</strong>.</p>
fetch POST from server using react and passport js <p>I have a form that I am submitting as a POST request...</p> <pre><code>&lt;form onSubmit={this.handleLogin.bind(this)} action="/" method="post"&gt; &lt;div&gt; &lt;label&gt;Username:&lt;/label&gt; &lt;input type="text" name="username"/&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Password:&lt;/label&gt; &lt;input type="password" name="password"/&gt; &lt;/div&gt; &lt;div&gt; &lt;input type="submit" value="Log In"/&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>so <code>onSubmit</code> I am calling <code>handleLogin</code> which is attempting to submit a form...</p> <pre><code>handleLogin(){ fetch('http://localhost:8080', { method: 'post', body: JSON.stringify({ username: this.state.username, password: this.state.password }) }) } </code></pre> <p>The form is being submitted to my server, the <code>POST</code> which is supposed to get the request looks as follows...</p> <pre><code>app.post('/', function(req, res, next) { console.log("post"); passport.authenticate('register', function(err, user, info) { console.log("authenticate"); })(req, res, next); }); </code></pre> <p>For some reason <code>user</code> is null and <code>info</code> is false, meaning passport is not called properly. By default, passport js expects a username and password, so I'm not sure if I am supposed to pass username and password through the POST request or not. </p> <p>Here is the rest of my code for <code>passport</code>...</p> <pre><code>passport.use('register', new LocalStrategy({ passReqToCallback : true }, function(req, username, password, done) { process.nextTick(function(){ //find user in DB with this username User.findOne({'username': username}, function(err, user) { if (err) { console.log("Error in registration: " + err); } //If user already exists in DB if (user) { console.log("User already exists"); return done(null, false, req.flash('message', 'User Already Exists')); } else { //if user does not exist, create it var newUser = new User(); newUser.username = username; newUser.password = newUser.generateHash(password); //console.log("hgeeer"); //save the user newUser.save(function(err) { if (err) { console.log('Error in Saving user: '+err); throw err; } console.log("User Registered"); return done(null, newUser); }); } }) }) })); </code></pre> <p>What is the proper way of doing this?</p>
<p>I think you didn't give relevant information to the <code>passport</code></p> <p>Try to give <code>username</code> and <code>password</code> in <code>Strategy</code> </p> <pre><code>passport.use('local-signup', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email',//changed accordingly as `username` passwordField : 'password', passReqToCallback : true // allows us to pass back the entire request to the callback }, </code></pre> <p>You can get reference <a href="https://scotch.io/tutorials/easy-node-authentication-setup-and-local" rel="nofollow">here</a></p>
Exit modal by clicking on background content in React <p>I'm using react-bootstrap (documentation: <a href="https://react-bootstrap.github.io/components.html#modals-props" rel="nofollow">https://react-bootstrap.github.io/components.html#modals-props</a>) and am not sure how I can go about closing a modal by clicking on the background.</p> <p>Currently, I'm closing it through (don't mind the function <code>onCloseModal</code>- it pretty much closes the modal):</p> <pre><code>&lt;Modal closeButton={true} onHide={this.onCloseModal.bind(this)}&gt; &lt;Modal.Header closeButton={true} onHide={this.onCloseModal.bind(this)}&gt; &lt;/Modal.Header&gt; &lt;/Modal&gt; </code></pre> <p>There's no documentation on how to close by clicking on the background. I'm sorry I haven't really tried anything, but I've looked everywhere on Stackoverflow and all solutions correspond to jQuery, not React.</p>
<p>It <strong>does has</strong> in the documentation in <code>props</code> section named <code>backdrop</code></p> <p>If you familiar with Bootstrap, you might know the attribute to describe show/hide the modal while clicking into the background action is called <code>static backdrop</code>.</p> <p>So to close a modal by clicking on the background. Try the below code.</p> <pre><code>&lt;Modal {...this.props} backdrop="true"&gt; &lt;Modal.Header closeButton&gt; &lt;Modal.Title id="contained-modal-title-sm"&gt;Modal heading&lt;/Modal.Title&gt; &lt;/Modal.Header&gt; &lt;Modal.Body&gt; &lt;h4&gt;Wrapped Text&lt;/h4&gt; &lt;/Modal.Body&gt; &lt;Modal.Footer&gt; &lt;Button onClick={this.props.onHide}&gt;Close&lt;/Button&gt; &lt;/Modal.Footer&gt; &lt;/Modal&gt; </code></pre> <p>Note that <code>...this.props</code> is <a href="https://facebook.github.io/react/docs/jsx-spread.html" rel="nofollow">JSX Spread Attributes</a></p>
Weird Behavior of Scala Future and Thread.sleep <p>I'm currently writing codes to extend the Future companion object. One function I want to implement is <code>Any</code></p> <pre><code>//returns the future that computes the first value computed from the list. If the first one fails, fail. def any[T](fs: List[Future[T]]): Future[T] = { val p = Promise[T]() fs foreach { f =&gt; { f onComplete { case Success(v) =&gt; p trySuccess v case Failure(e) =&gt; p tryFailure e } } } p.future } </code></pre> <p>I tried to test my code with</p> <pre><code> test("A list of Futures return only the first computed value") { val nums = (0 until 10).toList val futures = nums map { n =&gt; Future { Thread.sleep(n*1000); n } } val v = Await.result(Future.any(futures), Duration.Inf) assert(v === 0) } </code></pre> <p>But the returned value is 1, not 0. When I switched sleeping time to <code>n*1000</code> to <code>(n+1)*1000</code>, it works fine(returns 0).</p> <p>Is there any special effect when called sleep on 0?</p>
<p><code>Thread.sleep</code> is a blocking operation in your <code>Future</code> but you are not signaling to the <code>ExecutionContext</code> that you are doing so, so the behavior will vary depending on what ExecutionContext you use and how many processors your machine has. Your code works as expected with <a href="http://docs.scala-lang.org/overviews/core/futures.html" rel="nofollow"><code>ExecutionContext.global</code></a> if you add <code>blocking</code>:</p> <pre><code>nums map { n =&gt; Future { blocking { Thread.sleep(n*1000); n } } } </code></pre>
Kubernetes configuration step 2 CentOS 7 <p>From <a href="http://kubernetes.io/docs/getting-started-guides/kubeadm/" rel="nofollow">http://kubernetes.io/docs/getting-started-guides/kubeadm/</a></p> <p>CentOS Linux release 7.2.1511 (Core)</p> <p>(1/4) Installing kubelet and kubeadm on your hosts ..... it's ok</p> <pre><code>$sudo docker -v Docker version 1.10.3, build cb079f6-unsupported $sudo kubeadm version $kubeadm version: version.Info{Major:"1", Minor:"5+", GitVersion:"v1.5.0-alpha.0.1534+cf7301f16c0363-dirty", GitCommit:"cf7301f16c036363c4fdcb5d4d0c867720214598", GitTreeState:"dirty", BuildDate:"2016-09-27T18:10:39Z", GoVersion:"go1.6.3", Compiler:"gc", Platform:"linux/amd64"} $sudo systemctl enable docker &amp;&amp; systemctl start docker $sudo systemctl enable kubelet &amp;&amp; systemctl start kubelet </code></pre> <p>it's ok again</p> <pre><code>$ sudo kubeadm init &lt;master/tokens&gt; generated token: "15a340.9910f948879b5d99" &lt;master/pki&gt; created keys and certificates in "/etc/kubernetes/pki" &lt;util/kubeconfig&gt; created "/etc/kubernetes/kubelet.conf" &lt;util/kubeconfig&gt; created "/etc/kubernetes/admin.conf" &lt;master/apiclient&gt; created API client configuration &lt;master/apiclient&gt; created API client, waiting for the control plane to become ready </code></pre> <p>And at that place proccess stopped. Probably, i can'nt understand something, but RedHat OpenShift version 3 use kubernetes+docker. I tried OpenShift v3 docker version download - it was ok. </p>
<p>I fixed that issue with a likewise setup by declaring the private ip address as localhost in the /etc/hosts file. Example: /etc/hosts</p> <pre><code>10.0.0.2 localhost </code></pre> <p>Then I run a problem where kubectl get nodes threw: </p> <pre><code>The connection to the server localhost:8080 was refused - did you specify the right host or port? </code></pre> <p>This I fixed by copying the generated conf to the local kube config.</p> <pre><code>cp /etc/kubernetes/kubelet.conf ~/.kube/config </code></pre>
How to check if string is part of command "python --version" in bash? <p>In bash, I wish to check whether Python 2.7 is installed. While searching SO I found this: <a href="http://stackoverflow.com/questions/12375722/how-do-i-test-in-one-line-if-command-output-contains-a-certain-string">How do I test (in one line) if command output contains a certain string?</a></p> <p>In bash, I have this:</p> <pre><code>python --version Python 2.7.11 </code></pre> <p>And so I tried this:</p> <pre><code>[[ $(python --version) =~ "2.7" ]] || echo "I don't have 2.7" Python 2.7.11 I don't have 2.7 </code></pre> <p>...which I found strange, as I expected that to work.</p> <p>I also tried this:</p> <pre><code>if [[ $(python --version) =~ *2.7* ]] then echo "I have 2.7" else echo "I don't have 2.7" fi </code></pre> <p>...which resulted in:</p> <pre><code>Python 2.7.11 I don't have 2.7 </code></pre> <p>Hm! What am I doing wrong?</p>
<p><code>python --version</code> command outputs to <code>stderr</code>. </p> <p>You can redirect <code>stderr</code> to <code>stdout</code> prior to test:</p> <pre><code>if [[ $(python --version 2&gt;&amp;1) =~ 2\.7 ]] then echo "I have 2.7" else echo "I don't have 2.7" fi </code></pre>
Could not load file or assembly when generating report <p>A first chance exception of type <code>'System.IO.FileNotFoundException'</code> occurred in <code>mscorlib.dll</code></p> <blockquote> <p>Additional information: Could not load file or assembly 'file:///C:\Program Files (x86)\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjects Enterprise XI</p> </blockquote> <p>Here is my code: </p> <pre><code> Dim Creport As New CrystalReport1 Dset = New DataSet Dset = fncDset() If Dset.Tables(0).Rows.Count &gt; 0 Then Creport.SetDataSource(Dset.Tables(0)) CrystalReportViewer1.ReportSource = Creport CrystalReportViewer1.Refresh() End If </code></pre> <p>Error Occure here <code>Creport.SetDataSource(Dset.Tables(0))</code></p>
<p>You can try this solution. Add this to your config file (app.config).</p> <pre><code>&lt;startup useLegacyV2RuntimeActivationPolicy="true"&gt; &lt;supportedRuntime version="v4.0" sku=".NETFramework, Version=v4.0"/&gt; &lt;/startup&gt; </code></pre>
Use of undeclared type 'URL' in textView(_:shouldInteractWith:in:) <p>I am currently working on a simple app that retrieves some text and sets some UITextView's to the text with link autodetection enabled, and whilst attempting to allow the user to tap on the link, I have run into this issue whereby whilst attempting to implement the UITextView delegate to enable link redirection, the parser gives the error of: <code>Use of undeclared type 'url'</code></p> <p>If I try and use the newer version of textView(_:shouldInteractWith:in:interaction:), the parser also gives the same: <code>Use of undeclared type</code> error for the UITextItemInteraction</p> <pre><code>func textView(textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange) -&gt; Bool { return true } </code></pre>
<p>Check the documentation on that method. There is actually a fourth argument of type <code>UITextItemInteraction</code>. It is most likely declared optional and when you don't list it in your definition it just assumes you don't care about it, but it's still there. And it turns out <code>UITextItemInteraction</code> is only available in iOS 10 and later. If Xcode thinks 9.3 is the latest, your Xcode is out of date. You should update to Xcode 8. You can still target iOS 9 if you really want, but you'll need to mark that method as only available for iOS 10, something the Xcode 8 compiler errors should walk you through.</p>
What's wrong with my button. Can you help me with this? <p>Here's my php file. </p> <pre><code>&lt;?php //Getting the requested id $id = $_GET['id']; //Importing database require_once 'include/Config.php'; //Creating sql query with where clause to get an specific student $sql = "INSERT INTO bus_one (name,address,grade_level,pick_up,dismiss) SELECT name,address,grade_level,pick_up,dismiss FROM students"; //getting result $r = mysqli_query($con,$sql); //pushing result to an array $result = array(); $row = mysqli_fetch_array($r); array_push($result,array( "id"=&gt;$row['id'], "name"=&gt;$row['name'], "add"=&gt;$row['address'], "grad"=&gt;$row['grade_level'], "pick"=&gt;$row['pick_up'], "dis"=&gt;$row['dismiss'] )); //displaying in json format echo json_encode(array('result'=&gt;$result)); mysqli_close($con); ?&gt; </code></pre> <p>Here's my button.</p> <pre><code>private void sendStudent() { class sendStudent extends AsyncTask&lt;Void, Void, String&gt; { ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(BusNumberList.this, "Sending...", "Wait...", false, false); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); Toast.makeText(BusNumberList.this,s,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(Void... params) { RequestHandler rh = new RequestHandler(); String s = rh.sendGetRequestParam(Config.URL_SAVING_TO_BUS_ONE, id); return s; } } sendStudent de = new sendStudent(); de.execute(); } </code></pre> <p>This is why I want to happen. When I Click the button it will automatically get the student details and transfer copy it to my 2nd table. When I run the <code>PHP</code> file it is working but when I try debugging the app the button is not working. Can you help me with this?</p>
<pre><code>There are many ways of calling the function on a button's click. Option 1. Assign function to button's view in xmlfile: android:onClick="sendStudent" If this is the case, then replace "private void sendStudent() {" with "public void sendStudent(View view) {" Option 2. You can also set OnClickListener. Add below code in your OnCreate method. Button b = (Button) findViewById(R.id.button); //Use your button Id b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendStudent(); //Calling method for execution on button click } }); </code></pre>
Union and intersection of 2 deque (unusual segmentation fault) <pre><code>5,10,15,20,25 // first deque 50,40,30,20,10 // second deque </code></pre> <p><code>v</code> is union vector while <code>intersec</code> is intersection vector. Below is the code for finding union and intersection. In case if anyone have more easy solution, pl do share. Finally I want union - intersection.</p> <p>Below is the code which give unusual segmentation fault.</p> <pre><code> deque&lt;int&gt; first = {5,10,15,20,25}; deque&lt;int&gt; second = {50,40,30,20,10}; vector&lt;int&gt; v(first.size()+second.size()); vector&lt;int&gt;::iterator it; sort (first.begin(),first.end()); // 5 10 15 20 25 sort (second.begin(),second.end()); // 10 20 30 40 50 //union //line 79 it=set_union (first.begin(), first.end(), second.begin(), second.end(), v.begin()); v.resize(it-v.begin()); // now finding intersection vector&lt;int&gt; intersec(first.size()+second.size()); it=set_union (first.begin(), first.end(), first.begin(), second.end(), intersec.begin()); intersec.resize(it-intersec.begin()); </code></pre> <p>Now when compiled with -g flag, I used gdb and following is the backtrace stack</p> <pre><code>0x000000000040a010 in std::__copy_move&lt;false, false, std::random_access_iterator_tag&gt;::__copy_m&lt;std::_Deque_iterator&lt;int, int&amp;, int*&gt;, int*&gt; (__first=&lt;error reading variable: Cannot access memory at address 0x0&gt;, __last=0, __result=0x623ef0) at /usr/include/c++/5/bits/stl_algobase.h:340 340 *__result = *__first; (gdb) bt #0 0x000000000040a010 in std::__copy_move&lt;false, false, std::random_access_iterator_tag&gt;::__copy_m&lt;std::_Deque_iterator&lt;int, int&amp;, int*&gt;, int*&gt; ( __first=&lt;error reading variable: Cannot access memory at address 0x0&gt;, __last=0, __result=0x623ef0) at /usr/include/c++/5/bits/stl_algobase.h:340 #1 0x0000000000409156 in std::__copy_move_a&lt;false, std::_Deque_iterator&lt;int, int&amp;, int*&gt;, int*&gt; (__first=0, __last=0, __result=0x623d04) at /usr/include/c++/5/bits/stl_algobase.h:402 #2 0x00000000004077d2 in std::__copy_move_a2&lt;false, std::_Deque_iterator&lt;int, int&amp;, int*&gt;, __gnu_cxx::__normal_iterator&lt;int*, std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt; &gt; (__first=0, __last=0, __result=0) at /usr/include/c++/5/bits/stl_algobase.h:438 #3 0x0000000000405c99 in std::copy&lt;std::_Deque_iterator&lt;int, int&amp;, int*&gt;, __gnu_cxx::__normal_iterator&lt;int*, std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt; &gt; (__first=0, __last=0, __result=0) at /usr/include/c++/5/bits/stl_algobase.h:472 #4 0x0000000000404020 in std::__set_union&lt;std::_Deque_iterator&lt;int, int&amp;, int*&gt;, std::_Deque_iterator&lt;int, int&amp;, int*&gt;, __gnu_cxx::__normal_iterator&lt;int*, std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt;, __gnu_cxx::__ops::_Iter_less_iter&gt; (__first1=0, __last1=0, __first2=0, __last2=0, __result=0, __comp=...) at /usr/include/c++/5/bits/stl_algo.h:4965 #5 0x0000000000402b8c in std::set_union&lt;std::_Deque_iterator&lt;int, int&amp;, int*&gt;, std::_Deque_iterator&lt;int, int&amp;, int*&gt;, __gnu_cxx::__normal_iterator&lt;int*, std::vector&lt;int, std::allocator&lt;int&gt; &gt; &gt; &gt; (__first1=5, __last1=0, __first2=5, __last2=0, __result=5) at /usr/include/c++/5/bits/stl_algo.h:5011 #6 0x0000000000401b3b in main () at test.cpp:79 </code></pre> <p>I am not able to understand the problem in bt.</p>
<p>I think that there is a mistake in set_union() :</p> <pre><code>it=set_union (first.begin(), first.end(), first.begin(), second.end(), intersec.begin()); </code></pre> <p>Correct way Should be :</p> <pre><code>it=set_union (first.begin(), first.end(), second.begin(), second.end(), intersec.begin()); </code></pre> <p>I guess it is a typo.</p>
compare two columns of different files and add new column if it matches <p>I would like to compare the first two columns of two files, if matched need to print yes else no.</p> <p>input.txt</p> <pre><code>123,apple,type1 123,apple,type2 456,orange,type1 6567,kiwi,type2 333,banana,type1 123,apple,type2 </code></pre> <p>qualified.txt</p> <pre><code>123,apple,type4 6567,kiwi,type2 </code></pre> <p>output.txt</p> <pre><code>123,apple,type1,yes 123,apple,type2,yes 456,orange,type1,no 6567,kiwi,type2,yes 333,banana,type1,no 123,apple,type2,yes </code></pre> <p>I was using the below command for split the data, and then i will add one more columm based on the result Now the the input.txt has duplicate(1st column) so the below method is not working, also the file size was huge.</p> <p>Can we get the output.txt in <code>awk</code> one liner?</p> <p><code>comm -2 -3 input.txt qualified.txt</code></p>
<p>You can use <code>awk</code> logic for this as below. Not sure why do you mention one-liner awk command though.</p> <pre><code>awk -v FS="," -v OFS="," 'FNR==NR{map[$1]=$2;next} {if($1 in map == 0) {$0=$0FS"no"} else {$0=$0FS"yes"}}1' qualified.txt input.txt 123,apple,type1,yes 123,apple,type2,yes 456,orange,type1,no 6567,kiwi,type2,yes 333,banana,type1,no 123,apple,type2,yes </code></pre> <p>The logic is </p> <ul> <li>The command <code>FNR==NR</code> parses the first file <code>qualified.txt</code> and stores the entries in column <code>1</code> and <code>2</code> in first file with first column being the index.</li> <li>Then for each of the line in 2nd file <code>{if($1 in map == 0) {$0=$0FS"no"} else {$0=$0FS"yes"}}1</code> the entry in column 1 does not match the array, append the <code>no</code> string and <code>yes</code> otherwise.</li> <li><code>-v FS="," -v OFS=","</code> are for setting input and output field separators</li> </ul>
KeyModifier.SHIFT not working in Sikuli <p>I am new to Sikuli. I need to do Ctrl+Shift+Down in Sikuli. </p> <p>I have tried:</p> <p>type(Key.DOWN, KeyModifier.SHIFT + KeyModifier.CTRL) and type(Key.DOWN, KeyModifier.SHIFT|KeyModifier.CTRL)</p> <p>but none of them works.Both produce the same effect as pressing Ctrl+Down.</p> <p>Please help.</p>
<p>How about this: <br></p> <pre><code># Push down keys. keyDown(Key.CTRL) keyDown(Key.SHIFT) type(Key.DOWN) # Release keys. keyUp() </code></pre>
Method hiding using private access modifier <p>The code in question is: </p> <pre><code>class Student { private void study() { System.out.println("Student is studying"); } public static void main(String args[]) { Student student = new Sam(); student.study(); } } public class Sam extends Student { void study() { System.out.println("Sam is studying"); } } </code></pre> <p>Output: </p> <pre><code>Student is studying </code></pre> <p>An object of class Sam is created and as Student is the superclass we can assign Sam object to a reference variable of type Student. When it is calling the method study, it should be obvious that the object has the study method that prints "Sam is studying". I see people saying that as the Reference type is of Superclass and as the method was hidden it calls the superclass method but I cant digest this because of my understanding of the object and reference type. i.e reference variable is only a pointer to a object(remote control analogy of head first java)</p>
<p>As mentioned in the comments, a private method is automatically final and hidden. You are therefore not able to override any private methods. Therefore the derrived method <code>study</code> will become a brand new method, and will not override the Student's study. </p> <p>See <a href="http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ309_006.htm" rel="nofollow">this</a> link.</p>
Aurelia js providing dynamic content to popover body <p>I am following the structure to implement tool tip from <a href="https://sean-hunter.io/2015/12/24/bootstrap-components-the-aurelia-way/" rel="nofollow">Sean Hunter Blog</a> . Now i want provide tool-tip content as a dynamic html content i.e I want to show one html pattern inside content. How can I provide using Aurelia framework. In knockout JS using custom binding handler I am providing content as with id of division like below code.</p> <p><strong>Knockout Structure is</strong></p> <pre><code> &lt;button data-bind="tooltip: { template: 'ElementId', trigger: 'click', placement: 'right', container: 'body' }"&gt;Click Me&lt;/button&gt; &lt;div id="ElementId" style="display: none;"&gt; &lt;div&gt;Dynamic content will go here&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>How to achieve same with Aurelia Structure:</strong></p> <pre><code>&lt;template&gt; &lt;require from="templates/popover/tooltip"&gt;&lt;/require&gt; &lt;button data-toggle="tooltip" tooltip="placement:bottom;trigger:click;html:true;template:'ElementId';title:tooltip Header"&gt;Click Me&lt;/button&gt; &lt;div id="ElementId" style="display: none;"&gt; &lt;div&gt;Dynamic content will go here&lt;/div&gt; &lt;/div&gt; &lt;/template&gt; </code></pre> <p><strong>Custom Attribute code</strong></p> <pre><code>import {customAttribute, inject, bindable} from 'aurelia-framework'; import $ from 'bootstrap'; @customAttribute('tooltip') @inject(Element) export class Tooltip { element: HTMLElement; @bindable title: any; @bindable placement: any; @bindable content: any; @bindable template: any; constructor(element) { this.element = element; } bind() { if (this.content) { $(this.element).tooltip({ title: this.title, placement: this.placement, content: this.content }); } else { $(this.element).tooltip({ title: this.title, placement: this.placement, template: $('#'+this.template).html() }); } } // gets fired when the provided value changes, although not needed in this example since the json from reddit is static titleChanged(newValue) { $(this.element).data('bs.tooltip').options.title = newValue; } contentChanged(newValue) { if (this.content) { $(this.element).data('bs.tooltip').options.content = newValue; } else { $(this.element).data('bs.tooltip').options.template = newValue; } } placementChanged(newValue) { $(this.element).data('bs.tooltip').options.placement = newValue; } } </code></pre>
<p>You would need to implement the rest of bootstrap's <code>popover</code> API in your custom attribute, and add some logic to turn a selector into a template.</p> <p><strong>Here's an example: <a href="https://gist.run?id=909c7aa984477a465510abe2fd25c8a1" rel="nofollow">https://gist.run?id=909c7aa984477a465510abe2fd25c8a1</a></strong></p> <p>Note: i've added the default values from <a href="http://getbootstrap.com/javascript/#popovers" rel="nofollow">bootstrap popovers</a> for clarity</p> <h1>With a custom attribute:</h1> <p><strong>src/app.html</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;template&gt; &lt;h1&gt;${message}&lt;/h1&gt; &lt;button class="btn btn-block btn-default" popover="title.bind: message; placement: top"&gt;Default popover&lt;/button&gt; &lt;button class="btn btn-block btn-default" popover="title.bind: message; template-selector: #popoverTemplate; placement: bottom; html: true"&gt;Custom popover&lt;/button&gt; &lt;div id="popoverTemplate"&gt; &lt;div class="popover" role="tooltip"&gt; &lt;div class="arrow"&gt;&lt;/div&gt; &lt;h3 class="popover-title"&gt;&lt;/h3&gt; &lt;div&gt;Some custom html&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; </code></pre> <p><strong>src/app.ts</strong></p> <pre class="lang-ts prettyprint-override"><code>export class App { message = "Hello world"; } </code></pre> <p><strong>src/popover.ts</strong></p> <pre class="lang-ts prettyprint-override"><code>import {inject, customAttribute, bindable, DOM} from "aurelia-framework"; @customAttribute("popover") @inject(DOM.Element) export class Popover { public element: HTMLElement; constructor(element) { this.element = element; } @bindable({defaultValue: true}) public animation: boolean; @bindable({defaultValue: false}) public container: (string | false); @bindable({defaultValue: 0}) public delay: (number | object); @bindable({defaultValue: false}) public html: boolean; @bindable({defaultValue: "right"}) public placement: (string | Function); @bindable({defaultValue: false}) public selector: (string | false); @bindable({defaultValue: `&lt;div class="popover" role="tooltip"&gt;&lt;div class="arrow"&gt;&lt;/div&gt;&lt;h3 class="popover-title"&gt;&lt;/h3&gt;&lt;div class="popover-content"&gt;&lt;/div&gt;&lt;/div&gt;`}) public template: string; @bindable({defaultValue: false}) public templateSelector: (string | false); @bindable({defaultValue: ""}) public title: (string | Function); @bindable({defaultValue: "click"}) public trigger: string; @bindable({defaultValue: { selector: "body", padding: 0 }}) public viewport: (string | Object | Function); public attached(): void { let template; if (this.templateSelector) { const templateElement = document.querySelector(this.templateSelector); template = templateElement.innerHTML; } else { template = this.template; } $(this.element).popover({ animation: this.animation, container: this.container, delay: this.delay, html: this.html, placement: this.placement, selector: this.selector, template: template, title: this.title, trigger: this.trigger, viewport: this.viewport }); } } </code></pre> <h1>With a custom element:</h1> <p>This is in response to @Ashley Grant's comment. It could improve clarity if you used a custom element for this. I'm not sure of the implementation he had in mind, but this would be one way to make it work without really losing flexibility.</p> <p><strong>src/app.html</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;template&gt; &lt;h1&gt;${message}&lt;/h1&gt; &lt;popover-element title.bind="message" placement="bottom"&gt; &lt;/popover-element&gt; &lt;popover-element title.bind="message" placement="bottom"&gt; &lt;button slot="popoverTarget" class="btn btn-block btn-default"&gt; Custom popover (custom element) &lt;/button&gt; &lt;div slot="popoverTemplate" class="popover" role="tooltip"&gt; &lt;div class="arrow"&gt;&lt;/div&gt; &lt;h3 class="popover-title"&gt;&lt;/h3&gt; &lt;div&gt;Some custom html&lt;/div&gt; &lt;div&gt;Message: ${message}&lt;/div&gt; &lt;/div&gt; &lt;/popover-element&gt; &lt;/template&gt; </code></pre> <p><strong>src/app.ts</strong></p> <pre class="lang-ts prettyprint-override"><code>export class App { message = "Hello world"; } </code></pre> <p><strong>src/popover-element.html</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;template&gt; &lt;div ref="target"&gt; &lt;slot name="popoverTarget"&gt; &lt;button class="btn btn-block btn-default"&gt;Default popover (custom element)&lt;/button&gt; &lt;/slot&gt; &lt;/div&gt; &lt;div ref="template"&gt; &lt;slot name="popoverTemplate"&gt; &lt;div class="popover" role="tooltip"&gt; &lt;div class="arrow"&gt;&lt;/div&gt; &lt;h3 class="popover-title"&gt;&lt;/h3&gt; &lt;div class="popover-content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/slot&gt; &lt;/div&gt; &lt;/template&gt; </code></pre> <p><strong>src/popover-element.ts</strong></p> <pre class="lang-ts prettyprint-override"><code>import {customElement, bindable} from "aurelia-framework"; @customElement("popover-element") export class PopoverElement { public template: HTMLElement; public target: HTMLElement; @bindable({defaultValue: true}) public animation: boolean; @bindable({defaultValue: false}) public container: (string | false); @bindable({defaultValue: 0}) public delay: (number | object); @bindable({defaultValue: false}) public html: boolean; @bindable({defaultValue: "right"}) public placement: (string | Function); @bindable({defaultValue: false}) public selector: (string | false); @bindable({defaultValue: ""}) public title: (string | Function); @bindable({defaultValue: "click"}) public trigger: string; @bindable({defaultValue: { selector: "body", padding: 0 }}) public viewport: (string | Object | Function); public attached(): void { $(this.target.firstElementChild).popover({ animation: this.animation, container: this.container, delay: this.delay, html: this.html, placement: this.placement, selector: this.selector, template: this.template.firstElementChild.outerHTML, title: this.title, trigger: this.trigger, viewport: this.viewport }); } } </code></pre>
I want to trigger a response at different points in a loop <p>I have created a task on Psychopy in which beads a drawn from a jar. 50 different beads are drawn and after each bead the participant is asked to make a probability rating. The task is looped from an excel file but it takes too long to do 50 ratings. I was hoping to get ratings for the first 10 beads. Then draw up a rating for ever second bead until 20 beads are drawn. Then for the next 30 beads until the 50th bead to only ask for a rating every five beads drawn (I'm really new to coding, sorry for how incorrect this may be in advance). I've written the code like this however unfortunately it doesn't work? (on the turns that don't have a rating i've tried to put a keyboard response to trigger the next thing in the sequence to emerge) -</p> <pre><code>for row_index, row in (beads_params_pinkbluegreyratingparamters.xlsx): if row(0:10) and t &gt;= 0.0 and rating.status == NOT_STARTED: break rating.tStart = t # underestimates by a little under one frame rating.frameNStart = frameN # exact frame index rating.setAutoDraw(True) continueRoutine &amp;= rating.noResponse # a response ends the trial elif row(12:20:2) and t &gt;= 0.0 and rating.status == NOT_STARTED: break rating.tStart = t # underestimates by a little under one frame rating.frameNStart = frameN # exact frame index rating.setAutoDraw(True) continueRoutine &amp;= rating.noResponse elif rows.event.getkeys, row(11:19:2): elif len(theseKeys) &gt; 0: break key_resp_2.keys = theseKeys [-1] key_resp_2.rt = key_resp_2.clock.getTime() continueRoutine = False elif row(20:50:5) and t &gt;= 0.0 and rating.status == NOT_STARTED: break rating.tStart = t # underestimates by a little under one frame rating.frameNStart = frameN # exact frame index rating.setAutoDraw(True) continueRoutine &amp;= rating.noResponse rows.event.getKeys, row[21, 22, 23, 24, 26, 27, 28, 29, 31, 32, 33, 34, 36, 37, 38 ,39, 41, 42, 43, 44, 46, 47, 48, 49]: elif len(theseKeys) &gt; 0: key_resp_2.Keys = theseKeys [-1] key_resp_2.rt = key_resp_2.clock.getTtime() continueRoutine = False </code></pre>
<p>You should loop only once, but perform all checks inside that one loop:</p> <pre><code>for row_index, rows in (beads_params_pinkbluegreyratingparamters.xlsx): if (row_index &lt; 10): rows.ratingscale(0:10) elif (row_index &gt;=10 and row_index &lt;20): rows.ratingscale(12:20:2) rows.key_resp_2(11:19:2) elif (row_index &gt;=20): rows.ratingscale(25:50:5) rows.key_resp_2[21, 22, 23, 24, 26, 27, 28, 29, 31, 32, 33, 34, 36, 37, 38, 39, 41, 42, 43, 44, 46, 47, 48, 49] </code></pre> <p>Note that there are some syntax errors in your code, e.g. <code>rows.key_resp_2(11:19:2)</code> doesn't make sense.</p>
Android intent.getStringExtra() return null <p>MainActivity </p> <pre><code>public class MainActivity extends AppCompatActivity { private static final int REQ_CODE_TO_ADD = 123; final ArrayList&lt;Contact&gt; allContact = new ArrayList(); ArrayList&lt;String&gt; name = new ArrayList(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Intent intent = new Intent(this,DetailActivity.class); Button addbt = (Button)findViewById(R.id.addbt); public void onClickAdd(View v){ Intent intent = new Intent(this,AddContactActivity.class); startActivityForResult(intent,REQ_CODE_TO_ADD); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == REQ_CODE_TO_ADD){ if(resultCode == 0){ Intent intent = getIntent(); String name2 = intent.getStringExtra("namev"); String email2 = intent.getStringExtra("emailv"); String birthday2 = intent.getStringExtra("birthdayv"); Log.d("AAA","&gt;&gt;&gt;:"+name2); Contact person = new Contact(name2,email2,birthday2); allContact.add(person); }} } } </code></pre> <p>AddContactActivity</p> <pre><code>public class AddContactActivity extends AppCompatActivity { private static final int REQ_CODE_TO_MAIN = 321; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_contact); } public void onClickOk(View v){ EditText name = (EditText)findViewById(R.id.nameet); EditText email = (EditText)findViewById(R.id.email); EditText birthdate = (EditText)findViewById(R.id.birthdate); Intent intent = new Intent(); intent.putExtra("namev",name.getText().toString()); intent.putExtra("emailv",email.getText().toString()); intent.putExtra("birthdayv",birthdate.getText().toString()); setResult(0,intent); finish(); } } </code></pre> <p>AddContactActivity I already use intent.putExtra name.getText().toString() and send intent to MainActivity</p> <p>Why onActivityResult() in MainActivity Log.d output is null?</p>
<pre><code>if(resultCode == 0){ //Intent intent = getIntent(); String name2 = data.getStringExtra("namev"); String email2 = data.getStringExtra("emailv"); String birthday2 = data.getStringExtra("birthdayv"); Log.d("AAA","&gt;&gt;&gt;:"+name2); Contact person = new Contact(name2,email2,birthday2); allContact.add(person); }} </code></pre> <p>you need to use the <strong>data</strong> not getIntent()</p>
How to edit child pages in wordpress <p>Is there any way to edit child pages like <code>mywebsite.com/page/childpage</code> in wordpress. Actually i want to edit product category page in woocommerce. I want to add a div on the top of product catogery page. I am searching for this since 2 days on google but i didn't get solution. </p>
<p>If you need to add this div to all category pages (i.e. <a href="http://yourwebsite.com/product-category/category-name/" rel="nofollow">http://yourwebsite.com/product-category/category-name/</a>) then you need to edit the <code>archive-product.php</code> template. It is located at <code>\wp-content\plugins\woocommerce\templates</code>, but <strong>don't</strong> edit it there! </p> <p>Create <code>woocommerce</code> folder in your theme's folder and copy the file there, then edit. It will overwrite the default template and will be safe for Woocommerce updates, since they won't overwrite this folder. If you edit it in the original path you might loose your code with the next update.</p> <p>Here's a <a href="https://docs.woocommerce.com/document/template-structure/" rel="nofollow">link to details</a> on this.</p> <p>And if you want to edit the description for a specific category, you can do it in the admin panel under Products > Categories.</p>
Expanding a slice's size to prevent slice bounds out of range error <p>I have written the following:</p> <pre><code>func main() { //inside main fileInputBytes, err := ioutil.ReadFile("/tmp/test") byteSize2 := len(fileInputBytes) var inputFileByteSlice = fileInputBytes[0:] var numberOfIndexes = math.Floor(float64(byteSize / indexingOffset)) for i := 1; i &lt;= int(numberOfIndexes); i++ { // adding i to the indexer insures that we use lookahed to ignore previously inserted indexing values var v int = (i * indexingOffset) + i Insert(&amp;inputFileByteSlice, v+i, indexingByteValue) fmt.Println(i) } } //outside main //variation of https://blog.golang.org/slices with pointers and such func Insert(slice *[]byte, index int, value byte) { // Grow the slice by one element. (*slice) = (*slice)[0 : len(*slice)+1] // Use copy to move the upper part of the slice out of the way and open a hole. copy((*slice)[index+1:], (*slice)[index:]) // Store the new value. (*slice)[index] = value // Return the result. } </code></pre> <p>The <code>slice bounds out of range</code> error is getting on my nerves. The length of the slice grows outside of the size and overflows, the reason I don't understand is that I thought the call to 'grow' the slice by one element(before copy) will dynamically allocate more space. Since that is not the case, can anyone offer me a better suggestion?</p>
<p>First of all, a slice is already a reference type. So you don't need to pass its pointer around if you are not going to change its capacity. So your <code>main</code> can be simplified as:</p> <pre><code>func main() { fileInputBytes, err := ioutil.ReadFile("/tmp/test") byteSize2 := len(fileInputBytes) // No need to use pointer to slice. If you want a brand new slice // that does not affect the original slice values, use copy() inputFileByteArray := fileInputBytes var numberOfIndexes = math.Floor(float64(byteSize / indexingOffset)) for i := 1; i &lt;= int(numberOfIndexes); i++ { var v int = (i * indexingOffset) + i // Insert needs to return the newly updated slice reference // which should be assigned in each iteration. inputFileByteArray = Insert(inputFileByteArray, v+i, indexingByteValue) fmt.Println(i) } } </code></pre> <p>Then, the <code>Insert</code> function can be simplified simply by using <code>append</code> along with <code>copy</code> and returning the newly created slice:</p> <pre><code>func Insert(slice []byte, index int, value byte) []byte { if index &gt;= len(slice) { // add to the end of slice in case of index &gt;= len(slice) return append(slice, value) } tmp := make([]byte, len(slice[:index + 1])) copy(tmp, slice[:index]) tmp[index] = value return append(tmp, slice[index:]...) } </code></pre> <p>This may not be the best implementation but it is simple enough. Example usage at: <a href="https://play.golang.org/p/Nuq4RX9XQD" rel="nofollow">https://play.golang.org/p/Nuq4RX9XQD</a></p>
Javascript object comparision for each key and value <pre><code>var obj1 = {a:1, b:2, c:3}; var obj2 = {a:3, b:2, c:1}; </code></pre> <p>How to compare the objects are equal or not using javascript (for loop).</p> <p>I tried comparing both the objects by converting via stringify, but the comparison fails when the keys are misplaced or not in the correct order.</p>
<p>Go like this</p> <pre><code>Object.defineProperty(Object.prototype,"equals", { value: function (array) { for ( key in this ) if ( ! ( array[key] === this[key] ) ) return false; for ( key in array ) if ( ! ( array[key] === this[key] ) ) return false; return true; } }); </code></pre> <p>which will add a <code>equals</code>-method to all objects. You can use it like this:</p> <pre><code>[0,1,2].equals([0,1,2]); // true [0,1,2].equals([0,1,3]); // false [0,1,2].equals([0,1,2,3]); // false obj1.equals(obj2); // true </code></pre> <p>Note that this function doesn't compare in a sense of comparing "deep".</p>
Label Put Before Center AutoLayout <p>I want to put a label just before center.</p> <p>I am unable to do this and i am unable to find any link how we do this.I am newer in iOS. I am unable to do this.</p> <p>Any help would be appreciated.</p>
<p>The best way is to do the following</p> <ul> <li>Center the UILabel Horizontally with the View Controller's view</li> <li>Open the constraint and change label.Center X to label.Trailing</li> </ul> <p><a href="http://i.stack.imgur.com/9awCu.png" rel="nofollow"><img src="http://i.stack.imgur.com/9awCu.png" alt="enter image description here"></a></p>
What difference between @load() and ${} <p>code:</p> <pre><code>&lt;zk&gt; &lt;vbox r="@ref(1)"&gt; &lt;label value="${empty r}" /&gt; &lt;label value="@load(empty r)" /&gt; &lt;/vbox&gt; &lt;/zk&gt; </code></pre> <p>returns:</p> <pre><code>true false </code></pre> <p>${} not working with @ref()?</p>
<p>Short answer : no it doesn't.</p> <p>First, if you want automatic updates of values use <code>@load(...)</code> because static expressions in <code>${...}</code> are only evaluated once.</p> <p>Second, bind annotations @init/@load are being computed later in the ZK Bind lifecycle than the static EL expressions.</p> <p>So ZK first tries and evaluate your <code>${empty r}</code>, at this time r is not defined so <code>${empty r}</code> is null. Then later in the lifecycle it'll handle the databinding annotations @.</p>
Accessing php session while using Angular Routing <p>I am using Angular routing and want to access a php session variable in the view. </p> <pre><code>&lt;?php session_start(); //print_r($_SESSION['query']); the variable is available and will print here ?&gt; &lt;script&gt; var x = &lt;?$_SESSION['query']?&gt; console.log("x: " , x) //this returns undefined &lt;/script&gt; </code></pre> <p>I'm trying to pass the session variable as a parameter in function, but it is not available here either.</p> <pre><code>ng-init="mc.makeQuery(&lt;?($_SESSION['query'])?&gt;)" </code></pre>
<p>You can start session on your page like and create hidden field for session like this</p> <pre><code>&lt;input type="hidden" name="mysession" id="mysession"&gt; </code></pre> <p>and write javascript function some thing like this</p> <pre><code>function Result(){ var marks = 55; document.getElementById("mysession").innerHTML= &lt;?php echo session_id();?&gt;; document.getElementById("hdnmarks").innerHTML= marks; document.getElementById('Form').submit(); } </code></pre> <p>change the Form name with your form name.</p>
If I can't take more than one character as character variable, then what is the way to declare grade='A+'? <p>I can declare character A, B, C, D etc as grades. But couldn't declare 'A+'.</p> <p>So, if I can't take more than one character as character variable, then what is the way to declare grade='A+'? </p>
<p>You can use <a href="https://en.wikibooks.org/wiki/C_Programming/Strings" rel="nofollow"><strong>strings</strong></a> <em>(collection of characters with a null terminating character at the end, click on it to see more)</em> instead of characters. You can declare them this way</p> <pre><code>char grade[3] = "B+"; //one byte for 'B' //one for '+' //extra byte for null terminating character i.e, '\0' </code></pre> <p>Now, you can compare strings using the <a href="http://www.cplusplus.com/reference/cstring/strcmp/" rel="nofollow">strcmp()</a> function of <code>string.h</code> header file. Here's an example of how to use it:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; //to use strcmp() function int main(void) { char grade[3] = "B+"; //NOTE: strcmp() returns 0 if both strings sent as arguments are equal if(strcmp(grade, "A+") == 0) printf("garde is A+"); else if(strcmp(grade, "B+") == 0) printf("garde is B+"); else if(strcmp(grade, "C+") == 0) printf("garde is C+"); return 0; } </code></pre> <p><strong>output:</strong></p> <pre><code>garde is B+ </code></pre>
Calling a REST webservice from ReactJS <p>I was trying to call a REST webservice to fetch data from the database and return a JSON object back to the ReactJS app.When I access the URL from the browser it displays the JSON object but when I try to render the data in the table no content is displayed.</p> <p>My sample code looks like</p> <pre><code>import React from 'react'; import $ from 'jquery'; export default class Members extends React.Component { constructor(props) { super(props); this.state = { users: [] }; } componentDidMount() { $.ajax({ url: "http://localhost:8080/users" }).then(function(data) { this.setState({ users:data }); }); } render() { return ( &lt;UsersList users={this.state.users}/&gt; ) } } class UsersList extends React.Component { render() { var users = this.props.users.map(users =&gt; &lt;User key={user._links.self.href} user={user}/&gt; ); return ( &lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;/tr&gt; {users} &lt;/tbody&gt; &lt;/table&gt; ) } } class User extends React.Component { render() { return ( &lt;tr&gt; &lt;td&gt;{this.props.user.firstName}&lt;/td&gt; &lt;td&gt;{this.props.user.lastName}&lt;/td&gt; &lt;/tr&gt; ) } } </code></pre> <p>Is this a problem of asynchronous loading ?</p>
<p>According to <a href="http://stackoverflow.com/questions/23959912/ajax-cross-origin-request-blocked-the-same-origin-policy-disallows-reading-the">this</a> question JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on script tags. Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results.Try to use JSONP in your Ajax call. It will bypass the Same Origin Policy.like this : </p> <pre><code> componentDidMount() { $.ajax({ url: "http://localhost:8080/users", async:true, dataType : 'jsonp' //you may use jsonp for cross origin request crossDomain:true, }).then(function(data) { this.setState({ users:data }); }); } </code></pre> <p>Good answer on stackoverflow: <a href="http://stackoverflow.com/questions/3506208/jquery-ajax-cross-domain">jQuery AJAX cross domain</a></p>
After sorting JSONArray,Custom list view not changed? <p>I am sorting JSONArray and show them in a custom list view, but after sorting the data does not changed in custom list view.</p> <p>Here is my code for fab button to select which sort is to be perform:</p> <pre><code>fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder builder=new AlertDialog.Builder(SearchResult.this); builder.setTitle("Sort List Item"); builder.setItems(new CharSequence[]{"By Name", "By Father Name","By EPIC","By House Number"}, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { switch (i) { case 0: Toast.makeText(getApplicationContext(), "By Name", Toast.LENGTH_SHORT).show(); sortJsonTechnique="1"; if (myData) { sortByName(sortdata,sortJsonTechnique); } break; case 1: Toast.makeText(getApplicationContext(), "By Father Name", Toast.LENGTH_SHORT).show(); sortJsonTechnique="2"; if (myData) { sortByName(sortdata,sortJsonTechnique); } break; case 2: Toast.makeText(getApplicationContext(), "By EPIC", Toast.LENGTH_SHORT).show(); sortJsonTechnique="3"; if (myData) { sortByName(sortdata,sortJsonTechnique); } break; case 3: Toast.makeText(getApplicationContext(), "By House Number", Toast.LENGTH_SHORT).show(); sortJsonTechnique="4"; if (myData) { sortByName(sortdata,sortJsonTechnique); } break; default: break; } } }); builder.show(); } }); </code></pre> <p>And after selection made in fab button click i sort json array. Here is code for parse json array:</p> <pre><code> private void sortByName(String mysortJson,String sortType) { List&lt;JSONObject&gt; jsonObjects=new ArrayList&lt;JSONObject&gt;(); try { JSONObject object=new JSONObject(mysortJson); JSONArray jsonArray=object.getJSONArray("Data"); for (int i=0;i&lt;jsonArray.length();i++) { jsonObjects.add(jsonArray.getJSONObject(i)); } if (sortType.equals("1")) { Collections.sort(jsonObjects, new Comparator&lt;JSONObject&gt;() { @Override public int compare(JSONObject a, JSONObject b) { String val1=new String(); String val2=new String(); try { val1=(String) a.get("Name"); // Log.e("Value1",""+val1); val2=(String) b.get("Name"); // Log.e("Value2",""+val2); } catch (JSONException e) { e.printStackTrace(); } return val1.compareTo(val2); } }); for (int j=0;j&lt;jsonObjects.size();j++) { jsonArray.put(jsonObjects.get(j)); } voter_id=new String[jsonArray.length()]; boothname_id=new String[jsonArray.length()]; voter_name=new String[jsonArray.length()]; voter_f_m_h_name=new String[jsonArray.length()]; voter_epic=new String[jsonArray.length()]; voter_h_no=new String[jsonArray.length()]; voter_mobile=new String[jsonArray.length()]; voter_gender=new String[jsonArray.length()]; voter_age=new String[jsonArray.length()]; get_voter_dob=new String[jsonArray.length()]; get_marriage_anniv=new String[jsonArray.length()]; get_voter_caste_id=new String[jsonArray.length()]; get_voter_status_id=new String[jsonArray.length()]; get_voter_social_status_id=new String[jsonArray.length()]; for (int c=0;c&lt;jsonArray.length();c++) { JSONObject fetchVoter = jsonArray.getJSONObject(c); voter_id[c] = fetchVoter.getString(KEY_VOTER_ID); boothname_id[c] = fetchVoter.getString(KEY_BOOTHNAME_ID); voter_name[c] = fetchVoter.getString(KEY_SEARCH_NAME); voter_f_m_h_name[c] = fetchVoter.getString(KEY_SEARCH_F_H_M_NAME); voter_epic[c] = fetchVoter.getString(KEY_SEARCH_EPIC_NAME); voter_h_no[c] = fetchVoter.getString(KEY_SEARCH_HOUSE_NUMBER); voter_mobile[c]=fetchVoter.getString(KEY_SEARCH_MOBILE); voter_gender[c]=fetchVoter.getString(KEY_SEARCH_GENDER); voter_age[c]=fetchVoter.getString(KEY_SEARCH_AGE); get_voter_dob[c]=fetchVoter.getString(KEY_SEARCH_DOB); get_marriage_anniv[c]=fetchVoter.getString(KEY_MARRIEGE_ANNIV); get_voter_caste_id[c]=fetchVoter.getString(KEY_GET_CASTE_ID); get_voter_status_id[c]=fetchVoter.getString(KEY_GET_STATUS_ID); get_voter_social_status_id[c]=fetchVoter.getString(KEY_GET_SOCIAL_STATUS); } CustomSearchList adapter=new CustomSearchList(this,ParseJsonData.voter_id,ParseJsonData.boothname_id,ParseJsonData.voter_name,ParseJsonData.voter_f_m_h_name,ParseJsonData.voter_epic,ParseJsonData.voter_h_no,ParseJsonData.voter_mobile,ParseJsonData.voter_age,ParseJsonData.voter_gender,ParseJsonData.get_marriage_anniv,ParseJsonData.get_voter_dob,ParseJsonData.get_voter_caste_id,ParseJsonData.get_voter_status_id,ParseJsonData.get_voter_social_status_id); searchlist.setAdapter(adapter); adapter.notifyDataSetChanged(); } else if (sortType.equals("2")) { Collections.sort(jsonObjects, new Comparator&lt;JSONObject&gt;() { @Override public int compare(JSONObject a, JSONObject b) { String val1=new String(); String val2=new String(); try { val1=(String) a.get("FName"); // Log.e("Value1",""+val1); val2=(String) b.get("FName"); // Log.e("Value2",""+val2); } catch (JSONException e) { e.printStackTrace(); } return val1.compareTo(val2); } }); for (int j=0;j&lt;jsonObjects.size();j++) { jsonArray.put(jsonObjects.get(j)); } voter_id=new String[jsonArray.length()]; boothname_id=new String[jsonArray.length()]; voter_name=new String[jsonArray.length()]; voter_f_m_h_name=new String[jsonArray.length()]; voter_epic=new String[jsonArray.length()]; voter_h_no=new String[jsonArray.length()]; voter_mobile=new String[jsonArray.length()]; voter_gender=new String[jsonArray.length()]; voter_age=new String[jsonArray.length()]; get_voter_dob=new String[jsonArray.length()]; get_marriage_anniv=new String[jsonArray.length()]; get_voter_caste_id=new String[jsonArray.length()]; get_voter_status_id=new String[jsonArray.length()]; get_voter_social_status_id=new String[jsonArray.length()]; for (int c=0;c&lt;jsonArray.length();c++) { JSONObject fetchVoter = jsonArray.getJSONObject(c); voter_id[c] = fetchVoter.getString(KEY_VOTER_ID); boothname_id[c] = fetchVoter.getString(KEY_BOOTHNAME_ID); voter_name[c] = fetchVoter.getString(KEY_SEARCH_NAME); voter_f_m_h_name[c] = fetchVoter.getString(KEY_SEARCH_F_H_M_NAME); voter_epic[c] = fetchVoter.getString(KEY_SEARCH_EPIC_NAME); voter_h_no[c] = fetchVoter.getString(KEY_SEARCH_HOUSE_NUMBER); voter_mobile[c]=fetchVoter.getString(KEY_SEARCH_MOBILE); voter_gender[c]=fetchVoter.getString(KEY_SEARCH_GENDER); voter_age[c]=fetchVoter.getString(KEY_SEARCH_AGE); get_voter_dob[c]=fetchVoter.getString(KEY_SEARCH_DOB); get_marriage_anniv[c]=fetchVoter.getString(KEY_MARRIEGE_ANNIV); get_voter_caste_id[c]=fetchVoter.getString(KEY_GET_CASTE_ID); get_voter_status_id[c]=fetchVoter.getString(KEY_GET_STATUS_ID); get_voter_social_status_id[c]=fetchVoter.getString(KEY_GET_SOCIAL_STATUS); } CustomSearchList adapter=new CustomSearchList(this,ParseJsonData.voter_id,ParseJsonData.boothname_id,ParseJsonData.voter_name,ParseJsonData.voter_f_m_h_name,ParseJsonData.voter_epic,ParseJsonData.voter_h_no,ParseJsonData.voter_mobile,ParseJsonData.voter_age,ParseJsonData.voter_gender,ParseJsonData.get_marriage_anniv,ParseJsonData.get_voter_dob,ParseJsonData.get_voter_caste_id,ParseJsonData.get_voter_status_id,ParseJsonData.get_voter_social_status_id); searchlist.setAdapter(adapter); adapter.notifyDataSetChanged(); } else if (sortType.equals("3")) { Collections.sort(jsonObjects, new Comparator&lt;JSONObject&gt;() { @Override public int compare(JSONObject a, JSONObject b) { String val1=new String(); String val2=new String(); try { val1=(String) a.get("EPIC"); // Log.e("Value1",""+val1); val2=(String) b.get("EPIC"); // Log.e("Value2",""+val2); } catch (JSONException e) { e.printStackTrace(); } return val1.compareTo(val2); } }); for (int j=0;j&lt;jsonObjects.size();j++) { jsonArray.put(jsonObjects.get(j)); } voter_id=new String[jsonArray.length()]; boothname_id=new String[jsonArray.length()]; voter_name=new String[jsonArray.length()]; voter_f_m_h_name=new String[jsonArray.length()]; voter_epic=new String[jsonArray.length()]; voter_h_no=new String[jsonArray.length()]; voter_mobile=new String[jsonArray.length()]; voter_gender=new String[jsonArray.length()]; voter_age=new String[jsonArray.length()]; get_voter_dob=new String[jsonArray.length()]; get_marriage_anniv=new String[jsonArray.length()]; get_voter_caste_id=new String[jsonArray.length()]; get_voter_status_id=new String[jsonArray.length()]; get_voter_social_status_id=new String[jsonArray.length()]; for (int c=0;c&lt;jsonArray.length();c++) { JSONObject fetchVoter = jsonArray.getJSONObject(c); voter_id[c] = fetchVoter.getString(KEY_VOTER_ID); boothname_id[c] = fetchVoter.getString(KEY_BOOTHNAME_ID); voter_name[c] = fetchVoter.getString(KEY_SEARCH_NAME); voter_f_m_h_name[c] = fetchVoter.getString(KEY_SEARCH_F_H_M_NAME); voter_epic[c] = fetchVoter.getString(KEY_SEARCH_EPIC_NAME); voter_h_no[c] = fetchVoter.getString(KEY_SEARCH_HOUSE_NUMBER); voter_mobile[c]=fetchVoter.getString(KEY_SEARCH_MOBILE); voter_gender[c]=fetchVoter.getString(KEY_SEARCH_GENDER); voter_age[c]=fetchVoter.getString(KEY_SEARCH_AGE); get_voter_dob[c]=fetchVoter.getString(KEY_SEARCH_DOB); get_marriage_anniv[c]=fetchVoter.getString(KEY_MARRIEGE_ANNIV); get_voter_caste_id[c]=fetchVoter.getString(KEY_GET_CASTE_ID); get_voter_status_id[c]=fetchVoter.getString(KEY_GET_STATUS_ID); get_voter_social_status_id[c]=fetchVoter.getString(KEY_GET_SOCIAL_STATUS); } CustomSearchList adapter=new CustomSearchList(this,ParseJsonData.voter_id,ParseJsonData.boothname_id,ParseJsonData.voter_name,ParseJsonData.voter_f_m_h_name,ParseJsonData.voter_epic,ParseJsonData.voter_h_no,ParseJsonData.voter_mobile,ParseJsonData.voter_age,ParseJsonData.voter_gender,ParseJsonData.get_marriage_anniv,ParseJsonData.get_voter_dob,ParseJsonData.get_voter_caste_id,ParseJsonData.get_voter_status_id,ParseJsonData.get_voter_social_status_id); searchlist.setAdapter(adapter); adapter.notifyDataSetChanged(); } else if (sortType.equals(4)) { Collections.sort(jsonObjects, new Comparator&lt;JSONObject&gt;() { @Override public int compare(JSONObject a, JSONObject b) { String val1=new String(); String val2=new String(); try { val1=(String) a.get("HouseNo"); // Log.e("Value1",""+val1); val2=(String) b.get("HouseNo"); // Log.e("Value2",""+val2); } catch (JSONException e) { e.printStackTrace(); } return val1.compareTo(val2); } }); for (int j=0;j&lt;jsonObjects.size();j++) { jsonArray.put(jsonObjects.get(j)); } voter_id=new String[jsonArray.length()]; boothname_id=new String[jsonArray.length()]; voter_name=new String[jsonArray.length()]; voter_f_m_h_name=new String[jsonArray.length()]; voter_epic=new String[jsonArray.length()]; voter_h_no=new String[jsonArray.length()]; voter_mobile=new String[jsonArray.length()]; voter_gender=new String[jsonArray.length()]; voter_age=new String[jsonArray.length()]; get_voter_dob=new String[jsonArray.length()]; get_marriage_anniv=new String[jsonArray.length()]; get_voter_caste_id=new String[jsonArray.length()]; get_voter_status_id=new String[jsonArray.length()]; get_voter_social_status_id=new String[jsonArray.length()]; for (int c=0;c&lt;jsonArray.length();c++) { JSONObject fetchVoter = jsonArray.getJSONObject(c); voter_id[c] = fetchVoter.getString(KEY_VOTER_ID); boothname_id[c] = fetchVoter.getString(KEY_BOOTHNAME_ID); voter_name[c] = fetchVoter.getString(KEY_SEARCH_NAME); voter_f_m_h_name[c] = fetchVoter.getString(KEY_SEARCH_F_H_M_NAME); voter_epic[c] = fetchVoter.getString(KEY_SEARCH_EPIC_NAME); voter_h_no[c] = fetchVoter.getString(KEY_SEARCH_HOUSE_NUMBER); voter_mobile[c]=fetchVoter.getString(KEY_SEARCH_MOBILE); voter_gender[c]=fetchVoter.getString(KEY_SEARCH_GENDER); voter_age[c]=fetchVoter.getString(KEY_SEARCH_AGE); get_voter_dob[c]=fetchVoter.getString(KEY_SEARCH_DOB); get_marriage_anniv[c]=fetchVoter.getString(KEY_MARRIEGE_ANNIV); get_voter_caste_id[c]=fetchVoter.getString(KEY_GET_CASTE_ID); get_voter_status_id[c]=fetchVoter.getString(KEY_GET_STATUS_ID); get_voter_social_status_id[c]=fetchVoter.getString(KEY_GET_SOCIAL_STATUS); } CustomSearchList adapter=new CustomSearchList(this,ParseJsonData.voter_id,ParseJsonData.boothname_id,ParseJsonData.voter_name,ParseJsonData.voter_f_m_h_name,ParseJsonData.voter_epic,ParseJsonData.voter_h_no,ParseJsonData.voter_mobile,ParseJsonData.voter_age,ParseJsonData.voter_gender,ParseJsonData.get_marriage_anniv,ParseJsonData.get_voter_dob,ParseJsonData.get_voter_caste_id,ParseJsonData.get_voter_status_id,ParseJsonData.get_voter_social_status_id); searchlist.setAdapter(adapter); adapter.notifyDataSetChanged(); } // Log.e("Length Array",""+jsonArray.length()); // Log.e("Length List",""+jsonObjects.size()); } catch (JSONException e) { e.printStackTrace(); } } </code></pre> <p>I use `adapter.notifyDataSetChanged(); but my custom list not affect the sort. Please suggest me what to do.</p>
<p>Before set the data to Listview, you should sort the data using comparator class in java.</p> <p>you create one Model class with all variable what you want (name,booth_id etc)and store the each object into the ArrayList.</p> <pre><code>Collections.sort(ArrayListObject,new NameComparator()); </code></pre> <p>example</p> <pre><code>class NameComparator implements Comparator{ public int compare(Object o1,Object o2){ YourClassName s1=(YourClassName )o1; YourClassName s2=(YourClassName )o2; return s1.name.compareTo(s2.name); } } </code></pre>
How come java.lang.String does not validate encoding? <p>I ran in to something that surprised me a little. When trying to build a string from bytes that are not proper utf-8, the String constructor still gives me a result. No exception is thrown. Example:</p> <pre><code>byte[] x = { (byte) 0xf0, (byte) 0xab }; new String(x, "UTF-8"); // This works, or at least gives a result // This however, throws java.nio.charset.MalformedInputException: Input length = 3 ByteBuffer wrapped = ByteBuffer.wrap(x); CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder(); decoder.decode(wrapped); </code></pre> <p>Trying the same thing in for example python also gives an error, with a somewhat clearer error message:</p> <pre><code> &gt;&gt;&gt; '\xf0\xab'.decode('utf-8') Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: unexpected end of data </code></pre> <p>So why is it that the java string constructor seems to ignore errors in the input?</p> <p>update: I should be a little more clear. The javadoc points out that this is unspecified. But what could the reason be for implementing it like this? It seems to me you would never want this sort of behavior and any time you can't be 100% sure of the source you would need to use the CharsetDecoder to be safe.</p>
<p>The Java documentation for <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#String-byte:A-java.lang.String-" rel="nofollow">String(byte[], String)</a> says:</p> <blockquote> <p><strong>The behavior</strong> of this constructor when the given bytes are not valid in the given charset <strong>is unspecified</strong>. The CharsetDecoder class should be used when more control over the decoding process is required.</p> </blockquote> <p>Thee constructor <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#String-byte:A-java.nio.charset.Charset-" rel="nofollow">String(byte[], Charset)</a> has yet another behavior:</p> <blockquote> <p>This method always <strong>replaces malformed-input and unmappable-character sequences with this charset's default replacement string</strong>. The CharsetDecoder class should be used when more control over the decoding process is required.</p> </blockquote> <p>I like Phython's behavior better. But you can't expect Java to be exactly like Python.</p>
Email is not coming in Gmail inbox using this php code <p>I am using this code for my contact form in a html website but mail is not coming in Gmail Inbox.</p> <p>Can any one help me i am trying to solve this issue but i don't have any guide.</p> <pre><code>&lt;?php session_cache_limiter( 'nocache' ); $subject = $_REQUEST['subject']; // Subject of your email $to = "iamuser@gmail.com"; //Recipient's E-mail $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= "From: " . $_REQUEST['name'].'&lt;'.$_REQUEST['email'] .'&gt;'. "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $message = 'Name: ' . $_REQUEST['name'] . "&lt;br&gt;"; $message .= 'Company: ' . $_REQUEST['company'] . "&lt;br&gt;"; $message .= $_REQUEST['message']; if (@mail($to, $subject, $message, $headers)) { // Transfer the value 'sent' to ajax function for showing success message. echo 'sent'; // header('Location: ../index.html'); } else { // Transfer the value 'failed' to ajax function for showing error message. echo 'failed'; } ?&gt; </code></pre>
<p>There are some problem in setting the header. And most important is that you need to define the correct and valid Email Id in the <code>From</code> section because google generally used to validate the domain, the mail coming from. </p> <p>If it is not white-listed at google end then it wills end the mail to Spam automatically, that is happening now as I think.</p> <p>The problem is simple that the PHP-Mail function is not using a well configured SMTP Server. Nowadays Email-Clients and Servers perform massive checks on the emails sending server, like Reverse-DNS-Lookups, Graylisting and whatevs. All this tests will fail with the php mail() function. If you are using a dynamic ip, its even worse.Use the PHPMailer-Class and configure it to use smtp-auth along with a well configured, dedicated SMTP Server (either a local one, or a remote one) and your problems are </p> <p>You can try the below code.</p> <pre><code>$headers = "From: myplace@example.com\r\n"; $headers .= "Reply-To: myplace2@example.com\r\n"; $headers .= "Return-Path: myplace@example.com\r\n"; $headers .= "CC: sombodyelse@example.com\r\n"; $headers .= "BCC: hidden@example.com\r\n"; </code></pre> <p>Reference Link. <a href="https://github.com/PHPMailer/PHPMailerPHPMailer/PHPMailerPHPMailer" rel="nofollow">https://github.com/PHPMailer/PHPMailerPHPMailer/PHPMailerPHPMailer</a></p> <p>There is another code you can try:</p> <pre><code>function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) { $file = $path.$filename; $file_size = filesize($file); $handle = fopen($file, "r"); $content = fread($handle, $file_size); fclose($handle); $content = chunk_split(base64_encode($content)); $uid = md5(uniqid(time())); $header = "From: ".$from_name." &lt;".$from_mail."&gt;\r\n"; $header .= "Reply-To: ".$replyto."\r\n"; $header .= "MIME-Version: 1.0\r\n"; $header .= "Content-Type: multipart/mixed;boundary=\"".$uid."\"\r\n\r\n"; $header .= "This is a multi-part message in MIME format.\r\n"; $header .= "--".$uid."\r\n"; $header .= "Content-type:text/plain;charset=iso-8859-1\r\n"; $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n"; $header .= $message."\r\n\r\n"; $header .= "--".$uid."\r\n"; $header .= "Content-Type: application/octet-stream;name=\"".$filename."\"\r\n"; // use different content types here$header .= "Content-Transfer-Encoding: base64\r\n"; $header .= "Content-Disposition: attachment;filename=\"".$filename."\"\r\n\r\n"; $header .= $content."\r\n\r\n"; $header .= "--".$uid."--"; if (mail($mailto, $subject, "", $header)) {echo "mail send ... OK"; // or use booleans here} else {echo "mail send ... ERROR!"; } } </code></pre>
Editable dropdown in TinyMCE <p>There is a requirement, where it is asked to make the dropdown box editable in TinyMCE........</p> <p><a href="http://i.stack.imgur.com/GxXA2.png" rel="nofollow"><img src="http://i.stack.imgur.com/GxXA2.png" alt="enter image description here"></a></p> <p>Can it be converted in editable select box such as in libre and MS office product</p> <p><a href="http://i.stack.imgur.com/Hd8oR.png" rel="nofollow"><img src="http://i.stack.imgur.com/Hd8oR.png" alt="enter image description here"></a></p>
<p>Hopfully, i am able to achieve the result by using <code>combobox</code> as the type in my custom button.</p> <pre><code>setup: function (editor) { editor.addButton('mybutton', function() { var items= ["8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"] return { type: 'combobox', autofocus: true, label: 'FontSizes', values: items, onChange: function(e){ console.log(this.value()); } } } </code></pre>
How to use DATEADD(SQL) in DataView Rowfilter? (C#) <p>I`m making program to display information using DataGridView and ComboBox Selection.</p> <p>In SQL, query is </p> <pre><code>SELECT ListID, ListTitle, ListLastModifyDate WHERE ListLastModifyDate &lt;= DATEADD(MM, -1, GETDATE()) </code></pre> <p>I already built a code.</p> <ul> <li><p>Write a text in Text Box, then Click Start Button.</p></li> <li><p>Matched data showed in DataGridView</p></li> </ul> <p>And now I want to add this..</p> <ul> <li>If I choose item in Combobox, selected item`s result showed in DatagridView</li> <li>I want to show data without change datasource</li> </ul> <p>So I tried to use DataView`s RowFilter.. but some error found.</p> <p>Code is below</p> <pre><code>private void mtcbSiteColSearchCondition_SelectedIndexChanged(object sender, EventArgs e) { DataView dvSiteCol = new DataView(dtSiteCol); if (mtcbSiteColSearchCondition.SelectedItem.ToString() == "all") { mgrdSiteCollections.DataSource = dtSiteCol; } else { DateTime lastModifiedDate = DateTime.Now.AddMonths(-1); dvSiteCol.RowFilter = string.Format("SiteColLastModifyDate &lt;= {0}",lastModifiedDate.ToString("yyyy/MM/dd"), mtcbSiteColSearchCondition.SelectedItem.ToString()); mgrdSiteCollections.DataSource = dvSiteCol; } } </code></pre> <p>I`m not sure what is right...</p> <p>Please somebody help me how can I change that query...</p> <p>Thanks</p>
<p>The rules to use when applying a RowFilter are listed in the <a href="https://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.110).aspx" rel="nofollow">Expression</a> property of the DataColumn object.</p> <p>In particular when filtering on a DateTime value you should enclose your Date value inside the # symbol and express your date in the Invariant culture format</p> <p>So you should write </p> <pre><code> dvSiteCol.RowFilter = string.Format("SiteColLastModifyDate &lt;= #{0}#", lastModifiedDate.ToString("MM/dd/yyyy")); </code></pre> <p>It is no clear what do you want to do with this part of your code. It is not needed in the format expression, so you should remove this: <code>,mtcbSiteColSearchCondition.SelectedItem.ToString());</code></p>
Can clusterize.js be used with datatables.net? <p>I load a large amount of data into my tables.<br>I am using <a href="https://datatables.net/" rel="nofollow">datatables</a> to help with search, sorting, pagination, etc. With the large amount of data (and styled rows), it can often take a long time to render in the browser.<br><br>Is it possible to use Clusterize.js with datatables.net to improve rendering speeds?</p>
<p>Nope, long story short - it's not worth the effort</p> <p>Since you need such rich functionality as DataTable provides and infinity-scrolling feature Clusterize provides, consider switching to library that has both of these, such as SlickGrid. Despite tha fact that <a href="https://github.com/mleibman/SlickGrid" rel="nofollow">main repo is abandoned</a>, there are <a href="https://github.com/6pac/SlickGrid" rel="nofollow">actively maintaining fork</a>. See <a href="https://github.com/6pac/SlickGrid/wiki/Examples" rel="nofollow">examples</a> I am pretty sure you'll find there what you are looking for.</p> <p>I know it's not the answer you are waiting for because I know the pain of switching an existing implementation which works, but I don't think anyone will take over the responsibility of combining those two libraries in nearest future.</p>
File uploading issue in cakephp <p>I am new to Cakephp. I am using cakephp2.8.5 version. I am trying to upload a file from a HTML code but its not uploading any file and form is submitting.</p> <pre><code>View page add.ctp: &lt;form name="add_userform" class="form-horizontal" role="form" accept-charset="utf-8" enctype="multipart/form-data" method="post" id="UserAddForm" action="/invl_exams/users/add"&gt; &lt;div class="form-group" id="ShowDoc"&gt; &lt;label for="usersFile"&gt;File&lt;/label&gt; &lt;input type="file" name="data[User][doc_file]" id="usersFile"/&gt; &lt;/div&gt; &lt;/form&gt; Controller Page is UsersController.php: public function add() { if($this-&gt;request-&gt;is('post')) { $this-&gt;User-&gt;create(); $this-&gt;request-&gt;data['User']['password'] = AuthComponent::password($this-&gt;request-&gt;data['User']['password']); $filename = "app/webroot/files/".$this-&gt;data['User']['doc_file']['name']; if (move_uploaded_file($this-&gt;data['User']['doc_file']['tmp_name'],$filename)) { if($this-&gt;User-&gt;save($this-&gt;request-&gt;data)) { $this-&gt;redirect('addExam'); } } } } </code></pre>
<p>You can this plugin to upload image in Cakephp 2.x. It will handle validation errors like file type, file size etc.</p> <p>Plugin Link - <a href="https://github.com/josegonzalez/cakephp-upload/tree/2.x" rel="nofollow">https://github.com/josegonzalez/cakephp-upload/tree/2.x</a></p>
Cordova : how to deploy windows 10 apps <p>I built a <code>cordova windows 10 app</code>. The build works fine and I am able to launch my app on the simulator via <code>Visual Studio 2015</code>.</p> <p>How can i deploy this app for an entreprise? Basically I want to build an <code>appx</code> but I really don't know where to start? And what are the different stages?</p> <p>I developped and distributed many <code>cordova apps</code> on <code>iOS</code> and <code>Android</code> but the <code>windows</code> universe seems quiet dark...</p>
<p>I have recently entered the dark world of deploying Cordova-based Window 10 apps for enterprise purposes.</p> <p>Firstly, it makes a big difference if you are going to deploy via Windows Store or not. My answer below assumes you are going to use the standard public-facing Windows Store, but you can also go down the <a href="https://technet.microsoft.com/en-gb/itpro/windows/manage/distribute-apps-from-your-private-store" rel="nofollow">private store via Windows Store For Business</a> route to distribute enterpise apps, however I have no experience of this.</p> <p>Unlike the Google Play Store for Android or App Store for iOS, Windows Store enables you to <a href="https://msdn.microsoft.com/en-gb/windows/uwp/publish/set-app-pricing-and-availability#distribution-and-visibility" rel="nofollow">deploy apps without publicly listing them</a>. You can restrict access to Windows 10 apps to anyone in possession of the direct link or restrict access to a constrained list of people. The first option was good enough for me.</p> <p>In order to upload the apps to the Windows Store, you need to generate a <code>.appxupload</code> bundle. </p> <p>To do so with Cordova CLI I used <code>cordova build windows --release -- --archs="x86 x64 arm" --bundle --win</code>. You can also do this by opening the <code>platforms/windows/CordovaApp.sln</code> in Visual Studio and selecting "Project > Store > Create App Packages...". </p> <p>Both of the above assume your app is already configured with the correct package name and certificate for the corresponding app profile. You can create a new app profile in the Windows Store developer portal: <a href="https://developer.microsoft.com/en-us/dashboard/overview" rel="nofollow">https://developer.microsoft.com/en-us/dashboard/overview</a>. The easiest way to associate a profile with the your Cordova project is via Visual Studio: "Project > Store > Associate App with the Store...". </p> <p>You can then upload your <code>.appxupload</code> via the Windows Store developer portal when prompted to do so during the submission process.</p> <p>For testing purposes, I used the <a href="https://technet.microsoft.com/itpro/windows/deploy/sideload-apps-in-windows-10" rel="nofollow">Sideloading mechanism</a>, however this requires the device to be set in Sideloading or Developer mode, so is not suitable for enterprise deployment.</p>
PostgreSQL - Duplicate table in parts, empty other fields, rename table <p>I'm very new to PostgreSQL or SQL in general, so I don't know whether my question might be simple and stupid – sorry in advance.</p> <p>My situation is the following:</p> <ul> <li>I've got a table with 57 columns and 219 entries </li> <li>I need the table every year</li> <li>data of some columns should be transferred to the duplicated table (e.g. the first four columns)</li> <li>the other columns should be emptied</li> <li>the table got a trigger which should be also tranferred to the new table</li> <li>the name of the table is like "xxx_2017" and the name of the new table should be "xxx_2018"</li> </ul> <p><em>Note: the whole procedure will be binded to a button on a php-website in the end</em></p> <p>I think the first steps should be pure SQL with some special adjusted SELECT (<code>CREATE TABLE xx AS SELECT … FROM yy</code>), but the renaming seems to be more complicated because I need to save the last four digits of the name of my 'old' table into a variable as an <code>INT</code> or similar and need to count it up before I can give the variable to the name of my 'new' table.</p> <p>I know that I'm asking a question without having much groundwork and I don't expect a complete and working solution – of course you're free to post one anyway, if you want. But what I need is some advice an help to get this working.</p> <p>Thanks!</p> <hr> <p><strong>EDIT 1</strong><br> What I know is that I could ducplicate the table with all data (<code>SELECT *</code>) and delete data afterwards like <code>UPDATE table_name SET column1 = NULL, column2 = NULL, column3 = NULL</code>. But I would need to update 53 columns because I only need the data of 4 columns.</p>
<p>Alternative solution to the <code>create table xxx_2018 as select * from xxx_2017;' is to use</code>create table ... like ...` construct (it creates table only, also gives option for copying constraints etc; does not copies data):</p> <pre><code>create table xxx_2018 like xxx_2017 including all; insert into xxx_2018(&lt;&lt;4 columns you would like to fill&gt;&gt;) select &lt;&lt;4 columns you would like to fill&gt;&gt; from xxx_2017; create trigger xxx_2018_trigger ... on xxx_2018 execute procedure trigger_procedure(); </code></pre> <p>Reference: <a href="https://www.postgresql.org/docs/9.1/static/sql-createtable.html" rel="nofollow">https://www.postgresql.org/docs/9.1/static/sql-createtable.html</a> ("LIKE" paragraph)</p>
Error: method verifyCredentials in interface AccountService cannot be applied to given types <p>I am using the following code in my Twitter Integration App.</p> <pre><code>Twitter.getApiClient(session).getAccountService() .verifyCredentials(true, false, new Callback&lt;User&gt;() { @Override public void failure(TwitterException e) { //If any error occurs handle it here } @Override public void success(Result&lt;User&gt; userResult) { // get the user details } }); </code></pre> <p>It is throwing following error. </p> <pre><code>error: method verifyCredentials in interface AccountService cannot be applied to given types; required: Boolean,Boolean found: boolean,boolean,&lt;anonymous Callback&gt; reason: actual and formal argument lists differ in length </code></pre> <p>Can somebody please help me in resolving this error ?</p>
<p>Although the documentation still specifies two version for the method VerifyCredentials(), one that takes callback as an argument and one that doesn't, still I have faced the same issues.</p> <p>I tried to open the source code in Android Studio but it had only the version without the callback. </p> <p>Here is how I solved the issue.</p> <pre><code> //Getting the account service of the user logged in Call&lt;User&gt; call = Twitter.getApiClient(session).getAccountService() .verifyCredentials(true, false); call.enqueue(new Callback&lt;User&gt;() { @Override public void failure(TwitterException e) { //If any error occurs handle it here } @Override public void success(Result&lt;User&gt; userResult) { //If it succeeds creating a User object from userResult.data User user = userResult.data; setProfilePic(user.profileImageUrl.replace("_normal", "")); twitterLoginButton.setVisibility(View.GONE); } }); </code></pre> <p>Here is the link to Documentation : <a href="https://docs.fabric.io/javadocs/twitter-core/1.4.0/com/twitter/sdk/android/core/services/AccountService.html" rel="nofollow">Fabric Documentation</a></p> <p>Source : <a href="http://www.androidtutorialpoint.com/material-design/twitter-login-android-tutorial-using-fabric-twitter-login-kit/" rel="nofollow">Twitter Login Android</a></p>
Using multiple sql commands in a single method C# <p>Scope :School Project using: VS-2010, service based database Experience Level: Beginner-2 months of basic coding only</p> <p>General info: {Inventory,sales, purchases recording} windows (form) application System with service based database.</p> <p>Problem: "In the Customer Order Info form' under method to "add order" i want to:</p> <ol> <li>assign form input into variables</li> <li>use the first reader to read product quantity, etc from the 'Inventory details table' </li> <li>store data in variables</li> <li>calculate new stock quantity and other need info</li> <li>Sql to INSERT form inputs into 'order details table'</li> <li><p>Sql to UPDATE new quantity into the 'Inventory details table'</p> <pre><code> private void btnAdd_Click(object sender, EventArgs e) { try {// //1. declare variables int OrderID; string CusName; string GoodsIssued = ""; // for data entry into table string Entry1 = ""; string Entry2 = ""; string Entry3 = ""; // for calulation of new stock level int ProductIDA = 0; int QuantityOut = 0; int OldQty = 0; int NewQty = 0; int ReorderLvl = 0; string ReorderState = ""; //Boolean error = false; //2. get values from textboxes to variable OrderID = int.Parse(txtOrderID.Text); CusName = txtCustomerName.Text; if (rbYes.Checked == true) { GoodsIssued = "Yes"; } else if (rbNo.Checked == true) { GoodsIssued = "No"; } else { GoodsIssued = ""; } // further Error reporting possible /*due to complication we are compartmentalizing each iteam invoice*/ Entry1 = txtOQty.Text + "-" + txtItemID.Text; Entry2 = txtOQty2.Text + "-" + txtItemID2.Text; Entry3 = txtOQty3.Text + "-" + txtItemID3.Text; //Sql instert data needs finish here //SQL sql Search data needs follow ProductIDA = int.Parse(txtItemID.Text); // // // string search = "SELECT * FROM tblInventoryDetails WHERE [Product ID] = " + ProductIDA + ""; SqlCommand recall = new SqlCommand(search, con); con.Open(); SqlDataReader reader = recall.ExecuteReader(); while (reader.Read())// Readers need to be read using a loop!! { //string searchedId = reader[0].ToString(); //ID at loction 0 is ommited =can be included OldQty = Convert.ToInt32(reader[5]); ReorderLvl = Convert.ToInt32(reader[6]); ReorderState = reader[7].ToString(); } //////////////////////////////// NewQty = OldQty - QuantityOut; if (NewQty &gt;= ReorderLvl) //verify syntax { ReorderState = "No"; } else { ReorderState = "Yes"; } con.Close(); //3. create the query for entering new values into Order details table string insert = "INSERT INTO tblCustomerOrderDetails VALUES (" + OrderID + ", '" + CusName + "', '" + GoodsIssued + "', '" + Entry1 + "', '" + Entry2 + "', '" + Entry3 + "' )"; string update = "UPDATE tblInventoryDetails SET Quantity= " + NewQty + ", [Re-Order Recommendation]='" + ReorderState + "' WHERE [Product ID] =" + ProductIDA; //4. Creating the sql command with query name and connection SqlCommand cmdInsert = new SqlCommand(insert, con); SqlCommand cmdUpdate = new SqlCommand(update, con); //5. Opening connection path con.Open(); //6. Executing the command cmdInsert.ExecuteNonQuery(); cmdUpdate.ExecuteNonQuery(); //7.Display message if these try is sucessful MessageBox.Show("Updated and Saved Sucessfully"); }// close of try catch (Exception ex) { //8. display error message when its not sucessful MessageBox.Show("Error while saving" + ex); }// close of catch finally { //9.Close the connection con.Close(); }// close of finally // } </code></pre></li> </ol> <p>This is the order details form: <a href="http://i.stack.imgur.com/8Rka5.png" rel="nofollow">OrderDetails</a></p> <p>Updated Question: The Update part of the query where I want the new values of Quantity and re-order recommendation to be updated in the InventoryDetails table does not seem to pass when run. Everything else seems to work fine. Can any one point out my mistake or tell me why the Update function seems to not run?</p> <p>Observation: is it because this is the second [ExecuteNonQuery()] for this connection?</p> <p>Thanks in advance</p>
<p>In your Insert-Statement, there are no quotation marks for Entry3.</p>
Determine how many days a certificate is still valid from within bash script <p>I want to check how many days the certificate of a website is valid from within a bash script which runs on a standard Ubuntu 14.04 server. openssl is available.</p> <p>I already figured out that I can use openssl to get the target date</p> <pre><code>$ echo | openssl s_client -connect google.com:443 2&gt;/dev/null|openssl x509 -noout -enddate notAfter=Dec 22 16:37:00 2016 GMT </code></pre> <p>But how do I parse the resulting date and subtract the current one? Or might there be a better solution?</p>
<p>With GNU <code>date</code>'s <code>%j</code> to get day of the year and arithmetic expansion for subtraction:</p> <pre><code>$ echo $(( $(date -d "$(cut -d= -f2 &lt;(echo 'notAfter=Dec 22 16:37:00 2016 GMT'))" '+%j') - $(date '+%j'))) 73 </code></pre> <ul> <li><p><code>$(date -d "$(cut -d= -f2 &lt;(echo 'notAfter=Dec 22 16:37:00 2016 GMT'))" '+%j')</code> gets us the day of the year from the date we have got, replace teh <code>echo</code> command inside process substitution, <code>&lt;(echo 'notAfter=Dec 22 16:37:00 2016 GMT')</code> with the <code>openssl</code> command you have used initially</p></li> <li><p><code>$(date '+%j')</code> gets us today's date as day of the year</p></li> <li><p><code>$(())</code> is used for subtracting the integers</p></li> </ul>
Can PHP command a third party CLI? <p>I want to extend the automation of the PacketETH program CLI using PHP It can be done in GUI however this still means a user has to do it</p> <p>Is it possible to have the packetETH run and a PHP deliver instructions, and then receive results back for manipulation? In a broader sense, is this type of connection possible at all? Thankyou </p>
<p>You can access the command line from php by using the Php System Program Execution functions. <a href="http://php.net/manual/en/book.exec.php" rel="nofollow">http://php.net/manual/en/book.exec.php</a>. You can try out the exec function. It lets you execute shell commands.</p> <p>To run the packeteth program from php you can use a command like the following:</p> <p>exec("/path/to/packeteth/packETHcli -i lo -m 1 -f packet1.pca");</p>
Dropup Bootstrap Toggle Menu when Fixed on Bottom <p>I have a bottom-fixed menu and want the toggle to dropup instead of down. I've tried all the solutions found in stackoverflow (like this one <a href="http://stackoverflow.com/questions/17581352/how-to-get-a-bootstrap-dropdown-submenu-to-dropup">How to get a Bootstrap dropdown submenu to &#39;dropup&#39;</a>), wrapping up with .dropup class, or adding it to the element and so on, but nothing worked. This is my code:</p> <p><strong>EDIT TO ADD URL:</strong> <a href="http://linaresdemora.kmturismo.com/" rel="nofollow">http://linaresdemora.kmturismo.com/</a></p> <p><strong>EDIT 2 - TO POINT OUT THE ERRORS:</strong> One was the pointed out in the other answer. In addition, I gave it <code>height: 50px;</code> via custom css class, which stopped the menu to dropup.</p> <pre><code> &lt;nav class="navbar navbar-default navbar-fixed-bottom"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="#"&gt;Linares de Mora&lt;/a&gt; &lt;/div&gt; &lt;div id="navbar" class="collapse navbar-collapse"&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li&gt;&lt;a href="#about"&gt;Que Hacer&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Alojamiento&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Historia&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Comida&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&gt;Más &lt;span class="caret"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li role="separator" class="divider"&gt;&lt;/li&gt; &lt;li class="dropdown-header"&gt;Nav header&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Separated link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;One more separated link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/nav&gt; </code></pre>
<p>Check this link <a href="https://jsfiddle.net/edz80vw5/" rel="nofollow">https://jsfiddle.net/edz80vw5/</a></p> <pre><code>&lt;nav class="navbar navbar-default navbar-fixed-bottom"&gt; &lt;div class="container"&gt; &lt;div class="navbar-header"&gt; &lt;button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"&gt; &lt;span class="sr-only"&gt;Toggle navigation&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="navbar-brand" href="#"&gt;Linares de Mora&lt;/a&gt; &lt;/div&gt; &lt;div id="navbar" class="collapse navbar-collapse"&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li&gt;&lt;a href="#about"&gt;Que Hacer&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Alojamiento&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Historia&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Comida&lt;/a&gt;&lt;/li&gt; &lt;li class="dropup"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&gt;Más &lt;span class="caret"&gt;&lt;/span&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li role="separator" class="divider"&gt;&lt;/li&gt; &lt;li class="dropdown-header"&gt;Nav header&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Separated link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;One more separated link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/nav&gt; </code></pre> <p>The difference is made by the last <strong>li</strong> element of the first <strong>ul</strong> with class <strong>dropup</strong> instead of <strong>dropdown</strong>.</p>
Change intellij JVM <p>I saw a comment about fixing an issue with the Intellij </p> <p>"The problem should not occur if you switch Java used by the IntelliJ IDEA from OpenJDK bundled with IDEA to Oracle JVM. At least this can work as a workaround."</p> <p>How can I change the JVM in Intellij ? </p>
<p>Set an environment variable to tell IntelliJ what JVM to use for the IDE.</p> <p>Go into Control Panel...System...Advanced System Settings. Click the "Advanced" tab, then click the "Environment Variables" button to edit.</p> <p>Add a new user variable -</p> <p>"IDEA_JDK" for a 32-bit JVM, or "IDEA_JDK_64" for a 64-bit JVM. Set the variable to point to the directory of the JDK you want IntelliJ to use (e.g., "C:\Java\jdks\1.8x64" or similar)</p> <p>Restart IntelliJ.</p>
Merge records from two tables <p>I have two model <code>Part</code> and <code>DamagedPart</code>. All of them have <code>iid</code> field. </p> <p>I want to get combined ActiveRecord object with data from these two tables. </p> <p>Say, <code>parts</code> table has 10 records:</p> <pre><code>id: 1, iid: 100, d: 0 id: 2, iid: 150, d: 0 id: 3, iid: 200, d: 0 id: 4, iid: 240, d: 0 id: 5, iid: 433, d: 0 ... </code></pre> <p>And <code>damaged_parts</code> table has only two records (for example):</p> <pre><code>id: 10, iid: 200, d: 4 id: 20, iid: 240, d: 7 </code></pre> <p>Finally I need to get:</p> <pre><code>id: 1, iid: 100, d: 0 id: 2, iid: 150, d: 0 id: 10, iid: 200, d: 4 # &lt;--- replaced from 'damaged_parts' table id: 20, iid: 240, d: 7 # &lt;--- replaced from 'damaged_parts' table id: 5, iid: 433, d: 0 ... </code></pre> <p>Can I get this done by <strong>one</strong> AR query?</p> <p>Rails: <code>4.2.7.1</code><br> RDBMS: <code>MariaDB 10.0.27</code></p>
<p>You need <code>LEFT JOIN</code> and <code>COALESCE</code></p> <pre><code>SELECT p.id, p.iid, COALESCE(dp.d, p.d) AS d FROM parts p LEFT JOIN damaged_parts dp ON p.id = dp.id AND p.iid = dp.iid </code></pre>
Query for column value as column alias of a survey result <p>I am facing a problem in building a query of the following scenario. I am listing tables and values for an example:</p> <h2>Responses Table</h2> <pre><code>Q_ID | Response_ID | answer_col_label | answer_value 10 | 500 | Label_a | 1 11 | 501 | Label_b | 2 12 | 502 | Label_c | 3 </code></pre> <p>Then in results table, values are as under:</p> <h2>Results Table</h2> <pre><code>Q_ID | Response_ID | answers 10 | 500 | 502 </code></pre> <p>In results table, there is response_id pushed in answers column, which means that user selected this response_id from radio button/checkbox.</p> <p>Now I want to create a query where I want to show answer_col_label value (Lable_a) in column heading for including all responses of responses table and showing answer_value as selected result under that column heading.</p> <p>Please help me creating this query in SQL Server. Thank you for time and help.</p>
<p>Use PIVOT</p> <pre><code>SELECT P.* FROM ( SELECT A.Q_ID, A.Response_ID, A.answer_col_label, B.answers FROM @ResponseTable AS A INNER JOIN @ResultsTable AS B ON A.Q_ID = B.Q_ID AND A.Response_ID = B.Response_ID ) AS S PIVOT ( MAX(answers) FOR answer_col_label IN ([Label_a], [Label_b], &lt;and other labels&gt;) ) AS P </code></pre>
TypeScript build error when assigning double dimensional array in VS2015 <p>I am getting build errors in typescript project in VS2015. The application works fine in browser, but now I cannot publish due to these build errors.</p> <p><code>export var AddedFields: Array&lt;Array&lt;Field&gt;[]&gt;[];</code></p> <p><code>myGlobals.AddedFields[1][1] = new Field(newField.id, newField.label, newField.type, 0, 0);</code></p> <p>Error is</p> <p>Error TS2322 Build:<strong>Type 'Field' is not assignable to type 'Field[][]'</strong>. \Projects\angular2-systemjs-dotnet-core-master\src\TestAngular2\wwwroot\app\components\form-layout.component.ts 40 Build </p> <p>Could someone please identify what am I doing wrong?</p>
<p>Both the <code>Array</code> and <code>[]</code> notations can indeed be used to define an array type in Typescript, but by using both at the same time, you have effectively declared a 4-dimensional array.</p> <p>If you stick to one type of notation, it should be, for the <code>Array</code> notation:</p> <pre><code>export var AddedFields: Array&lt;Array&lt;Field&gt;&gt;; </code></pre> <p>or for the <code>[]</code> notation:</p> <pre><code>export var AddedFields: Field[][]; </code></pre>
how to pass variables from r program to mysql function <p>I am new to R Programming and MySQL. I have a requirement where I need to read the variables from R Programming and need to pass those as inputs to a function in MySQL. Can someone please help me in this regard?</p> <pre><code>options(echo=FALSE) args &lt;- commandArgs(trailingOnly=TRUE) start.date &lt;- as.Date(args[1]) end.date &lt;- as.Date(args[2]) library(RMySQL) mydb = dbConnect(mydb,xxxx) rs &lt;- dbSendQuery(mydb,"SELECT COMPUTE_WEEKS(start.date,end.date) FROM DUAL;") </code></pre> <p>Below is the error I am getting.</p> <p>rs &lt;- dbSendQuery(mydb, "SELECT COMPUTE_WEEKS(start.date,end.date) FROM DUAL;") Error in .local(conn, statement, ...) : could not run statement: Unknown table 'start' in field list</p> <p>Need to understand how to read data from r-program and pass it as arguments to procedures/functions in My-SQL. Currently using RMysql library.</p> <p>Regards Bhanu Pratap M </p>
<p>If you want to include the <em>R variables</em> called <code>start.date</code> and <code>end.date</code>, then you can use <code>paste</code> to build the query string:</p> <pre><code>query &lt;- paste0("SELECT COMPUTE_WEEKS(", start.date, ", ", end.date, ") FROM DUAL;") mydb &lt;- dbConnect(mydb, xxxx) rs &lt;- dbSendQuery(mydb, query) </code></pre>
How to capture event when jar's command prompt is closed using X button? <p>I have multiple jars that communicate to single app to provide their responses. I need to handle a scenario when command prompts are closed using X button at the top. All apps are written in JAVA so java code is needed.</p> <p>I have already added shutdown hooks but they are triggered only when threads are stopped in careful manner.</p> <pre><code>Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() {} }); </code></pre> <p>Also what if jars crashes how they can be captured in java?</p>
<p>It is impossible in Java. Different OS have different solution for that.</p> <p>Ask about your OS in related site.</p>
How to echo values from a PHP string into different iterations of a loop <p>I have creted a tool in WP admin that searches the custom post type ($apartments), returns a list of $apartments with their post meta, allows the user to check a checkbox next to selected posts and finally email those selected posts to the client. Its an $apartments recommendation tool. </p> <p>Currently I use some JS to get a string of post ID's along with an email address from selected apartments, then send them to a function that queries the DB and returns those posts inside a HTML template before using wp_mail() to send them out. </p> <p>I dont save these posts, everything is generated on the fly. The comment boxes (.comments) are used on the fly and I would like to also pass these to the query function however, if I add these to their own JS string as I have done the post ID's, how do I then echo these out to their appropriate items with my loop. The first and third item here have a comment, how would I add that comment to the first and third item within the loop. </p> <p>I send all this data to the PHP function via ajax so this would be posted as a JS string to a PHP function.</p> <pre><code>&lt;div class="search-reults"&gt; &lt;ul&gt; &lt;li class="item &lt;?php echo $ID; ?&gt;"&gt; &lt;p&gt;apartmentname&lt;/p&gt; &lt;textarea class="comments"&gt;some comments&lt;/texarea&gt; &lt;input type="checkbox" name="selectthis"&gt; &lt;/li&gt; &lt;li class="item &lt;?php echo $ID; ?&gt;"&gt; &lt;p&gt;apartmentname&lt;/p&gt; &lt;textarea class="comments"&gt;&lt;/texarea&gt; &lt;input type="checkbox" name="selectthis"&gt; &lt;/li&gt; &lt;li class="item &lt;?php echo $ID; ?&gt;"&gt; &lt;p&gt;apartmentname&lt;/p&gt; &lt;textarea class="comments"&gt;some comments&lt;/texarea&gt; &lt;input type="checkbox" name="selectthis"&gt; &lt;/li&gt; &lt;li class="item &lt;?php echo $ID; ?&gt;"&gt; &lt;p&gt;apartmentname&lt;/p&gt; &lt;textarea class="comments"&gt;&lt;/texarea&gt; &lt;input type="checkbox" name="selectthis"&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; jQuery('.item:has(input:checked)').each(function() { var str = jQuery(this).find('input[type=checkbox]').val(); postidstring += postidstring.length &gt; 0 ? ',' + str : str; }); </code></pre> <p>On click this send the postidstring via ajax to a wp_query() where it will return the apartments in a loop and send out the resulting HTML via wp_mail();</p>
<p>So you want to know how to automate the process ? right ?</p> <p>First, you need to store the list of apartments to an array. Assuming you know how to get the list of apartments from the DB via MySQL query, I'll skip to the next step.</p> <pre><code>&lt;?php for($i=0; $i&lt;$size_of_apartments; $i++) {?&gt; &lt;li class="item" &lt;?php echo $apartments[$i]['id']; ?&gt;&gt; &lt;p&gt;&lt;?php echo $apartments[$i]['apartment_name'];?&gt;&lt;/p&gt; &lt;textarea class="comments"&gt;&lt;?php echo $apartments[$i]['comments'];?&gt;&lt;/textarea&gt; &lt;input type="checkbox" name="selectthis"&gt; &lt;/li&gt; &lt;?php }?&gt; </code></pre> <p>Hope this helps you out ! :)</p>
How to call method and return its value with UnityPlayer.UnitySendMessage <p>How can I call this C# method from Java then return the string value?</p> <pre><code>public string getTest () { return "test"; } </code></pre> <p>This is what I've tried:</p> <pre><code>String str = UnityPlayer.UnitySendMessage("ProfileSave", "getTest",""); </code></pre> <p>I am getting the below error</p> <blockquote> <pre><code>String str=UnityPlayer.UnitySendMessage("ProfileSave", "getTest",""); ^ required: String found: void </code></pre> </blockquote>
<p><code>UnityPlayer.UnitySendMessage</code> is a <code>void</code> function and does not return a value. Take a look at the <code>UnitySendMessageExtension</code> function implementation below. It is similar to <a href="http://stackoverflow.com/a/39954620/3785314">turnipinindia's</a> answer but it returns a value. It only returns a <code>string</code> so you have to convert that string to whatever variable type you are working with.</p> <p><strong>Java</strong>:</p> <pre><code>public final class MyPlugin { //Make class static variable so that the callback function is sent to one instance of this class. public static MyPlugin testInstance; public static MyPlugin instance() { if(testInstance == null) { testInstance = new MyPlugin(); } return testInstance; } string result = ""; public string UnitySendMessageExtension(string gameObject, string functionName, string funcParam) { UnityPlayer.UnitySendMessage(gameObject, functionName, funcParam); string tempResult = result; return tempResult; } //Receives result from C# and saves it to result variable void receiveResult(string value) { result = "";//Clear old data result = value; //Get new one } } </code></pre> <p><strong>C#</strong>:</p> <pre><code>class TestScript: MonoBehaviour { //Sends the data from PlayerPrefs to the receiveResult function in Java void sendResultToJava(float value) { using(AndroidJavaClass javaPlugin = new AndroidJavaClass("com.company.product.MyPlugin")) { AndroidJavaObject pluginInstance = javaPlugin.CallStatic("instance"); pluginInstance.Call("receiveResult",value.ToString()); } } //Called from Java to get the saved PlayerPrefs void testFunction(string key) { float value = PlayerPrefs.GetFloat(key) //Get the saved value from key sendResultToJava(value); //Send the value to Java } } </code></pre> <p>Usage from Java:</p> <pre><code>String str = UnitySendMessageExtension("ProfileLoad", "testFunction","highScore"); </code></pre> <p>This will work with any <em>C#</em> function. Just make sure that you call <code>sendResultToJava</code> function at the end of the <em>C#</em> function like we did in the <code>testFunction</code> function, if you want it to return value. </p>
Return unique row identifier from an SQL query <p>I know this question may sound as a repetition. However, even though I found similar questions, I got nothing precise. I don't want to remove any duplicate values returned from my query. <strong>What I want is to get a unique identifier for example a serial number for a result that is returned from an sp</strong>. I tried using the Row_Number(). But, even that did not work since it should be partitioned based on a non repetitive column. My results need not have a non repetitive column. Rank and dense rank are also out the picture. So, what should I do to get a serial number type of column that uniquely identifies each rows. Also these rows should be int. Here is an example: </p> <pre><code> empName empSalary Peter 10000 Schott 20000 Schott 10000 </code></pre> <p>table should have one more column like this:</p> <pre><code>Slno empName empSalary 1 Peter 10000 2 Schott 20000 3 Schott 10000 </code></pre>
<p>If you don't care about the ordering:</p> <pre><code>Select ROW_NUMBER() over (order by (Select 1)) as SlNo ,* from table </code></pre> <p>OR</p> <p>Handle it in #temp table:</p> <pre><code>Select * into #TempTable from SourceTable ALTER TABLE tempdb.dbo.#TempTable ADD SlNo INT IDENTITY(1,1) ; Select * from #TempTable </code></pre>
Why does TypeScipt show me error, when I change DOM-element via getElementsByClassName(), but application works anyway? <p>I have angular2 application. Due to some problems I forced to use inside method of component such code (I understand that it's over than bad, but ...):|</p> <pre><code>let confirmWindowDOM = document.getElementsByClassName('modal')[0]; confirmWindowDOM.style['z-index'] = "2049"; </code></pre> <p>It produces the error, which I can see in console:</p> <pre><code>(program):75 ./some/path/to/component.component.ts (103,28): error TS2339: Property 'style' does not exist on type 'Element'. </code></pre> <p>But anyway application works as I expected.</p> <p>So there are some questions:</p> <ol> <li>This code is clear JS. As I understand TypeScript as superset of JavaScript must has no problem with that, however I have error and tests are failed. Even if I change code like this: document.getElementsByClassName('modal')[0].style['z-index'] = "1051";;</li> <li>How I can suppress this error or fix it ?</li> </ol>
<p><code>getElementsByClassName</code> returns collection of <code>Element</code>. You can use <a href="https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions" rel="nofollow">type assertion</a> in order to inform typescript that it is actually <code>HTMLElement</code>:</p> <pre><code>let confirmWindowDOM = document.getElementsByClassName('modal')[0] as HTMLElement; </code></pre>