input
stringlengths
51
42.3k
output
stringlengths
18
55k
Creating a dictionary in python by combining two .csv files <p>I am trying to create a dictionary in python by combining data from two .csv files, by matching the first column of the two files. This is what I have so far </p> <pre><code>import csv with open('a.csv', 'r') as my_file1 : rows1 = list(csv.reader(my_file1)) with open('aa.csv', 'r') as my_file2 : rows2 = list(csv.reader(my_file2)) max_length = min(len(rows1), len(rows2)) for i in range(10): new_dict = {} if (rows1[i][0]== rows2[i][0]): temp = {(rows1[i][0], (rows1[i][5], rows1[i][6], rows2[i][5], rows2[i][6] )) } new_dict.update(temp) print(new_dict) </code></pre> <p>The output that I get is the last data entry in arrays. It does not seem to append all the values. This is what the output looks like </p> <pre><code>{'2016-09-12': ('1835400', '45.75', '21681500', '9.78')} </code></pre> <p>instead of the complete list with keys and values. How do I go about correcting this? Thanks! </p>
<p>You're creating a new dictionary on every iteration of your <code>for</code>, so only the update from the last iteration is kept, others have been thrown away.</p> <p>You can solve this by moving the dictionary setup outside the <code>for</code>:</p> <pre><code>new_dict = {} for i in range(10): ... </code></pre>
Given known origin and destination latitude/longitude, how can I create its bounding box? <p>Origin Latitude/longitude: 39.50000000,-84.78000000</p> <p>Destination Latitude/longitude: 28.42000000,-81.31000000</p> <p>How can I draw its bounding box?</p> <p>The correct bounding box is:</p> <pre><code>+-----1 | / | | / | | / | 2-----+ </code></pre> <p>I'm intrested to find 1 and 2 points.</p> <p>I'm also attaching Image for better understanding the requirements. <a href="http://i.stack.imgur.com/Y5svh.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Y5svh.jpg" alt="enter image description here"></a> I am writing code in PHP.</p>
<p>you can use fitbounds</p> <pre><code>&lt;body&gt; ..... &lt;div id='your_map_id' style='height : 300px; width: 300px;'&gt;&lt;/div&gt; &lt;body&gt; &lt;style&gt; var mapDiv = document.getElementById('your_map_id'); var map = new google.maps.Map(mapDiv, { mapTypeId: google.maps.MapTypeId.ROADMAP }); var southWest = new google.maps.LatLng(28.42000000, -84.780000); var northEast = new google.maps.LatLng(39.50000000, -81.31000000); var bounds = new google.maps.LatLngBounds(southWest,northEast); map.fitBounds(bounds); &lt;/style&gt; </code></pre>
Swift3 Xcode8 - iOS app User profile data update and display in Profile Screen view <p>First post and coding since 2 weeks, please be indulgent. Learning in the making.</p> <p>It saves the users details correctly in Firebase under its own UID. My problem is that once the user logs out and log back in, the second party of the code under the override func viewDidLoad() is supposed to fetch the info available in the database and display them in the related text field, but it doesn't. Does anyone see anything madly wrong in the code below? Any solutions for this?</p> <p>(sorry if the code hurt your eyes, I took bits and pieces around) Cheers for the help.</p> <pre><code>import UIKit import Firebase import FirebaseAuth import FirebaseDatabase class EditProfileTableViewController: UITableViewController { var about = ["Name", "Email", "Phone", "Sex", "Profile Description", "Date of Birth"] var user = FIRAuth.auth()?.currentUser?.uid var ref = FIRDatabase.database().reference() @IBAction func backAction(_ sender: UIBarButtonItem) { self.dismiss(animated: true, completion: nil) } @IBAction func didTappedUpdateButton(_ sender: AnyObject) { var index = 0 while index&lt;about.count{ let indexPath = NSIndexPath(row: index, section: 0) let cell: TextInputTableView? = self.tableView.cellForRow(at: indexPath as IndexPath) as! TextInputTableView? if cell?.myTextField.text != ""{ let item:String = (cell?.myTextField.text!)! switch about[index]{ case "Name": self.ref.child("data/users").child("\(user!)/Name").setValue(item) case "Email": self.ref.child("data/users").child("\(user!)/Email").setValue(item) case "Phone": self.ref.child("data/users").child("\(user!)/Phone").setValue(item) case "Sex": self.ref.child("data/users").child("\(user!)/Sex").setValue(item) case "Profile Description": self.ref.child("data/users").child("\(user!)/Profile Description").setValue(item) case "Date of Birth": self.ref.child("data/users").child("\(user!)/Date of Birth").setValue(item) default: print("Don't Update") }//end switch }//end if index+=1 } } override func viewDidLoad() { super.viewDidLoad() self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) let ref = FIRDatabase.database().reference() ref.child("data/users").queryOrderedByKey().observe(FIRDataEventType.value, with: { (snapshot) in let usersDict = snapshot.value as! NSDictionary print(usersDict) let userDetails = usersDict.object(forKey: self.user!) var index = 0 while index&lt;self.about.count{ let indexPath = NSIndexPath(row: index, section:0) let cell : TextInputTableView? = self.tableView.cellForRow(at: indexPath as IndexPath) as! TextInputTableView? let field: String = (cell?.myTextField.placeholder?.lowercased() )! switch field { case "Name": cell?.configure(text: (userDetails as AnyObject).object(forKey: "Name") as? String, placeholder: "Name") case "Email": cell?.configure(text: (userDetails as AnyObject).object(forKey: "Email") as? String, placeholder: "Email") case "Phone": cell?.configure(text: (userDetails as AnyObject).object(forKey: "Phone") as? String, placeholder: "Phone") case "Sex": cell?.configure(text: (userDetails as AnyObject).object(forKey: "Sex") as? String, placeholder: "Sex") case "Profile Description": cell?.configure(text: (userDetails as AnyObject).object(forKey: "Profile Description") as? String, placeholder: "Profile Description") case "Date of Birth": cell?.configure(text: (userDetails as AnyObject).object(forKey: "Date of Birth") as? String, placeholder: "Date of Birth") default: print("") }//end switch index+=1 } }) } override func numberOfSections(in tableView: UITableView) -&gt; Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { // #warning Incomplete implementation, return the number of rows return about.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell: TextInputTableView = tableView.dequeueReusableCell(withIdentifier: "TextInput", for: indexPath) as! TextInputTableView cell.configure(text: "", placeholder: "\(about[indexPath.row])") return cell } </code></pre> <p><img src="http://i.stack.imgur.com/yYkWk.png" alt="enter image description here"></p>
<p>Sorry for the silence. I was away from my laptop. These are my suggestions.</p> <ol> <li><p>Get rid of the data node; it seems rather redundant. You can simply add other nodes under the root node i.e. <em>appname</em>.</p></li> <li><p>Refractor your <code>viewDidLoad</code>; because its rather convoluted. Put the firebase retrieval stuff in a separate method.</p></li> <li><p>Adopt a reusing habit. It makes your code less complex and easy to follow. This applies even with something as little as variables. e.g. you have <code>ref</code> declared globally; which is the way to go. But again you have another <code>ref</code> declared in your <code>viewDidLoad</code> and they both serve the same purpose. I know its a minor thing but why have multiple variables serving the same purpose?</p></li> <li><p>You are not checking your result for any errors or <code>nil</code> values. You are directly unwrapping things. It is fine to directly unwrap things but this should only be done in places which you are 100% certain that you do have a value. For most internet queries, this is not the case and you want your app to handle those scenarios as well.</p></li> </ol> <p>This is how I would have done it if I were you. I made these two global variables:</p> <pre><code>var currentUser: FIRUser = FIRUser() let databaseRef = FIRDatabase.database().reference() </code></pre> <p>Then I made this method which gets the user data just once. If you want it to get live updates, then simply change it from a <code>observeSingleEvent</code> to an <code>observe</code> instead and the type to either <code>.childAdded</code> or <code>.childChanged</code> depending on your specific scenario. I'll leave that challenge to you and everything else is the pretty much the same.</p> <pre><code>func getUserDetailsOnce() { self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0) // check first if the user is currently logged in. If yes, then save them in the variable user. Normally, you'd want to run this check inside your AppDelegate after didFinishLaunchWithOptions guard let user = FIRAuth.auth()?.currentUser else { print("No logged user in existence") return } currentUser = user // update the global variable // append to the current user's node location databaseRef.child("data/users").child(currentUser.uid).observeSingleEvent(of: .value) { (snapshot: FIRDataSnapshot) in // you have retrieved the result and store it in firebaseValue. snapshot.value returns AnyObject?. Since its an optional it can be nil and we want to handle that scenario. And its highly advisable to cast it as a [String:AnyObject] instead of an NSDictionary guard let firebaseValue = snapshot.value as [String:AnyObject] else { print("Error with FrB snapshot") // this is printed if no Firebase value is returned return } // Now that we have our value, we can access the respective elements let index = 0 while index &lt; self.about.count { let indexPath = NSIndexPath(row: index, section: 0) let cell: UITableViewCell = self.tableView.cellForRow(at: indexPath) // This is where I am a little bit puzzled as to how you have your cell structured. But if you want to access the individual elements inisde our database then you simply have to check for nils for each individual component as shown below guard let email = firebaseValue["email"] as? String, let name = firebaseValue["name"] as? String else // add the other ones respectively { print("Error extracting individual Firebase components") return } // Then you can display the values since they are now stored in the variables email,name etc index += 1 } } } </code></pre>
Rails 5: partial view with condition and locals <p>I'm a bit lost in creating "New campaign" button if user has particular role.</p> <p>In models/roles.rb I have:</p> <pre><code>class Role &lt; ApplicationRecord belongs_to :user, optional: true accepts_nested_attributes_for :user enum general: { seller: 1, buyer: 2, seller_buyer: 3}, _suffix: true enum dashboard: { denied: 0, viewer: 1, editer: 2, creater: 3, deleter: 4}, _suffix: true </code></pre> <p>In controllers/dashboards_controller.rb I have:</p> <pre><code>def dashboard_1 @roles = current_user.roles if @roles.any? { |role| role.creater_dashboard? || role.deleter_dashboard? } flash.now[:error] = "You are creater/deleter!" elsif @roles.any? { |role| role.viewer_dashboard? } flash.now[:error] = "You are viewer!" else redirect_to users_path end end </code></pre> <p>I have partial campaigns/_new.html.erb like this:</p> <pre><code>&lt;li&gt; &lt;%= link_to new_campaign_path(@campaign), {method: 'get', class: 'btn btn-w-m btn-primary'} do %&gt;New campaign &lt;% end %&gt; &lt;/li&gt; </code></pre> <p>and in dashboards/dashboard_1.html.erb I would need to <strong>render "New campaign" button if user is "creater" of "deleter" for Dashboard</strong>:</p> <pre><code>&lt;% if ... %&gt; &lt;%= render partial: "campaigns/new" %&gt; </code></pre> <p>As I have found out it can be done with locals, however I cannot figure out how? Many thanks for any help!</p> <p><strong>Added</strong></p> <p>In layouts/application.html.erb I have this:</p> <pre><code>&lt;!-- Navigation --&gt; &lt;%= render 'layouts/navigation' %&gt; </code></pre> <p>and in partial _navigation.html.erb I have this:</p> <pre><code>&lt;li class="&lt;%= is_active_controller('dashboards') %&gt;"&gt; &lt;% if @creator_deleter %&gt; &lt;%= link_to dashboard_path do %&gt; &lt;i class="fa fa-th-large"&gt;&lt;/i&gt; &lt;span class="nav-label" data-i18n="nav.dashboard"&gt;Dashboard&lt;/span&gt; &lt;% end %&gt; &lt;% end %&gt; &lt;/li&gt; ... #other links to different parts of app </code></pre> <p>How to hide "dashboard" link in partial if user is not @creator_deleter?</p>
<p>As far as I know you can't render the form with locals from the controller. Is there any reason why you would want to use a local? - these are normally used when rendering partials to pass local variables from one view to the partial, for purposes of reuse. for example...</p> <pre><code>&lt;%= render partial: 'form', locals: { my_local_var: my_local_var } %&gt; </code></pre> <p>I think what you actually want to do is set an instance variable from within the controller that is accessible during the rendering process. For example...</p> <pre><code>if @roles.any? { |role| role.creater_dashboard? || role.deleter_dashboard? } @creator_deleter = true elsif @roles.any? { |role| role.viewer_dashboard? } @viewer = true else redirect_to users_path end </code></pre> <p>and then you can test for that in your view</p> <pre><code>&lt;% if @creator_deleter %&gt; </code></pre>
Dealing with NA in numeric vector and using transform <p>I came up with a very hacky way of dealing with an issue I faced when combining two columns, but there must be a better/more efficient way to do what I did. Any suggestions for an R novice would be much appreciated. </p> <p>I have two columns, one with code and the other with locations, for various years. The data is inconsistent over years, eg data in 2004 has codes and locations separated, while 2012 has codes and locations combined in the location column, leaving the code column empty. I first want to standardize the data over years, so one column, called code_location, has the code and location combined for all observation, then create two more columns, one with code and the other with location. </p> <p>Here is the data:</p> <pre><code>df &lt;- read.table(text = c(" observation year code location 1 2004 23-940 town no. 1 2 2004 23-941 town no. 2 3 2012 NA 23-940 town no. 1 4 2012 NA 23-941 town no. 2"), header = TRUE) </code></pre> <p>I tried using <code>transform</code> and <code>paste</code> in the code below to combine the two columns, but it </p> <pre><code>df_combined &lt;- transform(df, code_location = paste(code, location, sep = " ")) </code></pre> <p>It worked in combining the code and location for 2004 observations, but it included the NAs from the code column in 2012 observations. (NB, both code and location are numeric vectors. I later use a regex where this becomes important. I tried <code>as.character</code> on code column to get rid of NA, but it then screwed up my regex later.)</p> <pre><code>observation year code_location 1 2004 23-940 town no. 1 2 2004 23-941 town no. 2 3 2012 NA 23-940 town no. 1 4 2012 NA 23-941 town no. 2 </code></pre> <p>To get around this, I created a dummy that told me which observations had NA and which didn't, and then used <code>split</code> in order to create two dataframes, do what I need to get code_location, and then combined the dataframes again. Here is my code:</p> <pre><code>df$cheat &lt;- ifelse(is.na(df$code) == T, 0, 1) ls_df &lt;- split(df, df$cheat) df_code &lt;- ls_df[[2]] df_na &lt;- ls_df[[1]] df_code &lt;- transform(df_code, code_location = paste(code, location, sep = " ")) df_combined &lt;- rbind(df_code, df_na) </code></pre> <p>And I get the following output, which is my desired output, but very roundabout. </p> <pre><code>observation year code_location 1 2004 23-940 town no. 1 2 2004 23-941 town no. 2 3 2012 23-940 town no. 1 4 2012 23-941 town no. 2 </code></pre>
<p>You can use the <code>ifelse</code> function:</p> <pre><code>transform(df, code_location = ifelse(is.na(code), as.character(location), paste(code, location))) </code></pre> <p>Note that <code>df$location</code> is a factor, so it needs to be converted to character if used by itself.</p>
Python: printing result of multiple inputs <p>I'm pretty new to python programming, but i'm trying to write a program that goes as follows:</p> <p>First: the program asks the user for a fixed number. Then: the user can input as many numbers as he wants, until he writes "stop". (this is not really where i'm having trouble)</p> <p>the output needs to be something like this: 'fixed number' 'input #1 = fixed number + first inputted number' 'input #2 = fixed number + first inputted number + second inputted number' 'an so on until all inputted numbers have been added'</p> <p>my code doesn't print this out correctly, it prints the correct #1, #2, #n but not the summation i listed above.</p> <p>Any help is appreciated</p> <p>Here is my code at this moment:</p> <pre><code>random_number = int(input("Enter random number:")) count_added = 0 while number != "stop": number = input("Enter number: ") if number == "stop": break else: number_int = int(number) count_added += 1 sum = number_int + random_number print(random_number) for x in range(1, count_added + 1): print("input #{} is sum {} ".format(x, sum)) </code></pre>
<pre><code>input_list = [] sum = 0 while True: user_input = int(input('Enter the number')) if user_input != 'stop' input_list.append(user_input) elif user_input == 'stop': break; for i in input_list: sum += i print(sum) </code></pre>
Jquery multiple file upload issue <p>I'm using Jquery File Upload plugin, to upload files, here is method which gets files from server and generates HTML and inserts in into an element: </p> <pre><code> getFilesToHolders:function (id,tablesName) { //attachecedFiles is a container for the generated html var attachedFiles = $('#IDAttachedfiles'); // clears this area in case of multiple file upload attachedFiles.html(''); attachments.getFiles(id,tablesName,function(data) { // getFiles just does an ajax request var template = '&lt;li class="list-group-item"&gt;&lt;b&gt;File:&lt;/b&gt; &lt;span class="filenameClassAtt"&gt;&lt;/span&gt; | &lt;b&gt;Extension:&lt;/b&gt; &lt;span class="label label-warning extensionAttachedFile"&gt;&lt;/span&gt; &lt;a href="" class="pull-right attachment-remove-class" style="padding-left:10px; color:#e74c3c;"&gt;&lt;i class="fa fa-remove "&gt;&lt;/i&gt;&lt;/a&gt; &lt;a class="pull-right download-attachment-class" href=""&gt;&lt;i class="fa fa-download"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;'; if (!data.length) { attachedFiles.html('&lt;h2&gt;No files&lt;/h2&gt;'); return; } $.each(data, function(index, val) { var newTemp = $(template); newTemp.find('.filenameClassAtt').html(val.url); newTemp.find('.extensionAttachedFile').html(val.extension); newTemp.find('.download-attachment-class').attr({ 'id': 'IDAttachmentDownload-'+val.id, 'data-tabel-name': val.table_name, 'data-record-id' :val.record_id });; newTemp.find('.attachment-remove-class').attr({ 'id': 'IDAttachmentDelete-'+val.id, 'data-tabel-name': val.table_name, 'data-record-id' :val.record_id }); attachedFiles.append(newTemp); }); }); }, </code></pre> <p>and this is method which executes after a file upload : </p> <pre><code>done: function (e, data) { var data = data.result; if (data.success == 1) { attachments.getFilesToHolders(data.record_id,data.table_name); swal(data.data,false,'success'); }else{ app.helper.displayErrors(data); } }, </code></pre> <p>and this method make use of the above method to load the files on the page after upload, so the <strong>problem</strong> here is when I upload multiple files done method executes multiple times and for some reason list of files generated after upload is multiplied by the amount of files I've uploaded even though <code>getFilesToHolders</code> method clears the div each time it is called <code>attachedFiles.html('');</code> so I don't know why the list is dublicated , here is sceenshot : <a href="http://i.stack.imgur.com/rHEqQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/rHEqQ.png" alt="enter image description here"></a></p> <p>here I heve uploaded only 4 files but got 16 on the page, from server side is OK, also when I get files after upload its also works fine shows 4 out of 4</p>
<p>The problem was with asynchronicity, <code>done</code> function was firing asynchronously so my getFile function was in the "queue" , the fix was just to place <code>attachedFiles.html('');</code> inside getFile function, so it will erase everything and start over, populating the div;</p>
How to get distance triggers working in argon.js and AFrame? <p>I'm trying to add distance triggers to an object in my ar-scene, following the <a href="https://github.com/argonjs/argon-aframe" rel="nofollow">code snippet</a> on the project's github page.</p> <p>The following gives me errors in Argon.</p> <p><code>&lt;ar-geopose id="GT2" lla=" -84.398881 33.778463" userotation="false" trigger="radius:100;event:alert('You are near GT.');"&gt; &lt;/ar-geopose&gt;</code></p> <p>Am I calling events incorrectly? </p>
<p>(This all assumes you are using argon.js and argon-aframe.js from <a href="http://argonjs.io" rel="nofollow">http://argonjs.io</a>)</p> <p>The "event" attribute of your trigger needs to be the name of an event you want to generate, not code to execute. The attributes of the components (like trigger) specify parameters (like any CSS attributes), not code.</p> <p>So, you should use something like this in your javascript</p> <pre><code>trigger="radius:100;event:target_trigger" </code></pre> <p>This will cause the trigger component to <code>emit("target_trigger")</code> on the entity you've attached it to.</p> <p>You could listen for that by doing something like </p> <pre><code>var GT = document.querySelector("#GT2"); GT.addEventListener('target_trigger', function(evt) { alert("you are near GT."); }); </code></pre> <p>I would avoid using alerts in an AR app, of course, but I assume you're doing this for testing/debugging.</p>
How to extend a website with a calculated column? <p>I actually don't know what I could search for, so I need advice in technology. So what do I want?</p> <p>Imagine you are visiting a website and you see a table/div combination like this:</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;div class="a"&gt; &lt;div class="price1"&gt; &lt;span&gt;100$&lt;/span&gt; &lt;/div&gt; &lt;div class="quantity"&gt; &lt;span&gt;3&lt;/span&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>You have a price and a quantity of an article and you want to calculate the sum (300$) dynamically and add the result somewhere on the website (one column more for example).</p> <p><strong>What can I do to achieve this dynamically like using a browser debugging tool like Firebug?</strong> I don't want to make a Java Application with an InputStream. </p> <p>(Note that I do not own the website!)</p>
<p>To adjust a page that way you need to modify it using <a href="https://developer.mozilla.org/en-US/docs/Glossary/JavaScript" rel="nofollow">JavaScript</a>.</p> <p>Regarding your example, to add the sum after the price and quantity you could have a script like this:</p> <pre class="lang-js prettyprint-override"><code>let price = Number.parseFloat(document.querySelector(".price1 &gt; span").textContent); let quantity = Number.parseFloat(document.querySelector(".quantity &gt; span").textContent); let a = document.querySelector(".a"); let sum = document.createElement("div"); sum.textContent = price * quantity; a.appendChild(sum); </code></pre> <p>This script can be executed with the command line of the browser debugging tool.</p> <p>Though note that this change is only temporary. It will be gone again the next time you access the website or reload it. To apply the script everytime the page is loaded you can use a browser add-on like <a href="https://addons.mozilla.org/firefox/addon/greasemonkey/?src=stackoverflow" rel="nofollow">Greasemonkey</a>, which allows to automatically execute your script on specific pages.</p>
What does defining a function with in the __init__ constructor in python mean? <p>I have just seen the following code and would like to know what the function within the <code>__init__</code> function means</p> <pre><code>def __init__(self): def program(percept): return raw_input('Percept=%s; action? ' % percept) self.program = program self.alive = True </code></pre>
<p>This code</p> <pre><code>class Foo: def __init__(self): def program(percept): return raw_input('Percept=%s; action? ' % percept) self.program = program </code></pre> <p>AFAIK, is actually the exact same as this since <code>self.program = program</code>. </p> <pre><code>class Foo: def __init__(self): pass def program(self, percept): return raw_input('Percept=%s; action? ' % percept) </code></pre> <p>The only reason I can see to nest a function there was if you just used the function to do some initializations within the constructor, but didn't want to expose it on the class. </p>
Why reinterpret_cast fails while memcpy works? <p>I'm writing some socket code and based on some params I'm using either IPv4 or IPv6. For that I have a code like this:</p> <pre><code>struct sockaddr final_addr; ... struct sockaddr_in6 addr6; ... memcpy(&amp;final_addr, &amp;addr6, size); ... bind(fd, &amp;final_addr, size); </code></pre> <p>This works fine. However if I do (which was my initial idea)</p> <pre><code>struct sockaddr final_addr; ... struct sockaddr_in6 addr6; ... final_addr = *reinterpret_cast&lt;struct sockaddr*&gt;(&amp;addr6); ... bind(fd, &amp;final_addr, size); </code></pre> <p>then it fails on <code>bind</code> with <code>Cannot assign requested address</code> error.</p> <p>Note that this incorrect code works fine if I switch to IPv4's <code>sockaddr_in</code>.</p> <p>What's going on here? Why can't I just reinterpret <code>sockaddr_in6</code> as <code>sockaddr</code>?</p>
<p>If in the first version of the code <code>size</code> is <code>sizeof(addr6)</code> (as you stated in the comments), then the first version of the code uses <code>memcpy</code> to copy <code>sizeof(struct sockaddr_in6)</code> bytes of data.</p> <p>The second version of the code uses regular <code>struct sockaddr</code> assignment to copy only <code>sizeof(struct sockaddr)</code> bytes.</p> <p><code>sizeof(struct sockaddr)</code> is smaller than <code>sizeof(struct sockaddr_in6)</code>, which makes these two code samples different.</p> <p>Note that in the first version the recipient object in that <code>memcpy</code> is of <code>struct sockaddr</code> type, i.e. it is smaller than the number of bytes copied. Memory overrun occurs, which clobbers some other data stored in adjacent memory locations. The code "works" only by accident. I.e. if this bit "works", then some other piece of code (the one that relies on the now-clobbered data) is likely to fail.</p>
Inner join multiple tables get name instead of id <p>I have 4 tables</p> <pre><code>Table incidences-employees --------------------------- idIncidenceEmployee PK idEmployee FK (employee.idemployee) idMasterIncidence FK (incidence-master.idIncidence) createdby FK (user-employee.idMongoUser) authorizedBy FK (user-employee.idMongoUser) Table incidence-master --------------------------- idIncidence PK name TAble user-employee -------------------------- idMongoUser PK idEmployee Table EMployee ------------------------- idEmployee Pk name lastName </code></pre> <p>I do this query </p> <pre><code>SELECT employee.name, incidences-master.name, incidences-employees.* FROM employee-incidences INNER JOIN employee ON employee.idEmployee = employee-incidences.idEmployee INNER JOIN incidences-master ON incidences-master.idIncidence = employee-incidences.idIncidenceEmployee </code></pre> <p>I get this</p> <pre><code>Employee name | Incidence name | idIncidenceEmployee | idEmployee | idMasterIncidence | createdby | authorizedBy John Doe | Incidence Name | 1 | 1 | 5 | abc123 | abc123 </code></pre> <p>But on created and authorizated by I get an ID, abc123, what I want is to match the id with a name, that id is ont the table user-employee</p> <pre><code> Table user-employee Table Employee ---------------------- - ------------------- idMongoUser -&gt; abc123 idEmployee -&gt; 1 idemployee -&gt; 1 Name -&gt; John Doe </code></pre> <p>I want John Doe to appear instead of the id.</p>
<p>incidences-employees.* is giving you all the fields from that table, which include the two IDs. One approach is to do two more joins, joining the employee table to the incidences table where employee.idemployee = incidences-employee.createdby and authorizedby. </p> <p>Then instead of using .*, you reference each field you want. You will also make things easier by using aliases like:</p> <pre><code>select ... from incidences-employee I join employee E1 on E1.idemployee = I.createdby </code></pre> <p>Then you can reference E1.name for the createdby name.</p>
How To Change Pycharms Default Testing Skeleton From Unittest Format to Pytest? <p>I'm trying to change from Unittest to PyTests. After changing the default test runner from Unittests to py.test under Python integration Tools I'm still getting the Unittest skeleton when creating a new test:</p> <p>Instead of this:</p> <pre><code>from unittest import TestCase class Test&lt;selected function&gt;(TestCase): pass </code></pre> <p>I want it to be this:</p> <pre><code>import pytest class Test&lt; selected function &gt;: def test_&lt;selected function&gt;: pass </code></pre> <p>I tried changing the Python Unit Test Code Template under Preferences>Editor>File and Code templates.</p> <p>No luck. Where do I change the default testing template?</p>
<p>In my case, the best solution I came up with was creating a new template. I called it <code>Python Test</code> and the template is as follows.</p> <pre><code># -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import pytest def test(): pass </code></pre> <p>This speeds up enough my test creation. At some point they will probably add the testing functionality.</p>
adding tuples to a list in an if loop (python) <p>I'm working in python with symbulate for a probability course and running some simulations. </p> <p>Setup: Two teams, A and B, are playing in a “best of n” game championship series, where n is an odd number. For this example, n=7, and the probability team A wins any individual game is 0.55. Approximate the probability that Team A wins the series, given that they win the first game.</p> <p>Here is what I've got so far, which I think is along the right lines:</p> <pre><code>model = BoxModel([1, 0], probs=[0.55, .45], size=7, replace=True) test = model.sim(10000) for x in range(0,10000): test1 = test[x] if test1[0] == 1: print (test1) test1 </code></pre> <p>The last two lines are where I'm having my difficulty. This 'for' and 'if' combination makes it so only the inputs that start with a '1' (i.e. Team A winning the first game) are displayed. I need to save these inputs into a table so that I can run some further testing on it.</p> <p>How do I input the value of test1 into a table while those loops are running? Currently, test1 only outputs the x=10,000th value.</p> <p>Edit: The "test" yields a list, 0-10000, of all the possible game outcomes. I need a list that only has the game outcomes that start with a "1".</p> <p>Edit2: Output of "test" (before I run a "for" or "if") look like: </p> <pre><code>Index Result 0 (1, 1, 1, 0, 0, 1, 1) 1 (0, 1, 0, 1, 1, 0, 0) 2 (1, 1, 1, 1, 0, 1, 0) 3 (0, 0, 1, 1, 1, 1, 1) 4 (0, 0, 0, 0, 0, 0, 0) 5 (1, 1, 0, 1, 0, 0, 1) 6 (0, 0, 1, 0, 1, 1, 1) 7 (0, 1, 0, 0, 0, 0, 1) 8 (1, 1, 0, 1, 0, 1, 0) ... ... 9999 (1, 1, 0, 1, 0, 0, 0) </code></pre> <p>I need a "test' (or another variable) to contain something that looks EXACTLY like that, but only contains lines that start with "1". </p>
<p>So you're looking to store the results of each test? Why not store them in a <code>list</code>?</p> <pre><code>test1_results = [] for x in range(0,10000): test1 = test[x] # check if first element in sequence of game outcomes is a win for team A if test1[0] == 1: # or '1' if you're expecting string test1_results.append(test1) </code></pre> <p>You can the run <code>print(test1_results)</code> to print the entire list of results, but if you want to print the first <code>n</code> results, do <code>print(test1_results[:n])</code>.</p> <p>If you want your <code>if</code> statement in there, you will have to slightly adjust the placement. What does your <code>test</code> object look like? Could you give us a small sample?</p> <p>edit: updated <code>if</code> statement to reflect comment below</p>
How can I display the results of a javascript function <p>I have an HTML link which is playing a sound through a javascript function.</p> <pre><code>&lt;a style="width:20%;" href="javascript:playArSound();"&gt;Listen&lt;/a&gt; </code></pre> <p>I would like to find out the value of href after the javascript has been performed, so that I can know where the mp3 file is located.</p> <p>Can anyone advise me how to do this please?</p>
<p>You need to use <code>getAttribute()</code> method to get the value of any attribute of element.Try the below code.</p> <pre><code>document.getElementsByTagName("a").getAttribute('href') </code></pre>
Select All checkbox in table header is causing issues <hr> <p>I have a table which contains a 'Select All' checkbox as the first column in the header row.</p> <p>The problem is column headers make perfectly sense when they represent the data type of their columns but the content of this th is just a checkbox with a "Select All" label.</p> <p>As it is now, it sets a relationship with all the checkboxes in its column, we're basically saying that all the checkboxes are someway related to "Select All".</p> <p>Is there any way to markup a 'Select All' checkbox in the table header so the relationship in terms of labeling is broken with all the checkboxes below it?</p> <p>I've read that changing the th in the table header that houses the 'Select All' checkbox to a td will solve this (and it does), but was curious if there's another solution that wouldn't require me to affect the markup of the header.</p> <p><strong>Screen reader reads as follows for the checkbox table header and table cell:</strong></p> <p><em>This is a table of Manage Courses. table with 3 rows and 6 columns row 1 Select all items in this table column 1 Select all items in this table checkbox not checked</em></p> <p><em>row2 Select all items in this table column 1 Dev ILT 1 checkbox not checked</em></p> <p>As you can see announcing the select checkbox for the course 'Dev ILT 1' as 'Select all items in this table' is misleading</p> <p><strong>Code example. This is just the header and body section.</strong> Not all rows or headers are listed in the code example as it's not relevant</p> <pre><code>&lt;thead&gt; &lt;tr class="thead-main"&gt; &lt;th align="center" scope="col" valign="top" class="colheadcheckbox"&gt; &lt;input type="checkbox" aria-label="Select all items in this table" onclick="SelectAllCheckbox.CheckUncheckAll(this, 'selectedID')" id="SelectAll"&gt; &lt;label for="SelectAll"&gt;&lt;span class="hidden"&gt;Select all items in this table.&lt;/span&gt;&lt;/label&gt; &lt;/th&gt; &lt;th scope="col" align="left" valign="middle" class="colhead"&gt; &lt;a href="?reverseSortBy=Name" title="Sort this column by descending order" class="sortdown"&gt; &lt;span&gt; Name &lt;/span&gt; &lt;img src="/geonext/images/skins/simple/schemes/dalmatian/indicator_sort_up.png" width="9" height="9" border="0" alt="This column is sorted by ascending order" title="This column is sorted by ascending order"&gt; &lt;/a&gt; &lt;/th&gt; &lt;th scope="col" align="left" valign="top" class="colhead"&gt; &lt;a href="?sortBy=Code" title="Sort this column by ascending order"&gt; Course Code &lt;/a&gt; &lt;/th&gt; &lt;th scope="col" align="left" valign="top" class="colhead"&gt; &lt;a href="?sortBy=class" title="Sort this column by ascending order"&gt; Type &lt;/a&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr class="first odd"&gt; &lt;td align="center" valign="middle" class=""&gt; &lt;input type="checkbox" class="checkbox with-font" name="selectedID" id="selectedID2" value="2"&gt; &lt;label for="selectedID2"&gt;&lt;span class="hidden"&gt; 2&lt;/span&gt;&lt;/label&gt; &lt;/td&gt; &lt;td class="sorted" align="Left"&gt; &lt;label for="selectedID2"&gt;&lt;a href="/editcourse.geo?id=2"&gt;Dev ILT 1&lt;/a&gt; &lt;/label&gt; &lt;/td&gt; &lt;td align="Left"&gt; ILT1 &lt;/td&gt; &lt;td align="Left"&gt; Instructor Led &lt;/td&gt; &lt;/tr&gt; &lt;tr class="even"&gt; &lt;td align="center" valign="middle" class=""&gt; &lt;input type="checkbox" class="checkbox with-font" name="selectedID" id="selectedID1" value="1"&gt; &lt;label for="selectedID1"&gt;&lt;span class="hidden"&gt; 1&lt;/span&gt; &lt;/label&gt; &lt;/td&gt; &lt;td class="sorted" align="Left"&gt; &lt;label for="selectedID22507408476"&gt;&lt;a href="/editcourse.geo?id=1"&gt;Dev UDT 1&lt;/a&gt;&lt;/label&gt; &lt;/td&gt; &lt;td align="Left"&gt; UDT1 &lt;/td&gt; &lt;td align="Left"&gt; User Defined Task &lt;/td&gt; &lt;/tr&gt; ' &lt;/tbody&gt; </code></pre>
<p>I'm having a hard time understanding how 'Select All' is a valid heading. The heading is meant to provide context for the data in the associated cells. Used properly, a screenreader will read out the heading as you navigate into the column/row. </p> <p>If someone navigates from a cell in the second column into a cell in the first, it would theoretically read </p> <blockquote> <p>"[h1]Select All checkbox unchecked[/h1] [td]input-label checkbox unchecked[td]" </p> </blockquote> <p>(square bracket content added for clarity - if you are navigating from one column to the next, the column header is read out before the data for each new column you navigate into)</p> <p>This hardly provides context as to what the checkbox is. The 'Select All' checkbox should more likely be used as the last element or even a footer element rather than a heading. </p> <p>It's hard to fully understand without a code example, but I would suggest never including functional elements in a table heading. It's intended for phrasing content.</p>
gulp.series() doesn't run tasks <p>I can't figure out why <code>gulp.series()</code> is not firing in my callback function. </p> <p>I'm trying to grab a string from a user input with <code>gulp-prompt</code> and invoke a build and deployment function with <code>gulp.series()</code>. My tasks within <code>gulp.series()</code> don't fire at all.</p> <pre><code>gulp.task('test', function(){ const prompt = require('gulp-prompt'); return gulp.src('test.js') .pipe(prompt.prompt({ type: 'checkbox', name: 'env', message: 'which environment do you want to deploy to?', choices: ['qa','prod'] },function(res){ //console.dir(res.env); var env = res.env; console.log(env); console.log('hi'); gulp.series('clean', 'patternlab:build', 'tag-version', deployWeb.bind(this, env), function(done){ done(); }); })); }); </code></pre>
<p>Calling <code>gulp.series('task1', 'task2')</code> does <strong>not</strong> run <code>task1</code> and <code>task2</code>. All it does is return a new function. Only once you call <strong>that</strong> function are the tasks actually executed.</p> <p>That means in your case you need to do the following:</p> <pre><code>var runTasks = gulp.series('clean', 'patternlab:build', 'tag-version', deployWeb.bind(this, env)); runTasks(); </code></pre> <p>The whole <code>function(done){ done(); }</code> part that you had in your code doesn't really make much sense and isn't needed for <code>gulp.series()</code>.</p>
changing file content - is this a bug in g++ 4.7.2 or am I doing it wrong? <p>While writing some code to update a position in a binary file I noticed something strange. Consider this example code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; using namespace std; int main() { char tmp; string s; fstream fs; fs.open("test.txt", fstream::out); fs &lt;&lt; "blub" &lt;&lt; endl; fs.close(); fs.open("test.txt", fstream::in); fs &gt;&gt; s; cout &lt;&lt; s &lt;&lt; endl; fs.close(); fs.open("test.txt", ios::in|ios::out|ios::binary); if (!fs.is_open() || !fs.good()) cerr &lt;&lt; "could not open!" &lt;&lt; endl; fs.read(&amp;tmp, 1); fs.read(&amp;tmp, 1); //fs.tellg(); //&lt;-- required to fix for old g++? const char *c = "ah"; fs.write(&amp;c[0], 1); fs.write(&amp;c[1], 1); fs.close(); fs.open("test.txt", fstream::in); fs &gt;&gt; s; cout &lt;&lt; s &lt;&lt; endl; } </code></pre> <p>In recent g++ versions (at least with 6.2.1), I can just read and then write some bytes without problems - In the example you get the correct output:</p> <pre><code>blub blah </code></pre> <p>Then I compiled the code with g++ 4.7.2 and suddenly the update has no effect, i.e. the second output is still "blub", <strong>unless</strong> I add fs.tellg() or fs.tellp(). I've found <a href="http://stackoverflow.com/questions/17536570/reading-and-writing-to-the-same-file-using-the-same-fstream">this</a> question, but as I understand, this is a limitation under Windows, but I am working under Linux.</p> <p>Now I wonder, is this a bug in the old g++ or am I doing it wrong and was just lucky with the modern g++ version, where it just works? Second question, why does asking for the current position fix it?</p> <p>Thanks in advance!</p>
<blockquote> <p>Now I wonder, is this a bug in the old g++</p> </blockquote> <p>No, there is no bug in g++ in this regard.</p> <blockquote> <p>or am I doing it wrong</p> </blockquote> <p>Yes. This is explained in the <a href="http://stackoverflow.com/questions/17536570/reading-and-writing-to-the-same-file-using-the-same-fstream">answer</a> that you linked.</p> <blockquote> <blockquote> <p>... output shall not be directly followed by input without an intervening call to the fflush function or to a file positioning function (fseek, fsetpos, or rewind), and input shall not be directly followed by output without an intervening call to a file positioning function, unless the input operation encounters end- of-file.</p> </blockquote> </blockquote> <p>Which is from C standard but made relevant by:</p> <blockquote> <blockquote> <p>The restrictions on reading and writing a sequence controlled by an object of class basic_filebuf are the same as for reading and writing with the Standard C library FILEs.</p> </blockquote> </blockquote> <p>There is a bug, but it is in your code. Your program doesn't meet the requirements laid out by the standard.</p> <blockquote> <p>but as I understand, this is a limitation under Windows</p> </blockquote> <p>That may possibly be the case, but more generally the limitation is in C++ (and C) specification. Whether a standard library has the limitation has no effect on whether the library is standard compliant. Any code that depends on the non-existence of the limitation is not compliant with the standard.</p> <blockquote> <p>and was [I] just lucky with the modern g++ version</p> </blockquote> <p>One might say that you were unlucky. It was a stroke of luck when the program didn't work and you discovered the bug.</p> <blockquote> <p>Second question, why does asking for the current position fix it?</p> </blockquote> <p>I doubt that <code>tellg</code> is sufficient to make your program compliant with the standard. So, I would say that it "fixes" the program by chance.</p> <p>You should probably be using <code>std::flush(fs);</code> instead.</p> <blockquote> <p>this would mean that the NEW version is LESS standard compliant? </p> </blockquote> <p>No, both versions of g++ are equally compliant in this regard. Your program isn't.</p>
git lfs bfg: after that, resolve conflicts how? <p>We have a repository in which we committed PDF snapshots of reports. I want to try out git lfs, see if it improves the quality of life.</p> <p>I followed the procedures here (<a href="https://github.com/rtyley/bfg-repo-cleaner/releases" rel="nofollow">https://github.com/rtyley/bfg-repo-cleaner/releases</a>) to use BFG to clean out the old binaries and transition to lfs. I wound my way through a couple of wrinkles related to the usage of Gitlab server for the repository, but in the end I believe this went well. </p> <p>I'm writing to show what we did and ask a question about cleaning up merge conflicts at the very end.</p> <p>I'll show you the transcript. We check out a "--mirror" clone (a bare repo) and BFG does its work on that, then we push it back after fiddling about:</p> <pre><code>guides-to-lfs$ git clone --mirror git@gitlab.kucenter.edu:crmda/guides.git Cloning into bare repository 'guides.git'... X11 forwarding request failed on channel 0 remote: Counting objects: 865, done. remote: Compressing objects: 100% (527/527), done. remote: Total 865 (delta 318), reused 834 (delta 303) Receiving objects: 100% (865/865), 151.75 MiB | 25.74 MiB/s, done. Resolving deltas: 100% (318/318), done. Checking connectivity... done. guides-to-lfs$ cd guides.git/ guides.git$ java -jar ~/bin/bfg-1.12.13.jar --convert-to-git-lfs '*.{pdf,ogv,tar.gz,zip}' --no-blob-protection Using repo : /home/pauljohn/GIT/CRMDA/guides-to-lfs/guides.git Found 0 objects to protect Found 3 commit-pointing refs : HEAD, refs/heads/master, refs/tmp/fd782dd8787a3ffb673455d1eafb9869/head Protected commits ----------------- You're not protecting any commits, which means the BFG will modify the contents of even *current* commits. This isn't recommended - ideally, if your current commits are dirty, you should fix up your working copy and commit that, check that your build still works, and only then run the BFG to clean up your history. Cleaning -------- Found 124 commits Cleaning commits: 100% (124/124) Cleaning commits completed in 1,933 ms. Updating 2 Refs --------------- Ref Before After -------------------------------------------------------------------- refs/heads/master | e3327ef1 | e4ac76a2 refs/tmp/fd782dd8787a3ffb673455d1eafb9869/head | 74ccc454 | 6639b246 Updating references: 100% (2/2) ...Ref update completed in 19 ms. Commit Tree-Dirt History ------------------------ Earliest Latest | | .......DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD D = dirty commits (file tree fixed) m = modified commits (commit message or parents changed) . = clean commits (no changes to file tree) Before After ------------------------------------------- First modified commit | cdd8f486 | 5e6b64eb Last dirty commit | e3327ef1 | e4ac76a2 Changed files ------------- Filename Before &amp; After -------------------------------------------------------------------------------------------------------------------- 01.LISREL.Syntax.pdf | 71a17dcc ⇒ 7f217f4d 02.ReadingDataIntoLISREL.pdf | c05c3fe6 ⇒ e7238e11 03.InterpretingLISRELOutput.pdf | 6ef054c8 ⇒ a2a63813 04.StartingValuesInLISREL.pdf | 335d7a09 ⇒ c86439ee, 9f6fc232 ⇒ 05182a86 05.WhatToReport.pdf | 2bee7a8d ⇒ 1106d2f4, 3d30b103 ⇒ ce27382c 06.Satorra-BentlerChi-Sq.pdf | 94ec6fd2 ⇒ b81d08b4, 7cd29d48 ⇒ 704d5f30 ... In total, 375 object ids were changed. Full details are logged here: guides.git.bfg-report/2016-10-05/14-03-18 BFG run is complete! When ready, run: git reflog expire --expire=now --all &amp;&amp; git gc --prune=now --aggressive guides.git$ git reflog expire --expire=now --all guides.git$ git gc --prune=now </code></pre> <p>In case you try this, you should be ready for some trouble pushing back into the repo. One issue is that Gitlab before 8.12 did not integrate password management between the SSH transfers for git and the HTTPS transfers for git lfs. Another problem is Gitlab project "protection", which you may have seen if you use Gitlab. I saw this the first time I pushed:</p> <pre><code>guides.git$ git push X11 forwarding request failed on channel 0 Git LFS: (0 of 105 files) 0 B / 140.38MB http: Post https://gitlab.kucenter.edu/crmda/guides.git/info/lfs/objects/batch: x509: certificate signed by unknown authority http: Post https://gitlab.kucenter.edu/crmda/guides.git/info/lfs/objects/batch: x509: certificate signed by unknown authority error: failed to push some refs to 'git@gitlab.kucenter.edu:crmda/guides.git' </code></pre> <p>We made several changes to get around the problem. We needed the absolutely newest version of Gitlab (8.12.4). I needed to tell Git to ignore the out-of-date-certificates. On the Gitlab server, the project had to be "unprotected" so that developers could push. I don't understand why that was necessary because I'm the owner and I can push regular git changes, but apparently the lfs integration is different. After that fussing about, we have success pushing back to repository:</p> <pre><code>guides.git$ GIT_SSL_NO_VERIFY=true git push X11 forwarding request failed on channel 0 Git LFS: (0 of 0 files, 105 skipped) 0 B / 0 B, 140.38 MB skipped Counting objects: 866, done. Delta compression using up to 8 threads. Compressing objects: 100% (520/520), done. Writing objects: 100% (866/866), 32.94 MiB | 26.41 MiB/s, done. Total 866 (delta 311), reused 866 (delta 311) To git@gitlab.kucenter.edu:crmda/guides.git + e3327ef...e4ac76a master -&gt; master (forced update) + 74ccc45...6639b24 refs/tmp/fd782dd8787a3ffb673455d1eafb9869/head -&gt; refs/tmp/fd782dd8787a3ffb673455d1eafb9869/head (forced update) </code></pre> <p>Success!</p> <p>Then I went back to the working directory of this repository, the one that had the PDF files saved inside it, and tried a git pull. I see a lot of merge conflicts that I'll have to address:</p> <pre><code>guides$ git pull X11 forwarding request failed on channel 0 remote: Counting objects: 792, done. remote: Compressing objects: 100% (491/491), done. remote: Total 792 (delta 294), reused 791 (delta 293) Receiving objects: 100% (792/792), 32.92 MiB | 54.09 MiB/s, done. Resolving deltas: 100% (294/294), done. From gitlab.kucenter.edu:crmda/guides + e3327ef...e4ac76a master -&gt; origin/master (forced update) warning: Cannot merge binary files: keyword_guide/guide_keywords.pdf (HEAD vs. e4ac76a2561fd4dc3ca52971e8ee3d5cbe930a0c) warning: Cannot merge binary files: Spanish_KUant_Guides/PDFs/9._opcion_RP_en_LISREL.pdf (HEAD vs. e4ac76a2561fd4dc3ca52971e8ee3d5cbe930a0c) warning: Cannot merge binary files: Spanish_KUant_Guides/PDFs/8._Imputacion_de_datos.pdf (HEAD vs. e4ac76a2561fd4dc3ca52971e8ee3d5cbe930a0c) warning: Cannot merge binary files: Spanish_KUant_Guides/PDFs/7._bootstrap.pdf (HEAD vs. e4ac76a2561fd4dc3ca52971e8ee3d5cbe930a0c) warning: Cannot merge binary files: Spanish_KUant_Guides/PDFs [...snip out hundreds of those ...] Automatic merge failed; fix conflicts and then commit the result. </code></pre> <p>I <em>think</em> I'll probably just make a clean clone of the remote and go on from there. The instructions I find on the Internet don't help too much with that, they are mostly about getting started with lfs, not so much about dealing with on-going lfs and clones of lfs. I worry a little bit about what would happen if somebody cloned this thing and they did not have lfs. Oh, well, we'll see.</p> <p>Here's my question. If I did want to deal with all of those binary conflicts, what would I do? If I simply want to accept all of the changes from the server, it appears I just need to run this over and over again, once for each conflicted "fn.pdf".</p> <pre><code>$ git checkout --theirs -- fn.pdf $ git add fn.pdf </code></pre> <p>Doing that over and over seems tedious, but I suppose I can do it. </p> <p>I also found advice in here (<a href="http://stackoverflow.com/questions/278081/resolving-a-git-conflict-with-binary-files">Resolving a Git conflict with binary files</a>) to try </p> <pre><code>$ git mergetool </code></pre> <p>but I can't tell for sure how to interact with it. The diff thing launches an gvim frame with 3 columns of buffers, but I have not successfully navigated it. It appears to me that's landing me in editor hell.</p>
<blockquote> <p>I think I'll probably just make a clean clone of the remote and go on from there.</p> </blockquote> <p>Right, this is the most important step after using any tool, be it BFG, filter-branch etc. which rewrites history (and usually in doing-so is removing unwanted files referenced in that history). BFG home page says:</p> <blockquote> <p>At this point, you're ready for everyone to ditch their old copies of the repo and do fresh clones of the nice, new pristine data. It's best to delete all old clones, as they'll have dirty history that you <em>don't</em> want to risk pushing back into your newly cleaned repo.</p> </blockquote> <p>The new/rewritten history will be from some-point in history forwards (the point of the first change in the rewrite) completely divergent from the old history as far as Git is concerned, because all commit-hashes from that point forward will change. The only sane way to proceed is for all developers to retire their current clones of the old history and obtain new clones. In theory you could update these, but it would require a lot of care with not much value.</p> <p>Removing old clones reduces the chance of someone pushing references to the old history, thereby reintroducing the old history and the unwanted files it contained.</p>
Ruby regex eliminate new line until . or ? or capital letter <p>I'd like to do the following with my strings: </p> <pre><code>line1= "You have a house\nnext to the corner." </code></pre> <p>Eliminate <code>\n</code> if the sentence doesn't finish in new line after dot or question mark or capital letter, so the desired output will be in this case: </p> <pre><code>"You have a house next to the corner.\n" </code></pre> <p>So another example, this time with the question mark: </p> <pre><code>"You like baggy trousers,\ndon't you? </code></pre> <p>should become:</p> <pre><code>"You like baggy trousers, don't you?\n". </code></pre> <p>I've tried: </p> <pre><code>line1.gsub!(/(?&lt;!?|.)"\n"/, " ") </code></pre> <p><code>(?&lt;!?|.)</code> this immediately preceding \n there must NOT be either question mark(?) or a comma</p> <p>But I get the following syntax error:</p> <pre><code>SyntaxError: (eval):2: target of repeat operator is not specified: /(?&lt;!?|.)"\n"/ </code></pre> <p>And for the sentences where in the middle of them there's a capital letter, insert a \n before that capital letter so the sentence:</p> <pre><code>"We were winning The Home Secretary played a important role." </code></pre> <p>Should become:</p> <pre><code>"We were winning\nThe Home Secretary played a important role." </code></pre>
<p>You are nearly there. You need to a) escape both <code>?</code> and <code>.</code> and b) remove quotation marks around <code>\n</code> in the expression:</p> <pre><code>line1= "You have a house\nnext to the corner.\nYes?\nNo." line1.gsub!(/(?&lt;!\?|\.)\s*\n\s*/, " ") #⇒ "You have a house next to the corner.\nYes?\nNo." </code></pre> <p>As you want the trailing <code>\n</code>, just add it afterwards:</p> <pre><code>line1.gsub! /\Z/, "\n" #⇒ "You have a house next to the corner.\nYes?\nNo.\n" </code></pre>
Swift Memory Management <p>I am developing an app in Swift and I am coming from non-arc Objective-C background. I ran into memory issues. So, I implemented <code>deinit</code> in my ViewControllers. None of them got called. Some code example:</p> <pre><code>@objc protocol ServerDelegate { @objc optional func onUpdateComplete () } var delegate_ : ServerDelegate? </code></pre> <p>I googled around and found that all my delegates were set to strong references. So, I made them weak references like:</p> <pre><code>@objc protocol ServerDelegate : class { @objc optional func onUpdateComplete () } weak var delegate_ : ServerDelegate? </code></pre> <p>and now <code>deinit</code> is called for each ViewController.</p> <p>However, when I see memory it does get freed up when I pop a View Controller from Navigation Controller. For example, In the very first scene I had 10 MB of memory allocated, I pushed a view controller, memory increased to 15 MB. Now when I pop it, <code>deinit</code>is called but this extra 5 MB is not freed. But if I push it again. Memory does not increase to 20 MB. It stays at 15 MB. Why is this happening? Is this normal? Are the images being cached and not released? Can I manually release them when I pop the View Controller? Thanks.</p>
<p>There is a system cache for images per the documentation of <a href="https://developer.apple.com/reference/uikit/uiimage/1624146-init" rel="nofollow"><code>UIImage.init(named:)</code></a>; you cannot manually flush it but Apple's design intention is that you wouldn't ever get any benefit from doing so if you could — like all <code>NSCache</code>-type caches it'll automatically flush itself should memory ever become scarce. So in the meantime all a flush would achieve would be fewer cache hits and expenditure of the processor cycles required for the flush.</p> <p>The documentation advises use of <code>imageWithContentsOfFile:</code> if you want to avoid the cache but if you're loading or being loaded from a XIB or Storyboard then you don't have sufficient direct control to assert influence.</p>
awk print overwrite strings <p>I have a problem using awk in the terminal. I need to move many files in a group from the actual directory to another one and I have the list of the necessary files in a text file, as:</p> <p>filename.txt </p> <pre><code>file1 file2 file3 ... </code></pre> <p>I usually digit:</p> <pre><code>paste filename.txt | awk '{print "mv "$1" ../dir/"}' | sh </code></pre> <p>and it executes:</p> <pre><code>mv file1 ../dir/ mv file2 ../dir/ mv file3 ../dir/ </code></pre> <p>It usually works, but now the command changes its behaviour and awk overwrites the last string <code>../dir/</code> on the first one, starting again the print command from the initial position, obtaining:</p> <pre><code>../dire1 ../dir/ ../dire2 ../dir/ ../dire3 ../dir/ </code></pre> <p>and of course it cannot be executed. What's happened? How do I solve it?</p>
<p>Your input file contains carriage returns (<code>\r</code> aka <code>control-M</code>). Run <code>dos2unix</code> on it before running a UNIX tool on it.</p> <p>idk what you're using paste for though, and you should not be using awk for this at all anyway, it's just a job for a simple shell script, e.g. remove the <code>echo</code> once you've tested this:</p> <pre><code>$ &lt; file xargs -n 1 -I {} echo mv "{}" "../dir" mv file1 ../dir mv file2 ../dir mv file3 ../dir </code></pre>
Grid.MVC Sorting Bug <p>Grid.MVC sorting not working as expected. For example I have a column with a number value and also date values. The screen shots provided show only the Total Premium sort not working right, but the same thing happens on the Effective Date Column as well. Is there something additional I need to do to tell it its a number or date so it sorts correctly?</p> <pre><code>@Html.Grid(Model.SearchResult).Named("searchGrid").Columns(col =&gt; { col.Add(c =&gt; c.PolicyNumber).Titled("Number").Sortable(true); col.Add(c =&gt; c.FormattedInsuredName).Titled("Insured Name").Sortable(true); col.Add(c =&gt; c.FormattedAddress).RenderValueAs(m =&gt; Html.Raw(m.FormattedAddress)).Encoded(false).Sanitized(false).Titled("Property Address").Sortable(true); col.Add(c =&gt; c.Status).Titled("Status").Sortable(true); col.Add(c =&gt; c.FormattedEffectiveDate).Titled("Effective Date").Sortable(true); col.Add(c =&gt; c.FormattedTotalPremium).Titled("Total Premium").Sortable(true); col.Add().Encoded(false).SetWidth(150).Sanitized(false).Titled("Action").RenderValueAs(dd =&gt; Html.DropDownList("ddlAction", dd.DropDownActions, new { @class = "form-control ddlAction", @data_viewquote = dd.QuoteURL })); }).WithPaging(25).Sortable(true) </code></pre> <p>From the screen shot below you can see that the Total Premium column is being sorted incorrectly. There are screen shots for both ASC and DESC.</p> <p><a href="http://i.stack.imgur.com/Q1Z52.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q1Z52.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/aqCTn.png" rel="nofollow"><img src="http://i.stack.imgur.com/aqCTn.png" alt="enter image description here"></a></p>
<p>Thanks Santi for the comment. </p> <p>The type for the model was being formatted to a string to show a certain format before it got to the grid. Removed the string formatting and put the formatting up at the grid to allow sorting on the proper type and still show formatting. New grid below with the additional .Format() pieces.</p> <pre><code>@Html.Grid(Model.SearchResult).Named("searchGrid").Columns(col =&gt; { col.Add(c =&gt; c.PolicyNumber).Titled("Number").Sortable(true); col.Add(c =&gt; c.FormattedInsuredName).Titled("Insured Name").Sortable(true); col.Add(c =&gt; c.FormattedAddress).RenderValueAs(m =&gt; Html.Raw(m.FormattedAddress)).Encoded(false).Sanitized(false).Titled("Property Address").Sortable(true); col.Add(c =&gt; c.Status).Titled("Status").Sortable(true); col.Add(c =&gt; c.FormattedEffectiveDate).Titled("Effective Date").Sortable(true).Format("{0:MM/dd/yyyy}"); col.Add(c =&gt; c.FormattedTotalPremium).Titled("Total Premium").Sortable(true).Format("{0:C2}"); col.Add().Encoded(false).SetWidth(150).Sanitized(false).Titled("Action").RenderValueAs(dd =&gt; Html.DropDownList("ddlAction", dd.DropDownActions, new { @class = "form-control ddlAction", @data_viewquote = dd.QuoteURL })); }).WithPaging(25).Sortable(true) </code></pre>
how to display title of websites in node.js <p>I want to get title of different site. like this.</p> <pre><code>localhost:1234/index/?url=google.com&amp;url=www.yahoo.com/&amp;url=twitter.com </code></pre> <p>if i got to this url it crawl on all the mention site in the url and display title of website.</p> <pre><code> - Google - Yahoo - Twitter </code></pre>
<pre><code> var Urls = 'localhost:1234/index/?url=google.com&amp;url=www.yahoo.com/&amp;url=twitter.com'; // remove all special characters like '/' '&amp;' and '=' Urls = Urls.replace(/\&amp;/g, '').replace(/\//g, '').replace(/\=/g, ''); // split it based on url Urls = Urls.split('url'); //delete first element as its not required delete Urls[0] Urls.forEach(function (url) { //split each element based on '.' url = url.split('.'); url.forEach(function (ele) { // if its not 'www' and 'com' if (ele !== 'www' &amp;&amp; ele !== 'com') { // the title of url console.log(ele); } }) }) </code></pre> <p>you need to remove all special character as above using regular expression and if urls contains ".org" or ".in" .. etc, then that also need to include inside if condition </p>
Open Youtube Video With Image on iPhone Safari HTML Page <p>Could someone please help me to figure out how to use a placeholder image to open a youtube video on mobile so that if the user clicks the image on the html page in safari on iphone, the video automatically plays fullscreen (note: on iphone the video would automatically go fullscreen in this instance, just as when you click an embedded youtube iframe).</p> <p>Thank you!</p>
<p>Does the normal syntax below give you some sort of issue? It looks ok on my emulator... :</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;p&gt;&lt;a href="https://www.youtube.com/embed/ALqFFeU-Wp8"&gt;Full Screen&lt;/a&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
How to execute a line in a definition only once <p>So basically, I defined a variable in the beginning of a function and then i called it in a while loop. The problem is that inside the function I change the variable from True to False based on a condition. I want the variable to remain False. But since the definition is used in a while loop it goes back to the top of the function and changes it back to True. I have called that function in a class. And if i try calling defining the variable anywhere outside the definition then it tells me </p> <pre><code>***UnboundLocalError: local variable 'rotateDone' referenced before assignment*** </code></pre> <p>Here is the code</p> <pre><code>class LaserClass(): def __init__(self, pic, pos = (0,0)): self.original_image = pic self.position = Vector2D(*pos) def update(self): rotateDone = False mouse_pos = Vector2D(*pygame.mouse.get_pos()) diff2_mouse_pos = mouse_pos - self.position x_axis = Vector2D(0,0) angle = 360 - x_axis.get_angle(diff2_mouse_pos) for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: rotateDone = True gameLoop = False main_player = Player(tdfighter, pos=(displayX/2,displayY/2)) main_laser = LaserClass(laser, pos=(displayX/2 ,displayY/2)) </code></pre> <p>The variable i am talking about is rotateDone</p> <pre><code>while gameLoop == False: display.blit(space_bg,[0,0]) main_player.update() main_laser.update() display.blit(main_player.image, main_player.rect) display.blit(main_laser.image, main_laser.rect) pygame.display.update() display.blit(main_laser.image, main_laser.rect) pygame.display.update() </code></pre>
<p>Perhaps you can just made the variable a member of the object. Something like this:</p> <pre><code>class LaserClass(): def __init__(self, pic, pos = (0,0)): self.original_image = pic self.position = Vector2D(*pos) self.rotateDone = False def update(self): 'some code here' for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: self.rotateDone = True </code></pre>
Kubernetes 1.4 secret file permission not working <p>running K8s 1.4 with minikube on mac. I have the following in my replication controller yaml:<br> </p> <pre><code>volumes: - name: secret-volume secret: secretName: config-ssh-key-secret items: - key: "id_rsa" path: ./id_rsa mode: 0400 - key: "id_rsa.pub" path: ./id_rsa.pub - key: "known_hosts" path: ./known_hosts volumeMounts: - name: secret-volume readOnly: true mountPath: /root/.ssh </code></pre> <p>when I exec into a pod and check, I see the following:</p> <pre><code>~/.ssh # ls -ltr lrwxrwxrwx 1 root root 18 Oct 6 17:01 known_hosts -&gt; ..data/known_hosts lrwxrwxrwx 1 root root 17 Oct 6 17:01 id_rsa.pub -&gt; ..data/id_rsa.pub lrwxrwxrwx 1 root root 13 Oct 6 17:01 id_rsa -&gt; ..data/id_rsa </code></pre> <p>plus looking at the ~ level:</p> <pre><code>drwxrwxrwt 3 root root 140 Oct 6 17:01 .ssh </code></pre> <p>so the directory isn't read only and the file permissions seem to have been ignored (even the default 0644 doesn't seem to be working). Am I doing something wrong or is this a bug?</p>
<p>The .ssh directory has links to the actual files. Following the link shows the actual files have the correct permissions (read only for id_rsa). </p> <p>I validated the ssh setup would actually work by <code>exec</code>ing into a container generated from that replication controller and doing a git clone via ssh to a repo holding that key.</p>
svn commandline options to check in all files and not open the gui <p>Tortoise svn commandline tool is there a switch or an argument to check All files and to suppress the gui. I am working on source control automation.</p> <pre><code>TortoiseProc.exe /command:commit /path:"C:\SVN" /url:"http://mysvnserver/trunk" /closeonend:2 </code></pre>
<p>As Ken White alluded to in his comment, TortoiseSVN is not designed to be automated in a completely "silent" fashion. If that's your requirement, you should use <code>svn.exe</code> (which is installed with TortoiseSVN as an optional component, or you can get it standalone).</p> <p>If there's a module/library for the environment you're working in (like SVNKit for Java, SharpSVN for .NET, PySVN for Python and SVN::Client for Perl), try to use that.</p> <p>If you're using the command-line client, you'll use <code>svn commit c:\svn</code> but I'd suggest including a commit message too. See <a href="http://svnbook.red-bean.com/en/1.8/svn.ref.svn.c.commit.html" rel="nofollow"><code>svn help commit</code></a> for full details (<code>ci</code> is an alias for <code>commit</code>).</p>
Parsing JSON with Bash JQ Issue <p>Using bash JQ parser, Im trying parse the fields from a cURL <code>JSON</code> response.</p> <p>In file <code>'a.json'</code> has 4 'hash' values and <code>'b.json'</code> has 5 'hash' values. Based on the assumption that my results will be similar to <code>"a.json"</code> I wrote a parser for it.</p> <pre><code>#jq -r '.info[].hashes[0].value','.info[].hashes[1].value','.info[].hashes[2].value','.info[].hashes[3].value' a.json </code></pre> <p>Sample JSON files</p> <pre><code>#a.json { "info": { "file": { "Score": 4.01207390507143, "file_subtype": "None", "file_type": "EXE", "hashes": [ { "name": "A", "value": "7e5dcd8ffdfa8d726ecbdd3c69e18230" }, { "name": "B", "value": "3c6781d16dc26baf6422bb24d1cd0f650e451b99" }, { "name": "C", "value": "3c6781d16dc26baf6422bb24d1cd0f650e451b99" }, { "name": "D", "value": "c25561f3246ef188467a47971821bab93934842a1e2a48910db9768a2f66e828" } ], "size": 1912 } } } #b.json { "info": { "file": { "Score": 4, "file_subtype": "None", "file_type": "Image", "hashes": [ { "name": "A", "value": "f34d5f2d4577ed6d9ceec516c1f5a744" }, { "name": "B", "value": "66031dad95dfe6ad10b35f06c4342faa" }, { "name": "C", "value": "9df25fa4e379837e42aaf6d05d92012018d4b659" }, { "name": "D", "value": "4a51cc531082d216a3cf292f4c39869b462bf6aa" }, { "name": "E", "value": "e445f412f92b25f3343d5f7adc3c94bdc950601521d5b91e7ce77c21a18259c9" } ], "size": 500 } } } </code></pre> <p>But some times the results will be like "b.json" too and have 5 fields . when i'm trying to parse with the JQ command that i have written , Will give me only 4 fields and missing out the last value of "E".</p> <pre><code>#jq -r '.info[].hashes[0].value','.info[].hashes[1].value','.info[].hashes[2].value','.info[].hashes[3].value' b.json Result : f34d5f2d4577ed6d9ceec516c1f5a744 66031dad95dfe6ad10b35f06c4342faa 9df25fa4e379837e42aaf6d05d92012018d4b659 4a51cc531082d216a3cf292f4c39869b462bf6aa </code></pre> <p>Now , How can we select only the hash values from desired 'name'. </p> <p>Example : If we want to select only hash values of string 'names' B,C,E in any JSON files using JQ ?</p> <p>Any suggestions please ? </p>
<p>You can get all the values with this:</p> <pre><code>jq -r '.info.file.hashes[] | .value' *.json </code></pre> <p>Suppose you need only the values where name == "B"</p> <pre><code>jq -r '.info.file.hashes[] | select(.name == "B") | .value' </code></pre> <p>Suppose you need only the values where name == "B" <em>or</em> "C"</p> <pre><code>jq -r '.info.file.hashes[] | select(.name | in({"B":1,"C":1})) | .value' </code></pre> <p>The "in" function checks if the passed-in string is a key in the given object. The values of <code>{"B":1,"C":1}</code> are arbitrary. Ref: <a href="https://stedolan.github.io/jq/manual/#in" rel="nofollow">https://stedolan.github.io/jq/manual/#in</a></p>
How to copy current state of master branch into another branch? <p>Have tried the accepted answer on this page here: <a href="http://stackoverflow.com/questions/3672073/how-to-merge-the-current-branch-into-another-branch">How to merge the current branch into another branch</a></p> <p>But the problem is, the master doesn't have any changes needed, and I created the branch with: <code>git checkout -b mybranch</code></p> <p>When I try <code>git push self mybranch:master</code></p> <p>It tells me that Everything up-to-date. But I know that. I just want to copy branch to another so that it has the current state of the master branch. And it will not ever be touched again.</p> <p>I will only be branching off of the master branch in the future. This other branch will never actually be touched. But I need to archive it so that if need-be, I can switch to that branch and bring it back whenever...</p> <p>How to copy master branch without creating a New Repo?</p>
<p>For marking specific points in history, you should use <strong><em><a href="https://git-scm.com/book/en/v2/Git-Basics-Tagging" rel="nofollow">tags</a></em></strong>, not "abandoned" branches.</p>
CardView Xamarin Android <p>I try to make CardView</p> <p>I have this code for Adapter:</p> <pre><code> using System; using System.Collections.ObjectModel; using System.Collections.Specialized; using Android.Support.V7.Widget; using Android.Views; namespace NavDrawer.Adapters { public class RecyclerAdapter&lt;T, V&gt; : RecyclerView.Adapter where V : RecyclerView.ViewHolder { ObservableCollection&lt;T&gt; _Collection; int _ResourceId; Action&lt;T, V&gt; _UpdateViewHolder; public RecyclerAdapter(ObservableCollection&lt;T&gt; collection, int resourceId, Action&lt;T, V&gt; viewHolderUpdateAction) { _ResourceId = resourceId; _Collection = collection; _Collection.CollectionChanged += OnCollectionChanged; _UpdateViewHolder = viewHolderUpdateAction; } ~RecyclerAdapter() { _Collection.CollectionChanged -= OnCollectionChanged; } public override int ItemCount { get { return _Collection.Count; } } public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position) { var viewHolder = holder as V; var item = _Collection[position]; _UpdateViewHolder(item, viewHolder); } public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) { var itemView = LayoutInflater.From(parent.Context).Inflate(_ResourceId, parent, false); return (V)Activator.CreateInstance(typeof(V), new object[] { itemView }); } public T GetItem(int index) { return ((_Collection != null &amp;&amp; index &lt; _Collection.Count) ? _Collection[index] : default(T)); } public void RemoveItem(int index) { if (_Collection != null &amp;&amp; index &lt; _Collection.Count) { _Collection.RemoveAt(index); } } public void InsertItemAt(int index, T item) { if (_Collection != null &amp;&amp; index &lt; _Collection.Count) { _Collection.Insert(index, item); } } public new Type GetType() { return typeof(T); } void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: NotifyItemInserted(e.NewStartingIndex); break; case NotifyCollectionChangedAction.Remove: NotifyItemRemoved(e.OldStartingIndex); break; case NotifyCollectionChangedAction.Replace: NotifyItemChanged(e.OldStartingIndex); NotifyItemChanged(e.NewStartingIndex); break; case NotifyCollectionChangedAction.Move: NotifyItemRemoved(e.OldStartingIndex); NotifyItemRemoved(e.NewStartingIndex); break; case NotifyCollectionChangedAction.Reset: NotifyDataSetChanged(); break; } } } } </code></pre> <p>This to ViewHolder:</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Support.V7.Widget; namespace NavDrawer.Adapters { public class SponsorsViewHolder : RecyclerView.ViewHolder { public ImageView Image { get; private set; } public TextView Sponsor { get; private set; } public TextView Sponsordescription { get; private set; } public SponsorsViewHolder(View itemView, Action&lt;int&gt; listener) : base(itemView) { Image = itemView.FindViewById&lt;ImageView&gt;(Resource.Id.sponsorimage); Sponsor = itemView.FindViewById&lt;TextView&gt;(Resource.Id.sponsorstitle); Sponsordescription = itemView.FindViewById&lt;TextView&gt;(Resource.Id.sponsorsdescription); } /*void OnButtonClick(object sender, EventArgs e) { if (SomeAction != null) { SomeAction(); }*/ } } </code></pre> <p>And here is my Fragment where I need to show CardView:</p> <pre><code> using Android.App; using Android.Content; using Android.Support.V4.App; using Android.Views; using Android.Widget; using NavDrawer.Activities; using Fragment = Android.Support.V4.App.Fragment; using TaskStackBuilder = Android.Support.V4.App.TaskStackBuilder; using Com.Nostra13.Universalimageloader.Core; using MvvmCross.Droid.Support.V7.Fragging.Fragments; using MvvmCross.Droid.Support.V7.Fragging.Attributes; using NavDrawer.Core.ViewModels; using Android.Runtime; using NavDrawer.DownloadClasses; using System.Collections.Generic; using static NavDrawer.Activities.FirstView; using Newtonsoft.Json; using System.Collections.ObjectModel; using System; using Android.Support.V7.Widget; using NavDrawer.Adapters; namespace NavDrawer.Fragments { [MvxFragment(typeof(HomeViewModel), Resource.Id.content_frame)] [Register("navdrawer.fragments.SponsorsFragment")] public class SponsorsFragment : MvxFragment&lt;SponsorsViewModel&gt; { public class Sponsors { public string id { get; set; } public string company_name { get; set; } public string description { get; set; } public string sponsor_level { get; set; } public string picture { get; set; } public string location { get; set; } public string website_url { get; set; } public string sm_twitter { get; set; } public string sm_facebook { get; set; } public string sm_linkedin { get; set; } public string sm_pinterest { get; set; } public string contact_number { get; set; } public string attachments { get; set; } public string date_time { get; set; } } public SponsorsFragment() { this.RetainInstance = true; } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Android.OS.Bundle savedInstanceState) { var ignored = base.OnCreateView(inflater, container, savedInstanceState); var view = inflater.Inflate(Resource.Layout.SponsorsList, null); GetAllSponsor sponsorlist = new GetAllSponsor(); sponsorlist.getallsponsor(); string spnsrlst = sponsorlist.ToFormattedJsonString(); List&lt;Sponsors&gt; sponsorObjectData = JsonConvert.DeserializeObject&lt;List&lt;Sponsors&gt;&gt;(spnsrlst); recyclerView.SetLayoutManager(new LinearLayoutManager(Activity)); recyclerView.SetAdapter(new RecyclerAdapter&lt;Sponsors, SponsorsViewHolder&gt;(Spnsr, Resource.Layout.SponsorsCard)); return view; } } </code></pre> <p>}</p> <p>I have some questions:</p> <ol> <li>I cant find recyclerview via this code <code>var recyclerView = FindViewById&lt;RecyclerView&gt;(Resource.Id.recyclerView);</code></li> <li>How I need to write code to pass json data to ObservableCollection?</li> </ol> <p>Anybody can help me?</p> <p>Thank's </p>
<p>mate.</p> <p>In your SponsorsList layout, do you have the RecyclerView view?</p> <pre><code> &lt;android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="wrap_content" android:clipToPadding="false" android:scrollbars="vertical" /&gt; </code></pre> <p>I didn't quite catch what you mean by your second question but isn't it what you were willing?</p> <pre><code>recyclerView.SetAdapter(new RecyclerAdapter&lt;Sponsors, SponsorsViewHolder&gt;(sponsorObjectData, Resource.Layout.SponsorsCard)); </code></pre> <p>I replaced Spnsr with sponsorObjectData.</p> <p>I would recommend you reading the following: <a href="https://developer.xamarin.com/guides/android/user_interface/recyclerview/" rel="nofollow">https://developer.xamarin.com/guides/android/user_interface/recyclerview/</a> and <a href="https://www.linkedin.com/pulse/creating-music-app-using-xamarin-sitecore-part-3-jo%C3%A3o-amancio-neto?trk=mp-author-card" rel="nofollow">https://www.linkedin.com/pulse/creating-music-app-using-xamarin-sitecore-part-3-jo%C3%A3o-amancio-neto?trk=mp-author-card</a>.</p>
Correct workflow when using parent NSManagedObjectContext <p>I'm using a chain of <code>NSManagedObjectContext</code> to represent a hierarchy of views and actions that can be rolled back/cancelled. This is one example: Let's say I have the following structure:</p> <ul> <li>Client list (Main NSManagedObjectContext)</li> <li>Client details (DetailContext - Parent = MainContext)</li> <li>Client Groceries (GroceryContext - Parent = DetailContext)</li> <li>Grocery Payment (PaymentContext - Parent = GroceryContext)</li> </ul> <p>This way, I can navigate to the Grocery payment, do changes, and cancel if necessary, same thing for all other levels. Since performing a save will move the changes on level up. So far, this is working as expected.</p> <p>What I want to understand is a good way to do the following:</p> <ul> <li>Open the client on the list;</li> <li>Open the groceries;</li> <li>Open the grocery payment record</li> <li>Add a transaction</li> </ul> <p>The thing is, that this transaction needs to be saved on the backend as well, and saved on the local main context, because no matter what I do on the rest of the workflow, that transaction was made.</p> <p>What I've been doing is that in case of a transaction is made, a series of delegates will be called until the root level which is the parent context of all, and save the transaction. But I'm wondering if there is a better way to do it. Because even though a transaction is done, I might want to cancel some other changes that were made during the way. But all those contexts need to have an updated object of that saved context for the transaction since that is final.</p> <p>Please don't get attached to the actual use case of clients-groceries, this was just to explain the hierarchy level of contexts.</p> <p>Thanks</p>
<p>Using all these nested child contexts is almost certainly the wrong approach. For the most part you only want the one main context while on the main thread, however if you have a whole bunch of changes that only make sense when done and saved together then you can use a temporary child context for that. When you save the child context then immediately save the main context too to get it onto disk. Think of it like a database transaction.</p> <p>If you have changes coming in from a background process you can either create a private child context, or a completely seperate private context straight off the persistent store coordinator - you will have to manually merge changes into the main context in the second case though. Use <code>managedObjectContextDidSaveNotification:</code> for that.</p>
How to catch a PermissionDenied(403) from Django with Ajax? <p>So im trying to handle a GET request with AJAX instead of Django so I can display a simple pop-up/modal with jQuery when a 403 Forbidden (Given by Django) is raised, however im not sure how to continue right now.</p> <p>This is my Javasscript that handles the request:</p> <p>Just gets a button in my html and waits for Click event.</p> <h1>main.js</h1> <pre><code>$(document).ready(function(){ $("#users_page").click(function(e){ e.preventDefault(); $.ajax({ "method": "GET", "url": "/dashby/users/", "beforeSend": function(xhr, settings){ console.log("Before send"); }, "success": function(result){ window.location.href = "/dashby/users/"; }, "error": function(xhr, textStatus, error){ console.log(error); }, }); }); }); </code></pre> <h1>my view.py for this matter</h1> <pre><code>class AllUsersViews(UserPassesTestMixin, View): template_name = 'all_users.html' raise_exception = True # Raise PermissionDenied(403) def test_func(self): #Only superusers can access this view. if self.request.user.is_superuser: return True def get(self, request): context = {'users': User.objects.all()} return render(request, self.template_name, context) </code></pre> <p>So right now if im a superuser i do get redirected to the page I want but I want to be able to basically display a message to the user (A pop-up or a modal) saying that they do not have permission if the PermissionForbidden is raised by Django.</p> <p>Also, I dont want the page to refresh when this happens or that the Chrome Console displays the 403 Forbidden Message.</p> <p>I dont know if it's actually a lot to ask/ if its long but thanks to any advice/tips in advance.</p>
<p>You should be able to see HTTP errors in the <code>error</code> handler:</p> <pre><code>$.ajax({ ... error: function (xhr, ajaxOptions, thrownError) { if(xhr.status==403) { alert(...); } } } </code></pre> <p>You will always see the 403 in the console as that's the HTTP response you are getting from the server.</p> <p>You can simplify the <code>test_func</code> to just:</p> <pre><code>class AllUsersViews(UserPassesTestMixin, View): ... def test_func(self): return self.request.user.is_superuser ... </code></pre>
How to check that fscanf() returns valid string in C? <p>I have a C / fscanf() question. FULL DISCLAIMER: I am CS student, working on an assignment. My code works, but the graders will compile our submissions with using the GCC "all errors and warnings" option:</p> <pre><code>gcc -Wall yourCodeHere.c </code></pre> <p>My code works, but I'm getting a warning which bugs me... and could lead to problems with the grader. My code is simple, it scans each line of a file into a string, then tosses that string to a function:</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;string.h&gt; void printString(char* string){ printf("file line is: \"%s\"\n", string); } int main(int argc, char *argv[]){ char *myFile = argv[1]; FILE *targetFile; targetFile = fopen(myFile, "r"); if (targetFile == NULL) { // some problem with the input file return -1; } else { char* string; while (fscanf(targetFile, "%s\n", string) != EOF){ printString(string); } } fclose(targetFile); return 1; } </code></pre> <p>The warning is:</p> <pre><code>$ gcc -Wall myCode.c myCode.c: In function ‘main’: myCode.c:21:4: warning: ‘string’ may be used uninitialized in this function [-Wmaybe-uninitialized] printString(string); ^ $ </code></pre> <p>I get what the compiler is trying to say: "<em>What if 'string' is not holding valid data?</em>" Its a valid point; I'm kinda assuming that every line of the input file will produce a working string.</p> <p>So: how to check this and get rid of that annoying warning? I note that fscanf() returns the number of items successfully scanned, so I tried this:</p> <pre><code> int num = 1; // initialize to something &gt;0 while (num = (fscanf(targetFile, "%s\n", string) != EOF) &gt; 0){ printString(string); } </code></pre> <p>But that produced <strong><em>two</em></strong> warnings:</p> <pre><code>$ gcc -Wall myCode.c myCode.c: In function ‘main’: myCode.c:21:3: warning: suggest parentheses around assignment used as truth value [-Wparentheses] while (num = (fscanf(targetFile, "%s\n", string) != EOF) &gt; 0){ ^ myCode.c:22:4: warning: ‘string’ may be used uninitialized in this function [-Wmaybe-uninitialized] printString(string); ^ $ </code></pre> <p>Plus, I worry that this would cause the program to stop reading the file too early if fscanf() returned 0 for some valid reason.</p> <p>So... Not certain how to get around this. In Java, I'd simply say "if(string != NULL) ..." and move on. But you can't do that in C. There must be some quick way of checking that fscanf() grabs a valid string before I call the external function.</p> <p>Anyone know a fix?</p> <p>Thanks! -Pete</p> <p>PS - Apologies if this is more a GCC question than a C question. :(</p>
<p><code>string</code> in your code is a pointer rather than an array. There is no memory allocated for <code>fscanf</code> to copy the characters into. Changing it to a character array will work as would <code>string = malloc(X);</code> where X is the number of bytes you want to allocate. Remember that you'll need an extra byte for the '\0' termination of the string. Also remember that you have no idea how big the line of test could be and <code>fscanf</code> will just copy bytes without caring about length, which brings up another issue -- how is <code>fscanf</code> supposed to know to copy an entire line rather than just a word or a character? You should look into that!</p>
Mock Kotlin class in Java unit test <p>I have this Java test with Mockito:</p> <pre><code>public class PersistentNodeDeserializerTests { @Test public void userInfoPersistentNodeDeserializer() { PersistentNode node = mock(PersistentNode.class); when(node.stringChild("username")).thenReturn("cliff12"); //more stuff } } </code></pre> <p><strong>PersistentNode</strong> is a Kotlin class:</p> <pre><code>open class PersistentNode(private val path: PersistentNodePath, val content: Any) { val stringPath: String get() = path.get() val key: String get() { val parts = stringPath.split("/"); return parts[parts.size - 1]; } val mapContent: Map&lt;String, Any&gt; get() { return content as HashMap&lt;String, Any&gt; } fun stringChild(child: String): String { return mapContent.get(child) as String } } </code></pre> <p>I get this error:</p> <blockquote> <p>kotlin.TypeCastException: null cannot be cast to non-null type java.util.HashMap</p> </blockquote> <p>How can I mock the property <code>stringChild</code> properly?</p>
<p>this library may solve your issue <a href="https://github.com/nhaarman/mockito-kotlin" rel="nofollow">https://github.com/nhaarman/mockito-kotlin</a></p> <p>EDIT: sorry, didn't realize you were using a Java test. If it's an option, try writing your test in kotlin too</p>
Pick file from Custom gallery of Audio and Video files <p>I have created a <code>Gallery Activity</code> which contains list of audio and video files located on SD Card. I have another activity through which I want to pick files from <code>Gallery Activity</code> using <code>Intent</code>. I have added following <code>intent-filter</code> to manifest:</p> <pre><code>&lt;activity android:name=".Activities.GalleryActivity" android:icon="@drawable/gallery" android:label="@string/gallery" android:parentActivityName=".Activities.MainActivity"&gt; &lt;intent-filter &gt; &lt;action android:name="android.intent.action.PICK" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;data android:scheme="file" /&gt; &lt;/intent-filter&gt; &lt;intent-filter &gt; &lt;action android:name="android.intent.action.GET_CONTENT" /&gt; &lt;category android:name="android.intent.category.OPENABLE" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;data android:mimeType="audio/*" /&gt; &lt;data android:mimeType="video/*" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>Here is how I have created <code>Intent</code> to pick file:</p> <pre><code>Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); startActivityForResult(intent, ATTACH_FILES); </code></pre> <p><strong>EDITS: Here is item <code>onClickListener</code> of <code>Gallery Activity</code>:</strong></p> <pre><code>viewAdapter.withOnClickListener(new FastAdapter.OnClickListener&lt;GalleryRowContent&gt;() { @Override public boolean onClick(View v, IAdapter&lt;GalleryRowContent&gt; adapter, GalleryRowContent item, int position) { if (adapter.getFastAdapter().getSelections().size() == 0) { if (item.getTag().equals("audio")) { Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); File file = new File(item.getFilePath()); intent.setDataAndType(Uri.fromFile(file), "audio/*"); startActivity(intent); } else if (item.getTag().equals("video")) { Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); File file = new File(item.getFilePath()); intent.setDataAndType(Uri.fromFile(file), "video/*"); startActivity(intent); } } return false; } }); </code></pre> <p>This code shows my app in intent chooser and also opens <code>Gallery Activity</code>, however when I click on any file, it opens the file intead of picking it. Can anyone help me?</p>
<p>To return a result from an activity started by <code>startActivityForResult()</code>, call <code>setResult()</code>, supplying the <code>Intent</code> containing the "result". Usually, this is immediately followed by a call to <code>finish()</code>, so control returns to the activity that had called <code>startActivityForResult()</code>, so it can use the result.</p>
RxSwift PublishSubject is being disposed <p>I bind Button pressed to <code>PublishSubject</code> in a router like so:</p> <pre><code>hambugerButton .rx_tap .bindTo(router.openMenu) .addDisposableTo(disposeBag) </code></pre> <p>In my Router:</p> <pre><code>let openMenu = PublishSubject&lt;Void&gt;() //... openMenu .map { _ in menuNavigationController } .bindTo(mainNavigationController.rx_present()) .addDisposableTo(disposeBag) </code></pre> <p>However, when the controller is being deallocated, the button is sending 'complete' signal. When <code>PublishSubject</code> receives it, it won't react to signals from another controller (which is understandable: it is an <code>Observable</code> guarantee). </p> <p>The only solution I came up with:</p> <pre><code>hambugerButton .rx_tap .subscribeNext { self.router.openMenu.onNext() } .addDisposableTo(disposeBag) </code></pre> <p>Which looks ugly and kinda spoils the idea of a reactive interface. My question is, is there a way to avoid propagation of the <code>Completed</code> event to <code>PublishSubject</code>? Can I make some <code>Observer</code> which will ignore such events?</p>
<p>If the view controller which owns the <code>hamburgerButton</code> is being deallocated, and thus the <code>hamburgerButton</code> is also being deallocated, why wouldn't you want the binding to <code>router.openMenu</code> to also be deallocated? Maybe it's not clear what your view controller hierarchy is from your question.</p> <p>Also, in the first snippet, you shouldn't be making a binding without adding it to a <code>DisposeBag</code> like so:</p> <pre><code>hambugerButton .rx_tap .bindTo(router.openMenu) .addDisposableTo(disposeBag) </code></pre>
Dagger2, providing Retrofit instances with different APIs same time <p>In my project I use Retrofit and trying to use Dagger for injecting dependencies. I also have 2 Retrofit services with different APIs. I need to use 2 different APIs with different baseUrls at the same time. I stucked here, and dont know what to do next.</p> <p>My ApplicationModule:</p> <pre><code>@Module public class ApplicationModule { private String FIRST_API_URL = "https://first-api.com"; private String SECOND_API_URL = "https://second-api.com"; private String mBaseUrl; private Context mContext; public ApplicationModule(Context context) { mContext = context; } @Singleton @Provides GsonConverterFactory provideGsonConverterFactory() { return GsonConverterFactory.create(); } @Singleton @Provides @Named("ok-1") OkHttpClient provideOkHttpClient1() { return new OkHttpClient.Builder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .build(); } @Singleton @Provides @Named("ok-2") OkHttpClient provideOkHttpClient2() { return new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build(); } @Singleton @Provides RxJavaCallAdapterFactory provideRxJavaCallAdapterFactory() { return RxJavaCallAdapterFactory.create(); } @Singleton @Provides @FirstApi Retrofit provideRetrofit(@Named("ok-1") OkHttpClient client, GsonConverterFactory converterFactory, RxJavaCallAdapterFactory adapterFactory) { return new Retrofit.Builder() .baseUrl(FIRST_API_URL) .addConverterFactory(converterFactory) .addCallAdapterFactory(adapterFactory) .client(client) .build(); } @Singleton @Provides @SecondApi Retrofit provideRetrofit2(@Named("ok-1") OkHttpClient client, GsonConverterFactory converterFactory, RxJavaCallAdapterFactory adapterFactory) { return new Retrofit.Builder() .baseUrl(SECOND_API_URL) .addConverterFactory(converterFactory) .addCallAdapterFactory(adapterFactory) .client(client) .build(); } @Provides @Singleton Context provideContext() { return mContext; } } </code></pre> <p>My Application:</p> <pre><code>public class MyApplication extends Application { private ApplicationComponent mApplicationComponent; @Override public void onCreate() { super.onCreate(); initializeApplicationComponent(); } private void initializeApplicationComponent() { mApplicationComponent = DaggerApplicationComponent .builder() .applicationModule(new ApplicationModule(this, Constant.BASE_URL)) // I think here needs to do something to use different URLs .build(); } public ApplicationComponent getApplicationComponent() { return mApplicationComponent; } @Override public void onTerminate() { super.onTerminate(); } } </code></pre> <p>This is how I am resolving dependencies in My fragment.</p> <pre><code> protected void resolveDependency() { DaggerSerialComponent.builder() .applicationComponent(getApplicationComponent()) .contactModule(new ContactModule(this)) .build().inject(this); } </code></pre> <p>The problem is that I need to do injection with 2 APIs in Fragment, to obtain data from these APIs.</p> <p><strong>UPDATED:</strong> I have created annotations:</p> <pre><code>@Qualifier @Retention(RUNTIME) public @interface FirstApi{} @Qualifier @Retention(RUNTIME) public @interface SecondApi{} </code></pre> <p>My Contact Module:</p> <pre><code>@Module public class ContactModule { private ContactView mContactView; public ContactModule(ContactView contactView) { mContactView = contactView; } @PerActivity @Provides FirstContactService provideFirstContactService(@FirstApi Retrofit retrofit) { return retrofit.create(FirstContactService.class); } @PerActivity @Provides SecondContactService provideSecondContactService(@SecondApi Retrofit retrofit) { return retrofit.create(SecondContactService.class); } @PerActivity @Provides ContactView provideContactView() { return mContactView; } } </code></pre> <p>I always get error "retrofit2.retrofit cannot be provided without and @Provides or @Produces-annotated method"</p> <p>ApplicationComponent</p> <pre><code>@Singleton @Component(modules = ApplicationModule.class) public interface ApplicationComponent { Retrofit exposeRetrofit(); Context exposeContext(); } </code></pre>
<p>You just use the <code>@Inject</code> annotation along with the <code>@Named()</code> annotation, like so:</p> <pre><code>@Inject @Named("provideRetrofit") Retrofit mRetrofit; @Inject @Named("provideRetrofit2") Retrofit mRetrofit2; </code></pre> <p>Or you could even inject the Retrofit services directly:</p> <pre><code>@Provides @Singleton public CustomService provideCustomService(@Named("provideRetrofit") Retrofit retrofit) { return retrofit.create(CustomService.class); } </code></pre>
parse csv using lua script <p>I have a csv file that has data like this: </p> <pre><code>+12345678901,08:00:00,12:00:00,1111100,35703,test.domain.net +12345678901,,,0000000,212,test.domain.net </code></pre> <p>I'm trying to write lua code that will loop through each line, and create an array of values like this: </p> <pre><code>local mylist = {} for line in io.lines("data/dd.csv") do local id, start, finish, dow, int, domain = line:match("(+%d+),(%d*:*),(%d*:*),(%d*),(%d*),(%a*.*)") mylist[#mylist + 1] = { id = id, start = start, finish = finish, dow = dow, int = int, domain = domain} print(mylist[#mylist]['id']) end </code></pre> <p>The problem is that when the code hits a line that has empty values for start and finish, the regex fails and all fields are nil.</p> <p>I thought using the * meant 0 or more... I can't seem to find my error / typo. </p> <p>Thanks. </p>
<p>It seems that you just need to group the digits and <code>:</code> inside a <code>[...]</code>:</p> <pre><code>match("(%+%d+),([%d:]*),([%d:]*),(%d*),(%d*),(.*)") ^ ^^^^^^ ^^^^^^ </code></pre> <p>Now, the <code>[%d:]*</code> matches zero or more digits or <code>:</code> symbols. Your pattern did not find the match because <code>%d*:*</code> matched 0+ digits followed with 0+ <code>:</code> symbols, and you had more than 1 such sequence.</p> <p>Also, you need to escape the first <code>+</code> to make sure it matches a literal <code>+</code>.</p> <p>See <a href="http://ideone.com/oc1G9N" rel="nofollow">online Lua demo</a></p>
Join with <= in the On clause in Google bigquery <p>I want to execute a query with <code>join</code> in Google <code>bigquery</code> that has '&lt;=' instead of '=' in it's on clause:</p> <pre><code>select s.count_value as count_value,s.total as total,sum(p.total) as accumulated from stats s join stats p on p.rn &lt;=s.rn group by count_value,total,s.rn </code></pre> <p>When I run this query, I receive an error message saying:</p> <blockquote> <p>Error: ON clause must be AND of = comparisons of one field name from each table, with all field names prefixed with table name.</p> </blockquote> <p>Any idea how I can implement this query?</p>
<p>You should enable Standard SQL to do such JOINs<br> See <a href="https://cloud.google.com/bigquery/sql-reference/enabling-standard-sql" rel="nofollow">Enabling Standard SQL</a> </p> <p>in CLI - just add the --use_legacy_sql=false flag to your command line statement.</p>
How to calculate how many bacteria in each group are resistant to an antibiotic <p>I am attempting to count instances of resistance to 1 or 1+ antibiotics under certain conditions. Here is an example of what what my spreadsheet looks like:</p> <p><a href="http://i.stack.imgur.com/AXnLg.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/AXnLg.jpg" alt="enter image description here"></a></p> <p>For each drug "1" indicates resistance and "0" indicates sensitivity. </p> <p>If I wanted to determine the number of bacteria in Group A that are resistant to only one antibiotic how would I do this? Or if I wanted to find how many bacteria in Group A are resistant to 1 or more antibiotics? </p> <p>I've been struggling with this one for awhile so if anyone could point me in the right direction I would sure appreciate it. </p> <p>Ideally my output would look like this </p> <p><img src="http://i.stack.imgur.com/BO9wF.png" alt="enter image description here"></p>
<p>Create a new column for "Resistance Count" and use <code>=COUNTIF(B2:D2,"&gt;=1")</code> for cell E2 and fill down. Then you can filter the table by Type or Resistance Count. Use <code>SUBTOTAL</code> to count the filtered rows.</p>
What is the difference between // and .// in XPath? <p>When I execute these XPath expression on Chrome Developer Tools' console over google.com, I got the same results</p> <ul> <li><p><code>$x("(.//*[@id='gs_lc0'])")</code></p></li> <li><p><code>$x("(//*[@id='gs_lc0'])")</code></p></li> </ul> <p>What is the usage of dot in XPath?</p>
<p>In XPath, <code>//</code> and <code>.//</code> are both syntactic abbreviations:</p> <ul> <li><code>//</code> is short for <code>/descendant-or-self::node()/</code></li> <li><code>.//</code> is short for <code>self::node()/descendant-or-self::node()/</code></li> </ul> <p>The <code>descendant-or-self</code> axis contains the context node and all descendents of the context node. <strong>So the difference between <code>//</code> and <code>.//</code> is reduces to a difference in context nodes.</strong></p> <p>For <code>//</code>, the context node is the root node; <code>//</code> is an <em><a href="https://www.w3.org/TR/xpath/#NT-AbsoluteLocationPath" rel="nofollow">absolute location path</a></em>.</p> <p>For <code>.//</code>, the context node depends upon the context; <code>.//</code> is a <a href="https://www.w3.org/TR/xpath/#NT-RelativeLocationPath" rel="nofollow">relative location path</a>. At the top-level evaluation in Google Developer Tools console, the context node is the root node, so you'll see identical results.</p> <p><strong>In short:</strong></p> <ul> <li>Use <code>//</code> when you wish to select nodes from the entire document.</li> <li>Use <code>.//</code> when you wish to select nodes only beneath the context node.</li> </ul>
Component does not get updated after calling `this.forceUpdate();` <p>I am using <a href="https://facebook.github.io/react-native/docs/direct-manipulation.html" rel="nofollow">direct manipulation</a> to change the color of a view, every time a specific event occurs.</p> <p>My render function:</p> <pre><code> render() { return ( &lt;View&gt; &lt;View ref={component =&gt; this._view = component} style={{width: 50, height: 50}} /&gt; &lt;/View&gt; ); </code></pre> <p>My update function that is called every time a specific event occurs:</p> <pre><code> onSlideChangeHandle(index) { this._view.backgroundColor = 'red' this._view.forceUpdate() } </code></pre> <p>Do I need to do something more to force the component to change the color? The method is called, and the property is updated. Unfortunately, the UI is not updated calling the force update. Do I miss something? I know I should use the state to update the components, but for this specific case I really need direct manipulation.</p>
<p>I found the issue. I need to update the background color using the <code>setNativeProps</code>.</p> <pre><code>onSlideChangeHandle(index) { this._view.setNativeProps({ style: { backgroundColor: 'red' } }); } </code></pre>
AngularJS/JSON: Refer to array member by value instead of index? <p>I have JSON data in the format of:</p> <pre><code>[ { "name": "partnerCodePrefix", "val": "12345", "inherit": true }, { "name": "partnerCode", "val": "AAAAAnnnnnnnnnnnnnnn", "inherit": false } ] </code></pre> <p>Currently, I am accessing this data in my UI with array index numbers, like:</p> <pre><code> &lt;tr class="inherited"&gt; &lt;td&gt; &lt;label&gt;Partner Code Prefix&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="checkbox" name="partnerCodePrefixInherit" id="" ng-model="mob.mobData[1].inherit"&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="text" ng-model="mob.mobData[1].val" ng-disabled="mob.mobData[1].inherit"&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>So, in this example I get the <code>val</code> of <code>partnerCodePrefix</code> with</p> <pre><code>ng-model="mob.mobData[1].val" </code></pre> <p>However, I would rather get the <code>val</code> with the array member's <code>name</code> value rather than its index, so I can more easily re-order rows if needed.</p> <p>Something like: </p> <pre><code> ng-model="mob.mobData['name==partnerCodePrefix'].val" </code></pre> <p>Is there any way to do this? What's the correct syntax?</p>
<p>I think that you can have a function that takes the value has the parameter and returns the index of the array when the name is equal to the parameter like </p> <p>mob.mobData[ returnIndex(str)].Val</p>
Stream Lining a long code <p>I have below codes running through multiple command buttons. Just wanted to know if there is any method to stream line. Each button works in a flow having certain characteristics. I am sure there are ways to cutoff excess junk. </p> <pre><code>Private Sub CommandButton1_Click() ActiveSheet.Unprotect "bir@2016" Range("A17").Select ActiveCell.FormulaR1C1 = "Research" Sheets("Questionnaire").Select Sheets("Questionnaire").Range("A1").Select Sheets("Analyst Score").Select Sheets("Questionnaire").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub CommandButton10_Click() ActiveWorkbook.Unprotect "bir@2016" Sheets("Investigation Comments Input").Visible = False Sheets("Analyst Score").Visible = False Sheets("Questionnaire").Select ActiveWorkbook.Protect "bir@2016" End Sub Private Sub CommandButton11_Click() ActiveWorkbook.Unprotect "bir@2016" Sheets("Report Template").Visible = True Sheets("Report Template").Select Sheets("Report Template").Range("B4").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub Commandbutton2_Click() ActiveSheet.Unprotect "bir@2016" Range("A17").Select ActiveCell.FormulaR1C1 = "Quality Check" Sheets("Questionnaire").Select Sheets("Questionnaire").Range("A1").Select Sheets("Analyst Score").Select Sheets("Questionnaire").Select Sheets("Questionnaire").Range("W1").Select ActiveCell.Value = Time Sheets("Questionnaire").Range("A1").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub CommandButton3_Click() ActiveSheet.Unprotect "bir@2016" Range("A17,B17,B1,C1,B3:B5,B7,H19:I127,O19:O127,K19:K127,L19:L127").Select Range("H19").Activate Selection.ClearContents Sheets("Questionnaire").Select Sheets("Questionnaire").Range("W1:X1,Z1:AE1").Select ActiveSheet.Unprotect "bir@2016" Selection.ClearContents Sheets("Analyst Score").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub CommandButton4_Click() ActiveSheet.Unprotect "bir@2016" ActiveSheet.Unprotect "bir@2016" Range("I19:I127").Select Range("I19").Activate Selection.ClearContents Range("N7").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub CommandButton5_Click() ActiveSheet.Unprotect "bir@2016" ActiveWindow.ScrollRow = 9 Range("A19").Select ActiveWindow.FreezePanes = True ActiveSheet.Protect "bir@2016" End Sub Private Sub CommandButton6_Click() ActiveSheet.Unprotect "bir@2016" ActiveWindow.FreezePanes = False ActiveWindow.SmallScroll Down:=-33 ActiveSheet.Protect "bir@2016" End Sub Private Sub CommandButton7_Click() ActiveSheet.Unprotect "bir@2016" ActiveSheet.Unprotect "bir@2016" Range("H19:H127").Select Range("H19").Activate Selection.ClearContents Range("N7").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub CommandButton8_Click() ActiveSheet.Unprotect "bir@2016" Rows("17:127").Select Selection.EntireRow.Hidden = True Range("H5").Select Range("Z:Z,AA:AA,AB:AB").Select Range("AB9").Activate Selection.EntireColumn.Hidden = True Range("M14").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub CommandButton9_Click() ActiveSheet.Unprotect "bir@2016" Rows("17:127").Select Selection.EntireRow.Hidden = False Range("H5").Select Range("Z:Z,AA:AA,AB:AB").Select Range("AB9").Activate Selection.EntireColumn.Hidden = False Range("M14").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub DEWS_Click() ActiveSheet.Unprotect "bir@2016" Range("A17").Select ActiveCell.FormulaR1C1 = "Dews" Sheets("Questionnaire").Select Sheets("Questionnaire").Range("W1").Select ActiveSheet.Unprotect "bir@2016" ActiveCell.Value = Time Range("W2").Value = Date Sheets("Questionnaire").Range("A1").Select ActiveSheet.Protect "bir@2016" End Sub Private Sub Worksheet_Calculate() If Range("E5").Value &lt; 1 Then Me.Shapes("CommandButton2").Visible = False If Range("E5").Value &gt; 1 Then Me.Shapes("CommandButton2").Visible = True End Sub </code></pre>
<p>There a lot of ways to shorten your code:</p> <p>1) Start off with Kyle's comment and reduce your select statements.</p> <p>2) If you are looking to <em>visually</em> unclutter your code, make better use of white space.</p> <p>3) In commandbutton4, commandbutton7, you unprotect the same sheet twice. </p> <p>Other than the above, there is not much more to do if you need every single one of these buttons. Are you sure you can't combine buttons? </p>
efficiently replace values from a column to another column Pandas DataFrame <p>I have a Pandas DataFrame like the following one: </p> <pre><code> col1 col2 col3 1 0.2 0.3 0.3 2 0.2 0.3 0.3 3 0 0.4 0.4 4 0 0 0.3 5 0 0 0 6 0.1 0.4 0.4 </code></pre> <p>I want to replace the <code>col1</code> values with the values in the second column (<code>col2</code>) only if <code>col1</code> values are equal to 0, and after (for the zero values remaining), do it again but with the third column (<code>col3</code>). The Desired Result is the next one:</p> <pre><code> col1 col2 col3 1 0.2 0.3 0.3 2 0.2 0.3 0.3 3 0.4 0.4 0.4 4 0.3 0 0.3 5 0 0 0 6 0.1 0.4 0.4 </code></pre> <p>I did it using the <code>pd.replace</code> function, but it seems too slow.. I think must be a faster way to accomplish that. </p> <pre><code>df.col1.replace(0,df.col2,inplace=True) df.col1.replace(0,df.col3,inplace=True) </code></pre> <p>is there a faster way to do that?, using some other function instead of the <code>pd.replace</code> function?, maybe slicing the <code>df.col1</code> ?</p> <p>PS1. Additional info: the original goal of the problem is to replace the zero values (in <code>col1</code>) with the statistic mode of some groups of ids. That is why I have <code>col2</code>(best mode, first option of replacement) and <code>col3</code>(last mode, still functional but not so desirable as <code>col2</code>). </p>
<p>Using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> is faster. Using a similar pattern as you used with <code>replace</code>:</p> <pre><code>df['col1'] = np.where(df['col1'] == 0, df['col2'], df['col1']) df['col1'] = np.where(df['col1'] == 0, df['col3'], df['col1']) </code></pre> <p>However, using a nested <code>np.where</code> is slightly faster:</p> <pre><code>df['col1'] = np.where(df['col1'] == 0, np.where(df['col2'] == 0, df['col3'], df['col2']), df['col1']) </code></pre> <p><strong>Timings</strong></p> <p>Using the following setup to produce a larger sample DataFrame and timing functions:</p> <pre><code>df = pd.concat([df]*10**4, ignore_index=True) def root_nested(df): df['col1'] = np.where(df['col1'] == 0, np.where(df['col2'] == 0, df['col3'], df['col2']), df['col1']) return df def root_split(df): df['col1'] = np.where(df['col1'] == 0, df['col2'], df['col1']) df['col1'] = np.where(df['col1'] == 0, df['col3'], df['col1']) return df def pir2(df): df['col1'] = df.where(df.ne(0), np.nan).bfill(axis=1).col1.fillna(0) return df def pir2_2(df): slc = (df.values != 0).argmax(axis=1) return df.values[np.arange(slc.shape[0]), slc] def andrew(df): df.col1[df.col1 == 0] = df.col2 df.col1[df.col1 == 0] = df.col3 return df def pablo(df): df['col1'] = df['col1'].replace(0,df['col2']) df['col1'] = df['col1'].replace(0,df['col3']) return df </code></pre> <p>I get the following timings:</p> <pre><code>%timeit root_nested(df.copy()) 100 loops, best of 3: 2.25 ms per loop %timeit root_split(df.copy()) 100 loops, best of 3: 2.62 ms per loop %timeit pir2(df.copy()) 100 loops, best of 3: 6.25 ms per loop %timeit pir2_2(df.copy()) 1 loop, best of 3: 2.4 ms per loop %timeit andrew(df.copy()) 100 loops, best of 3: 8.55 ms per loop </code></pre> <p>I tried timing your method, but it's been running for multiple minutes without completing. As a comparison, timing your method on just the 6 row example DataFrame (not the much larger one tested above) took 12.8 ms.</p>
How to embed CDATA in Mulesoft <p>I'm trying to embed a literal CDATA value in a Mulesoft flow and cannot figure out how to do so.</p> <p>My desired output (in an HTTP request body) is:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;soap:Body&gt; &lt;query xmlns="http://autotask.net/ATWS/v1_5/"&gt; &lt;sXML&gt; &lt;![CDATA[&lt;queryxml&gt;&lt;entity&gt;ticket&lt;/entity&gt;&lt;query&gt;&lt;condition&gt;&lt;field&gt;id&lt;expression op="equals"&gt;12345&lt;/expression&gt;&lt;/field&gt;&lt;/condition&gt;&lt;/query&gt;&lt;/queryxml&gt;]]&gt; &lt;/sXML&gt; &lt;/query&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>My Dataweave transformation looks as follows:</p> <pre><code>%dw 1.0 %output application/xml %namespace soap http://schemas.xmlsoap.org/soap/envelope --- { soap#Envelope @(version: "1.0") : { soap#Header: {}, soap#Body: { query: { sXML: "&lt;queryxml&gt;&lt;entity&gt;ticket&lt;/entity&gt;&lt;query&gt;&lt;condition&gt;&lt;field&gt;id&lt;expression op=\"equals\"&gt;12345&lt;/expression&gt;&lt;/field&gt;&lt;/condition&gt;&lt;/query&gt;&lt;/queryxml&gt;" } } } } </code></pre> <p>But when I send this request to requestb.in (to inspect the contents), I can see it's coming through like this (focus on the sXML entity):</p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8'?&gt; &lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope" version="1.0"&gt; &lt;soap:Header/&gt; &lt;soap:Body&gt; &lt;query&gt; &lt;sXML&gt;&amp;lt;queryxml&gt;&amp;lt;entity&gt;ticket&amp;lt;/entity&gt;&amp;lt;query&gt;&amp;lt;condition&gt;&amp;lt;field&gt;id&amp;lt;expression op="equals"&gt;12345&amp;lt;/expression&gt;&amp;lt;/field&gt;&amp;lt;/condition&gt;&amp;lt;/query&gt;&amp;lt;/queryxml&gt;&lt;/sXML&gt; &lt;/query&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>How can I get a literal CDATA value in there via dataweave / MEL?</p> <p>Thank you.</p>
<p>I would try:</p> <pre><code>sXML: "&lt;queryxml&gt; .... &lt;/queryxml&gt;" as :cdata </code></pre> <p>See <a href="https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-formats#custom-types-2" rel="nofollow">https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-formats#custom-types-2</a> for more information.</p>
SAS PROC SQL - issue with Left join on two character variables <pre><code> DataSet: Test1 Name Type Length Format Informat RowID Numeric 8 6. 6. COL2 Character 6 $6. $6. COL3 Numeric 8 NUMERIC12. NUMERIC12. DATE Numeric 8 11. 11. TIME Character 8 $CHAR8. $CHAR8. Amount Numeric 8 DataSet: Test2 Name Type Length Format Informat RowID Numeric 8 9. 9. COL2 Character 32 $32. $32. COL3 Date 8 DATETIME27.6 DATETIME27.6 COL4 Character 17 $17. $17. TIME Character 8 $CHAR8. $CHAR8. COL5 Numeric 8 NUMERIC12. NUMERIC12. AMOUNT Numeric 8 </code></pre> <p>Sample Data </p> <pre><code>Test1 RowID COL2 COL3 DATE TIME AMOUNT 3330 123456 123 20110523 14.14.50 2.00 3330 334567 123 20110523 19.13.34 2.00 3330 889789 123 20110523 20.01.11 2.00 3330 45678 1643 20110523 06.53.05 6.00 TEST2 RowID COL2 COL3 COL4 TIME COL5 Amount 3330 0010181002233611096xyBC3TLnDkVB7 23MAY2011:19:14:50.000000 20110523 14:14:50 14:14:50 123 2.00 3330 0010181005005029491mnopqrbT2cySA 24MAY2011:00:13:34.000000 20110523 19:13:34 19:13:34 123 2.00 3330 001018100222213220332ghijkl63BR1 23MAY2011:11:53:05.000000 20110523 06:53:05 06:53:05 1643 6.00 3330 00101810021738472682abcdef7vUcte 23MAY2011:13:30:03.000000 20110523 08:30:03 06:53:05 5575 1.00 </code></pre> <p>I want to left join Test1 with Test2 on Columns Test1.COL3=Test2.COL5 and Test1.Time=Test2.TIME with the desired output to look like</p> <pre><code> Final RowID COL2 COL3 DATE TIME AMOUNT RowID COL2 COL3 COL4 TIME COL5 Amount 3330 123456 123 20110523 14.14.50 2.00 3330 0010181002233611096xyBC3TLnDkVB7 23MAY2011:19:14:50.000000 20110523 14:14:50 14:14:50 123 2.00 3330 334567 123 20110523 19.13.34 2.00 3330 0010181005005029491mnopqrbT2cySA 24MAY2011:00:13:34.000000 20110523 19:13:34 19:13:34 123 2.00 3330 889789 123 20110523 20.01.11 2.00 . . . . . . . 3330 45678 1643 20110523 06.53.05 6.00 3330 001018100222213220332ghijkl63BR1 23MAY2011:11:53:05.000000 20110523 06:53:05 06:53:05 1643 6.00 </code></pre> <p>I'm running the below code is SAS</p> <pre><code> proc sql; create table final as select * from ( (select * from Test1) A left join (select * from Test2) B on Test1.COL3=Test2.COL5 and Test1.Time=Test2.TIME ) quit; </code></pre> <p>and Im not getting the desired output even though TIME column in both the datasets are of same length, Format and Informat</p> <p>I'm getting the results as</p> <pre><code> Final RowID COL2 COL3 DATE TIME AMOUNT RowID COL2 COL3 COL4 TIME COL5 Amount 3330 123456 123 20110523 14.14.50 2.00 . . . . . . . 3330 334567 123 20110523 19.13.34 2.00 . . . . . . . 3330 889789 123 20110523 20.01.11 2.00 . . . . . . . 3330 45678 1643 20110523 06.53.05 6.00 . . . . . . . I do not understand what is wrong. </code></pre>
<p><code>14.14.50</code> ne <code>14:14:50</code></p> <p>Fix your formats, or use INPUT to make them both a number.</p>
ksoap2 stringArray for php Request <p>How to make such a request?</p> <pre><code>&lt;SOAP-ENV:Body&gt; &lt;ns1:CurrencySyncDelete&gt; &lt;Row xsi:type="ns2:Map"&gt; &lt;item&gt; &lt;key xsi:type="xsd:string"&gt;ID&lt;/key&gt; &lt;value xsi:type="xsd:int"&gt;999&lt;/value&gt; &lt;/item&gt; &lt;/Row&gt; &lt;/ns1:CurrencySyncDelete&gt; &lt;/SOAP-ENV:Body&gt; </code></pre>
<p>I decided the problem with the help of marshaling <a href="http://read.pudn.com/downloads143/sourcecode/mobile/j2me/625948/branches/2_1_0_AttributePatch_1473145/ksoap2/ksoap2/src/org/ksoap2/serialization/MarshalHashtable.java__.htm" rel="nofollow">http://read.pudn.com/downloads143/sourcecode/mobile/j2me/625948/branches/2_1_0_AttributePatch_1473145/ksoap2/ksoap2/src/org/ksoap2/serialization/MarshalHashtable.java__.htm</a></p>
Website layout for mobile looks fine on emulator but not on actual mobile device <p>I just started learning html/css/javascript and decided to throw together a website for practice. I now know that a lot of the approaches I took in creating this website are seen as bad practice, which is why I will not continue to do them. What i'm having issues with is getting the mobile layout I see on Firefox's mobile emulator to appear as is on an actual mobile device. Any advice on how to fix this issue? </p> <p>Thanks in advance!</p> <p><a href="https://www.dropbox.com/sh/d6emlme37x08wge/AAA-ot9OeRGSYauRomMGHd6Ia?dl=0" rel="nofollow"> Website Files </a></p>
<p>Try adding this meta tag to your pages, in the &lt;head&gt; element:</p> <pre><code>&lt;meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" /&gt; </code></pre> <p>I had this issue with Bootstrap awhile ago and then found this nifty answer online. I also would recommend using something like Bootstrap or Materialize.</p>
Can't find Google Play Services in components in Xamarin Android project <p>I am trying to add the Google Play Services component to my Xamarin application because I need to integrate google maps api into the application. When I try to search Google play services in components I can't find Google Play Services. I see other components such as Google Play services-ads or Google Play Services- App Indexing but no Google Play Services. </p> <p>I installed the Google play services client in the sdk manager:</p> <p><a href="http://i.stack.imgur.com/3j3lp.png" rel="nofollow"><img src="http://i.stack.imgur.com/3j3lp.png" alt="enter image description here"></a></p> <p>And the minimum api level that the app is targeting is level 19. Still I can't find Google Play Services. Here is a screenshot of the all the results: <a href="http://i.stack.imgur.com/Rkn1F.png" rel="nofollow"><img src="http://i.stack.imgur.com/Rkn1F.png" alt="enter image description here"></a></p> <p><strong>Edit</strong></p> <p><a href="https://forums.xamarin.com/discussion/54499/google-play-services-v27-migration" rel="nofollow">https://forums.xamarin.com/discussion/54499/google-play-services-v27-migration</a></p> <p>According to the above website google play services-All does not exist anymore and now their are individual packages. So now I have to install Google Play Services-Maps.</p>
<p>You can use NuGet to download <a href="https://www.nuget.org/packages/Xamarin.GooglePlayServices.Maps/" rel="nofollow">Google Play Services Maps</a> to your project.</p> <p><a href="https://www.nuget.org/packages/Xamarin.GooglePlayServices.Maps/" rel="nofollow">https://www.nuget.org/packages/Xamarin.GooglePlayServices.Maps/</a></p> <p>Or you can download the component from the <a href="https://components.xamarin.com/view/googleplayservices-maps" rel="nofollow">component store</a></p> <p><a href="https://components.xamarin.com/view/googleplayservices-maps" rel="nofollow">https://components.xamarin.com/view/googleplayservices-maps</a></p> <p>The Google Play Services library was too large at one point and google decided to separate the concerns into a smaller packages for many reasons such as hitting 64K reference limit too fast even though you only used a small subset of the APIs for your application.</p> <p>You can read an overview guide on this topic here:</p> <p><a href="https://developers.google.com/android/guides/overview" rel="nofollow">https://developers.google.com/android/guides/overview</a></p>
Where is year at 2:54 the speaker is referring to? <p>In <a href="https://www.youtube.com/watch?v=k0Uv7jX--W4" rel="nofollow">this tutorial</a>, at <code>2:54</code> minute - the speaker is saying:</p> <blockquote> <p>Now, in the last example with IPO pub year, we were using an expression that resolves to a value for a scalar. In that case, it's a year. In this case our scalar as we saw earlier resolves to a document.</p> </blockquote> <p>but we don't see <strong>year</strong> anywhere in the query? Where is year at 2:54 the speaker is referring to?</p>
<p>You should be able solve your question yourself:</p> <blockquote> <p>Now, in the <strong>last example</strong> with IPO pub year, we were using an expression that resolves to a value for a scalar. In that case, it's a year. In this case our scalar as we saw earlier resolves to a document.</p> </blockquote> <p>The lecturer is referring (probably) to the <code>pub_year</code> field used of the <strong>last example</strong> (which is no longer on the screen at this point) and contrasting the use there -- which resulted in a scalar value -- with the use in the case shown at this point, which results in a document.</p>
How can I modify a javascript event in a PDF file programmatically? <p>My PDF file has an event attached to a button. I need to be able to modify that event programmatically. I tried this way using iTextSharp, but it didn't change the javascript in the new file:</p> <p>var pdfReader = new PdfReader(originalPdfDocumentPath);</p> <p>pdfReader.RemoveUsageRights();</p> <p>var pdfStamper = new PdfStamper(pdfReader, new FileStream(newPdfDocumentPath, FileMode.Create, FileAccess.Write, FileShare.None), '\0', true);</p> <p>var originalXml = pdfReader.AcroFields.Xfa.DomDocument.InnerXml;</p> <p>var newXml = originalXml.Replace("Table2.Row1.instanceManager.removeInstance(1)", "Table2._Row1.removeInstance(this.parent.parent.index)");</p> <p>pdfStamper.AcroFields.Xfa.DomDocument.InnerXml = newXml; // Unfortunately, this line does nothing.</p> <p>pdfStamper.Close();</p> <p>pdfReader.Close();</p> <p>Any help would be greatly appreciated.</p>
<p>I found that it works if, instead of changing the XML directly, I change the DomDocument and mark the XFA as changed. Below is the corrected code:</p> <pre><code>var pdfReader = new PdfReader(originalPdfDocumentPath); pdfReader.RemoveUsageRights(); var pdfStamper = new PdfStamper(pdfReader, new FileStream(newPdfDocumentPath, FileMode.Create, FileAccess.Write, FileShare.None), '\0', true); var originalXml = pdfReader.AcroFields.Xfa.DomDocument.InnerXml; var newXml = originalXml.Replace("Table2.Row1.instanceManager.removeInstance(1)", "Table2._Row1.removeInstance(this.parent.parent.index)"); /* New Code */ var doc = new XmlDocument(); doc.LoadXml(newXml); pdfStamper.AcroFields.Xfa.DomDocument = doc; pdfStamper.AcroFields.Xfa.Changed = true; /* End of New Code */ pdfStamper.Close(); pdfReader.Close(); </code></pre> <p>I should note that, even though this code changes the javascript in the PDF file, it also disables the extended features in Adobe Acrobat Reader. You can find more information regarding this here:</p> <p><a href="http://developers.itextpdf.com/question/why-do-i-get-error-saying-use-extended-features-no-longer-available" rel="nofollow">http://developers.itextpdf.com/question/why-do-i-get-error-saying-use-extended-features-no-longer-available</a></p> <blockquote> <p>"The problem is related to whether or not your document is Reader Enabled. Reader-enabling can only be done using Adobe software. It is a process that requires a digital signature using a private key from Adobe. When a valid signature is present, specific functionality (as defined in the usage rights when signing) is unlocked in Adobe Reader. You change the content of such a PDF, hence you break the signature."</p> </blockquote>
Oracle SQL Developer how to copy multiple procedures from one server to another <p><a href="http://i.stack.imgur.com/7QjSI.png" rel="nofollow"><img src="http://i.stack.imgur.com/7QjSI.png" alt="enter image description here"></a>What is the best way to copy procedures from one server to another I dont want to copy and paste each one and run which I am doing currently. I have a staging database and a target database. I have procedures that are in target that are not in staging how do I go about this? I've researched about merge but that only works for tables... I think?</p>
<p>'Best' - no way to answer without knowing more about what you want.</p> <p>You can drag and drop a procedure or procedures from one database connection to another and we'll copy them over. V4.1.5 or v4.2.</p> <p>In all other versions you can use Tools > Database > Copy and select your PL/SQL and target database and we'll copy them over.</p> <p>Def don't copy and paste.</p> <p>What you should probably really do is have a working directory of all your source code, and then you could load them up in whatever database you want by calling them @ style with a SQL*Plus script against the target database.</p> <p>SQL Developer will run the SQL*Plus scripts for you via F5 in a SQL Worksheet. </p>
JDBC - varbinary(max) out parameter of stored procedure is truncated to 8000 bytes <p>I'm using Spring Data JPA 1.10.2 with jTds 1.3.1 to call a stored procedure. </p> <p>The stored procedure has an out parameter, <code>@data</code> of type varbinary(max). <code>@data</code> contains about ~10,000 bytes. </p> <p>Here's the stored procedure signature:</p> <pre><code>ALTER procedure [User].[pTest] @data varbinary(max) out ,@name nvarchar(max) = null ,@date datetime as begin . . . </code></pre> <p>My entity class is:</p> <pre><code>@Entity @NamedStoredProcedureQuery(name = "User.getUser", procedureName = "User.pTest", parameters = { @StoredProcedureParameter(mode = ParameterMode.OUT, name = "data", type = byte[].class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "name", type = String.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "date", type = Date.class) }) @Data //lombok public class User { // serves no purpose other than to meet // JPA requirement @Id private Long id; } </code></pre> <p>The repository code is</p> <pre><code>public interface UserRepository extends Repository&lt;User, Long&gt; { @Procedure("User.pTest") byte[] getUserSession(@Param("name") String name, @Param("date") Date date ); } </code></pre> <p>My test code is as follows and when I run it I get the error:</p> <pre><code>@Test public void testGettingApxSession() { Calendar cal = new GregorianCalendar(2016,6,5); byte[] b = userRepository.getUserSession("myName", cal.getTime()); } </code></pre> <p>When I log out <code>@data</code> using:</p> <pre><code> StringBuilder sb = new StringBuilder(); for (byte a : b) { sb.append(String.format("%02X ", a)); } </code></pre> <p>I noticed that only 8,000 bytes are being returned. When I run the same stored procedure in SQL Server Management Studio, I notice it has ~10,000 bytes and ends as it should with hex code FFFF.</p> <p>So, it appears my results are being truncated when running the stored procedure from my Java app. </p> <p>How can I prevent this truncation? Is there a different data type that I should be specifying for varbinary(max) instead of byte[]?</p> <p><strong>Update</strong> </p> <p>I've also tried Microsoft's JDBC driver (v 6.0.7728.100) and experience the same issue. My guess is that the JDBC drivers (I think) are taking the max to be 8000 based on that being the max number, <code>n</code>, you can specify in <code>varbinary(n)</code>. However, the max capacity of <code>varbinary</code> is much greater than 8000 and is specified by <code>varbinary(max)</code>. <code>varbinary(max)</code> can hold 2^31 - 1 bytes. See my question and other's answers <a href="http://dba.stackexchange.com/questions/152239/sql-server-how-can-varbinarymax-store-8000-bytes">here</a></p>
<p>Use Microsoft's JDBC driver and specify the output parameter type as a <code>Blob</code>:</p> <pre><code>@Entity @NamedStoredProcedureQuery(name = "User.getUser", procedureName = "User.pTest", parameters = { @StoredProcedureParameter(mode = ParameterMode.OUT, name = "data", type = Blob.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "name", type = String.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "date", type = Date.class) }) </code></pre> <p>Note: This will not work with jTDS. It will still truncate anything > 8000 bytes.</p> <p>If the <code>Blob</code> needs to be passed back to SQL Server, you must convert back to a byte array as follows:</p> <pre><code>byte[] bytes = blob.getBytes(1, (int) blob.length()); </code></pre>
How does OracleRefereceCursor get data from database? <p>Let's say I have a stored procedure in Oracle db which has a ref cursor output parameter.</p> <p>From .Net using ODP.Net I am trying to get the data from the DB as below (I have taken this from <a href="http://www.oracle.com/technetwork/articles/dotnet/williams-refcursors-092375.html" rel="nofollow">http://www.oracle.com/technetwork/articles/dotnet/williams-refcursors-092375.html</a>)</p> <pre><code> OracleCommand cmd = new OracleCommand("otn_ref_cursor.get_emp_info", con); cmd.CommandType = CommandType.StoredProcedure; // create parameter object for the cursor OracleParameter p_refcursor = new OracleParameter(); // this is vital to set when using ref cursors p_refcursor.OracleDbType = OracleDbType.RefCursor; // this is a function return value so we must indicate that fact p_refcursor.Direction = ParameterDirection.ReturnValue; // add the parameter to the collection cmd.Parameters.Add(p_refcursor); // create a data adapter to use with the data set OracleDataAdapter da = new OracleDataAdapter(cmd); // create the data set DataSet ds = new DataSet(); // fill the data set da.Fill(ds); </code></pre> <p>How does the dataset fill the records? Does it make one round-trip to database server to get one record at a time?</p> <p>Is it the same as </p> <pre><code>OracleDataReader dr = cmd.ExecuteReader(); while (reader.Read()) { //Do Something } </code></pre> <p>I think the approach of using DataReader will make one round-trip per each row to db, is my understanding correct?</p>
<p>The amount of data fetched in each roundtrip to the database is controlled by the Fetchsize which is a certain number of bytes. I forget the default size. You can control this by setting FetchSize to a multiple of Rowsize. ODP.NET will cache the data until it needs to fetch more.</p>
How get permission on WatchFace <p>I have a application on Android Wear. App comprises only WatchFace. How I can get permission without activity? Permission added into manifest.</p>
<p>Go to Settings -> Permissions -> Select your app -> Turn on the permissions you have put in your manifest file</p>
jQuery-AJAX: How to disable a button on table row only when a condition is met <p>I'm trying to disable a button only when a certain condition is met. The buttons are generated dynamically and they have a dynamic ID as well. These buttons are on a table and they appear on each row. (2 buttons per row and one of those two should always be disabled).</p> <p>The way I've done it so far, it disables all of the (same) buttons on all rows if the condition is met and I only need to disable the ones meeting the condition.</p> <p>This is the code I have so far.</p> <pre><code>&lt;script&gt; /* Search */ $('document').ready(function() { $('#submit-btn').prop('disabled', true); $('#fld_name').prop('disabled', true); $('#fld_id').prop('disabled', true); $('#fld_current').prop('disabled', true); $('#fld_new').prop('disabled', true); /* disable search button until ID length is reached */ $('#search-btn').prop('disabled', true); $('#search_value').keyup(function() { var id_search = $('#search_value').val().length; if(id_search &lt; 6){ $('#search-btn').prop('disabled', true); } else if (id_search == 6){ $('#search-btn').prop('disabled', false); } }); $("#search-btn").on('click', function(){ var data = $("#search-form").serialize(); $.ajax({ type : 'POST', url : 'search.php', data : data, cache: false, beforeSend: function() { $("#msg-block").fadeOut(); $("#search-btn").html('&lt;img src="../base_images/btn-loader-1.gif" /&gt; &amp;nbsp; Searching...'); $('#search-btn').prop('disabled', true); $('#user_list tbody').empty(); }, success : function(response) { result = jQuery.parseJSON(response); if(result.search_result == "found"){ $("#search-btn").html('Search'); $('#fld_name').prop('disabled', false).prop('readonly', true); $('#fld_id').prop('disabled', false).prop('readonly', true); $('#fld_current').prop('disabled', false).prop('readonly', true); $('#fld_new').prop('disabled', false); $("#fld_id").val(result.fld_id); $("#fld_name").val(result.name); $("#fld_current").val(result.current_status); //load table with search results. $.ajax({ type : 'POST', url : 'test.php', dataType: 'json', data : data, cache: false, success : function(result) { $('html, body').animate({ scrollTop: $('#user_list').offset().top }, 2000); for (var i = 0; i &lt; result.length; i++){ $('#user_list tbody').append( '&lt;tr id="user_tb_row"&gt;' +'&lt;td class="center tb_rec_id" id="'+result[i].tb_rec_id+'"&gt;' + result[i].tb_rec_id + '&lt;/td&gt;' +'&lt;td class="center tb_uni_id" id="'+ result[i].tb_emp_id +'"&gt;' + result[i].tb_emp_id + '&lt;/td&gt;' +'&lt;td&gt;' + result[i].tb_name + '&lt;/td&gt;' +'&lt;td class="center tb_status_id" id="'+result[i].tb_status+'"&gt;&lt;span class="label label-sm label-success center"&gt;' + result[i].tb_status + '&lt;/span&gt;&lt;/td&gt;' +'&lt;td class="center"&gt;' + result[i].tb_date + '&lt;/td&gt;' +'&lt;td&gt;' +'&lt;div class="margin-bottom-0"&gt;' +'&lt;button class="btn btn-sm green btn-outline margin-bottom access_activate" id="act_'+result[i].tb_rec_id+'"&gt;' +'&lt;i class="fa fa-search"&gt;&lt;/i&gt; Activate &lt;/button&gt;' +'&lt;button class="btn btn-sm green btn-outline margin-bottom access_suspend" id="sus_'+result[i].tb_rec_id+'"&gt;' +'&lt;i class="fa fa-search"&gt;&lt;/i&gt; Suspend &lt;/button&gt;' +'&lt;/div&gt;' +'&lt;/td&gt;' +'&lt;/tr&gt;'); //This is what I have been testing. if($('.tb_status_id').attr('id') == 1){ $('#act_'+result[i].tb_rec_id).prop('disabled', true); $('#sus_'+result[i].tb_rec_id).prop('disabled', false); } else if($('.tb_status_id').attr('id') == 0){ $('#act_'+result[i].tb_rec_id).prop('disabled', false); $('#sus_'+result[i].tb_rec_id).prop('disabled', true); } } } }); } else if(result.search_result == "not_found"){ //do stuff } else { //do other stuff } } }); return false; }); }); &lt;/script&gt; </code></pre>
<p>I've figured out how to accomplish what I needed. the if statement wasn't going to work because it will take every element with the same class and disable or enable it if the condition was met. Also, if/else cannot be used as is inside append.</p> <p>In order to make it work, I added used a <strong>ternary condition</strong> within the appended elements which will generate the content of each row individually based on that particular condition. (in this case the buttons).</p> <pre><code>for (var i = 0; i &lt; result.length; i++){ $('#user_list tbody').append( '&lt;tr id="user_tb_row"&gt;' +'&lt;td class="center tb_rec_id" id="'+result[i].tb_rec_id+'"&gt;' + result[i].tb_rec_id + '&lt;/td&gt;' +'&lt;td class="center tb_uni_id" id="'+ result[i].tb_emp_id +'"&gt;' + result[i].tb_emp_id + '&lt;/td&gt;' +'&lt;td&gt;' + result[i].tb_name + '&lt;/td&gt;' +'&lt;td class="center tb_status_id" id="'+result[i].tb_status+'"&gt;&lt;span class="label label-sm label-success center"&gt;' + result[i].tb_status + '&lt;/span&gt;&lt;/td&gt;' +'&lt;td class="center"&gt;' + result[i].tb_date + '&lt;/td&gt;' +'&lt;td&gt;' +'&lt;div class="margin-bottom-0"&gt;' +(result[i].tb_status == 1 ? //this is the conditional statement. '&lt;button class="btn btn-sm green btn-outline margin-bottom access_activate" id="act_'+result[i].tb_rec_id+'" disabled&gt;' //disabled button where condition is met +'&lt;i class="fa fa-search"&gt;&lt;/i&gt; Activate &lt;/button&gt;' +'&lt;button class="btn btn-sm green btn-outline margin-bottom access_suspend" id="sus_'+result[i].tb_rec_id+'"&gt;' +'&lt;i class="fa fa-search"&gt;&lt;/i&gt; Suspend &lt;/button&gt;' : //else statement '&lt;button class="btn btn-sm green btn-outline margin-bottom access_activate" id="act_'+result[i].tb_rec_id+'" disabled&gt;' +'&lt;i class="fa fa-search"&gt;&lt;/i&gt; Activate &lt;/button&gt;' +'&lt;button class="btn btn-sm green btn-outline margin-bottom access_suspend" id="sus_'+result[i].tb_rec_id+'"&gt;' //disabled button where condition is met +'&lt;i class="fa fa-search"&gt;&lt;/i&gt; Suspend &lt;/button&gt;' ) +'&lt;/div&gt;' +'&lt;/td&gt;' +'&lt;/tr&gt;'); } </code></pre> <p>I'm use that there are other ways to do this but this is the only way I figured out how to do it. Hope it helps others that might be looking to accomplish the same thing.</p>
Transactions dependency between rest services <p>We are converting our application to support SOA, mainly into restful services. I have the services developed, however I am now concerned about how to rollback the transaction of service 1 if service 2 fails.</p> <p>I have a page made of three services. If any of the service fails then i have to roll back the entire page to the previous state and make sure all the asynchronous service calls fired from the page are rolled back as well.</p> <p>I don't have any direction how to handle this. Can anyone throw light on this.</p> <p>Let me know if i am not making sense and have to provide more information</p>
<p><strong>tl;dr</strong>: use compensation actions and idempotence</p> <p>In more detail:</p> <p>SOA and REST are architectural styles. This also means that when moving from a monolith to SOA and moving from distributed transactions to REST as well as moving from RPC (RMI, etc.) to REST, you have to rethink transactions.</p> <p>Lets first have a look how this works in the non-REST world and then how this changes. You are a bit vague on how your current application looks like so I'll point out a range of scenarios.</p> <h2>Monolith</h2> <p>When you have a monolithic application, your whole code resides in the same artifact, all processing is done on the same machine, and all data access is centralized. You can have a single transaction that spans everything. Your DBMS grants you the <a href="https://en.wikipedia.org/wiki/ACID" rel="nofollow">ACID</a> properties.</p> <h2>Distributed Transactions</h2> <p>There are ways to span a transaction across the network and coordinate several nodes using <a href="https://en.wikipedia.org/wiki/Two-phase_commit_protocol" rel="nofollow">2PC</a>. This is not very different from the monolith scenario -- except there are more latencies, more rollbacks, more scaling issues, etc.</p> <h2>SOA</h2> <p>In a SOA world, you stop coupling your services using the database and have your services interact using service interfaces instead. This has plenty of advantages but also some consequences, you should be aware of.</p> <p>In SOA you don't use distributed transactions but every service has its own database and its own transaction. When there are two services and service A calls service B and B fails, A can recognize this failure (catch the exception or let the container handle that) and rollback its own transaction. But if A has successfully called B and then fails before committing its own transaction than there is no possibility what so ever to rollback the transaction at B because at B the transaction is already committed. In short: You don't have ACID anymore with SOA. There is no guarantee on atomicity or consistency and only partial isolation. Get used to it.</p> <p>In fact ACID is a lie for normal RDBMS, too. When they are operated on pure ACID compliance ("serializable") they get unusably slow. Because of that, DBMS have different <a href="https://en.wikipedia.org/wiki/Isolation_(database_systems)" rel="nofollow">isolation levels</a> where you allow them to make certain shortcuts. Actually almost nobody operates a database such that they really guarantee ACID. The inconsistencies that may occur are just rare enough so you can tolerate them. Inconsistencies can occur and you have to recover from them or work around them.</p> <p>The same thing applies when you handle with something outside your database. You cannot unprint an invoice. You cannot unsend an email, etc. You cannot unbake a cake. You have to find a suitable compensation action.</p> <p>And this is also what you have to do in a SOA environment. Inconsistencies may occur and this means you have to handle them for yourself. There are several ways to do so:</p> <ul> <li>If they are rare enough and the data is not that critical, you may safely ignore them. </li> <li>If they are rare enough, you can choose to handle them manually. If there's a problem with one customer per year, fix the problem when the customer complains, apologize, and send him a goody or so.</li> <li><p>If these problems occur more often than you can handle manually, implement an automatic compensation action. If the invoice is printed, throw it a way. If you already sent it, send a cancellation. If the customer has already payed, send a credit note, etc.</p> <p>You are already used to having compensation actions in your application. You can handle failing service just like a wrong invoice. And just like in the wrong invoice example, it heavily depends on the concrete failure situation how you may want to handle it. Maybe the correct solution is to delete some database record. Or you need to repeat a service call. Or you need to make another service call. I cannot tell you what exactly you need to do but you will know it when you think about it.</p></li> </ul> <h2>REST</h2> <p>One thing which can go wrong and may need a compensation action is that a service call can fail (for several reasons). REST and HTTP have several mechanisms which help you in this case. </p> <p>One of these mechanisms is <a href="http://www.restapitutorial.com/lessons/idempotency.html" rel="nofollow">idempotence</a>. If your service call failed or if you are not sure if it succeeded, you can just retry the service call. You are required to make all your GET, PUT, and DELETE operations idempotent so your service clients can safely retry. POST and PATCH operations are not required to be idempotent, although especially with PATCH it is helpful if they are so nevertheless.</p> <p>There are quite sophisticated mechanisms (e.g. calls with preconditions) but in fact with idempotence you can handle 95% of your problems. You can read about them when you are used to rest. At the beginning you should stick to the basics. Only use the more sophisticated stuff if you have a good reason to do so.</p> <p>BTW: It is very helpful to have a unit test which checks for idempotence. Especially if you are not used to it or if there is some complicated stuff going on, it is advisable to check this as you really don't want to get that wrong.</p> <h2>Conclusion</h2> <p>The solution is not to bring transactions to SOA and REST but to think in a service-oriented and restful way when you develop your application.</p>
Karma cannot load Angular 2 Component <p>My Karma cannont load angular 2 component. Drop this error: </p> <pre><code>[web-server] :404 : /base/src/client/app/container/container.component </code></pre> <p>i do everything with angular 2 testing tutorial (i only modified path in karma) So problem must be in path. but i don't have any idea how to fix it.</p> <p>My Path:</p> <pre><code>src | |client | | |container | | | |container.component.ts | | | |container.component.spec.ts |karma.conf.js |karma-test-shim.js </code></pre> <p>container.component.ts</p> <pre><code>import { Component, OnInit } from '@angular/core'; import { UserService } from '../user/user.service'; import { User } from '../user/user'; //import { FacebookLogin } from '../facebook/fb-login'; //import { Facebook } from '../facebook/facebook'; @Component({ selector: 'app-container', //templateUrl: '../../views/content.html', template: `Hello World`, providers: [UserService] }) export class ContainerComponent implements OnInit{ user: User; // constructor(private userService: UserService) { // this.loadUser(); // if(typeof FB == 'undefined') {console.log("NULL");} // } // loadUser() { // this.userService.getMockUser().then(userData =&gt; // { // this.user = userData // console.log("User data: " + userData.email); // }); // } ngOnInit(){ } } </code></pre> <p>container.component.spec.ts</p> <pre><code>import { ComponentFixture, TestBed, async } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { ContainerComponent } from './container.component'; let comp: ContainerComponent; let fixture: ComponentFixture&lt;ContainerComponent&gt;; let de: DebugElement; let el: HTMLElement; describe('Container Component', () =&gt; { // beforeEach( async(() =&gt; { // TestBed.configureTestingModule({ // declarations: [ContainerComponent], // }).compileComponents(); // fixture = TestBed.createComponent(ContainerComponent); // comp = fixture.componentInstance; // })); beforeEach(() =&gt; { TestBed.configureTestingModule({ declarations: [ContainerComponent], // declare the test component }); }); }); </code></pre> <p>karma.conf.js</p> <pre><code> // #docregion module.exports = function(config) { var appBase = 'src/client/app/'; // transpiled app JS and map files var appSrcBase = 'src/client/app/'; // app source TS files var appAssets = '/base/app/'; // component assets fetched by Angular's compiler var testBase = 'testing/'; // transpiled test JS and map files var testSrcBase = 'testing/'; // test source TS files config.set({ basePath: '', frameworks: ['jasmine'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), // click "Debug" in browser to see it require('karma-htmlfile-reporter') // crashing w/ strange socket error ], 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: false, 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: false}, {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: {}, // disabled HtmlReporter; suddenly crashing w/ strange socket error reporters: ['progress', 'kjhtml'],//'html'], // HtmlReporter configuration htmlReporter: { // Open this file to see results in browser outputFile: '_test-output/tests.html', // Optional pageTitle: 'Unit Tests', subPageTitle: __dirname }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }) } karma-test-shim.js // #docregion // /*global jasmine, __karma__, window*/ Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing. // Uncomment to get full stacktrace output. Sometimes helpful, usually not. // Error.stackTraceLimit = Infinity; // jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000; var builtPath = '/base/src/client/app/'; __karma__.loaded = function () { }; function isJsFile(path) { return path.slice(-3) == '.js'; } function isSpecFile(path) { return /\.spec\.(.*\.)?js$/.test(path); } function isBuiltFile(path) { return isJsFile(path) &amp;&amp; (path.substr(0, builtPath.length) == builtPath); } var allSpecFiles = Object.keys(window.__karma__.files) .filter(isSpecFile) .filter(isBuiltFile); System.config({ baseURL: '/base', // Extend usual application package list with test folder packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } }, // Assume npm: is set in `paths` in systemjs.config // Map the angular testing umd bundles map: { '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js', '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js', '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js', '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js', '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js', '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js', '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js', '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js', }, }); System.import('systemjs.config.js') .then(importSystemJsExtras) .then(initTestBed) .then(initTesting); /** Optional SystemJS configuration extras. Keep going w/o it */ function importSystemJsExtras(){ return System.import('systemjs.config.extras.js') .catch(function(reason) { console.log( 'Warning: System.import could not load the optional "systemjs.config.extras.js". Did you omit it by accident? Continuing without it.' ); console.log(reason); }); } function initTestBed(){ return Promise.all([ System.import('@angular/core/testing'), System.import('@angular/platform-browser-dynamic/testing') ]) .then(function (providers) { var coreTesting = providers[0]; var browserTesting = providers[1]; coreTesting.TestBed.initTestEnvironment( browserTesting.BrowserDynamicTestingModule, browserTesting.platformBrowserDynamicTesting()); }) } // Import all spec files and start karma function initTesting () { return Promise.all( allSpecFiles.map(function (moduleName) { return System.import(moduleName); }) ) .then(__karma__.start, __karma__.error); } </code></pre>
<p>I recently came across this same issue and I came to the conclusion that SystemJS is responsible for default extensions (should be 'js'). Make sure that your ng2 app folder is properly connected with your systemjs.config file.</p> <pre><code>(function (global) { System.config({ paths: { // paths serve as alias 'npm:': 'node_modules/' }, // map tells the System loader where to look for things map: { // app is within the app folder app: 'app', &lt;&lt;&lt;&lt;&lt;&lt;&lt;------ HERE '@angular/core': 'npm:@angular/core/bundles/core.umd.js', '@angular/common': 'npm:@angular/common/bundles/common.umd.js', '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js', '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js', '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js', '@angular/http': 'npm:@angular/http/bundles/http.umd.js', '@angular/router': 'npm:@angular/router/bundles/router.umd.js', '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js', '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js', // other libraries 'rxjs': 'npm:rxjs', 'angular-in-memory-web-api': 'npm:angular-in-memory-web-api' }, packages: { app: { &lt;&lt;&lt;&lt;&lt;&lt;&lt;------ HERE main: './main.js', defaultExtension: 'js' &lt;&lt;&lt;&lt;&lt;&lt;----- Important!! }, rxjs: { defaultExtension: 'js' }, 'angular-in-memory-web-api': { main: 'server/server.js', defaultExtension: 'js' } } }); })(this); </code></pre> <p>If this is correct and it is still having issues than it's probably an inconsistency in how your karma web-server and your node server serve your client files. You can add a proxy in your karma.conf file...</p> <pre><code>proxies: { // required for component assets fetched by Angular's compiler "/app/": "/base/client/app/" }, </code></pre> <p>Hope this helps! c:</p>
Distinguishing between 0 and null in OR statement in Javascript <p>I have below code in my function, I want to assign a value to the variable newValue.</p> <p><code>var newValue = fieldValue || originalValue || masterValue;</code></p> <p>Here if I have the originalValue = 0, the java script treats it as false/null and assigns masterValue to the newValue. Instead I want to assign originalValue (0) to the newValue.</p> <p>Is there a way to achieve this without an extra line of code?</p>
<p>Yes but it gets a bit complicated (<em>using the ternary operator</em>).</p> <pre><code>var newValue = fieldValue || (originalValue || originalValue===0) ? originalValue : masterValue; </code></pre> <p>(<em>this assumes you want to 0 to be assigned even when in <code>fieldValue</code></em>)</p>
heightForHeaderInSection only called once <p>Coding in Swift 3. Have a tableView with custom cells and header.</p> <p>I have a tableView with custom cells and headers. The headers have two (2) labels in them and have dynamic cell heights since the labels may be long. My problem is the first time the tableView and sections are configured the label appears as it should, HOWEVER, after scrolling down and then back up the headers' layout somehow breaks. </p> <p><a href="http://i.stack.imgur.com/yPsVx.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/yPsVx.jpg" alt="When tableView first loads and user scrolls down everything appears fine"></a></p> <p>As you can see below, after I scroll down then back up to the cells, the label is getting cutoff.</p> <p><a href="http://i.stack.imgur.com/Dwo3q.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Dwo3q.jpg" alt="After scrolling down and back up label is cut off"></a></p> <p>After printing out what methods are being called I found that the first time scrolling down the tableView the following two (2) override functions are called.</p> <pre><code>override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -&gt; CGFloat { print("\(section) heightForHeaderInSection") print("\(section) returning AUTO for header") return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -&gt; UIView? { print("\(section) viewForHeaderInSection") let header = tableView.dequeueReusableCell(withIdentifier: "QuestionHeader") as! QuestionHeader header.delegate = self header.contentView.backgroundColor = UIColor.groupTableViewBackground header.questionTextLabel.text = String(questionStringArray[section]) header.questionNumberLabel.text = (String(section + 1) + ")") return header.contentView } </code></pre> <p>But when i scroll back up ONLY the viewForHeader function is called and I think because the height is no longer being set to UITableViewAutomaticDimension the labels get cutoff?</p> <p>Any ideas?</p>
<p>You should return <code>header</code> instead of <code>header.contentView</code> from <code>tableView: viewForHeaderInSection:</code> method:</p> <pre><code>override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -&gt; UIView? { let header = tableView.dequeueReusableCell(... ... return header } </code></pre>
JavaScript function is not defined in external .js file in IE only <p>I use an external JavaScript file (.js) in a classic ASP program. I added a new function 'isFutureDate(dt)' to this file. The new function works fine when using Chrome browser to access the web page. When using IE 11, it showed the error of "isFutureDate() is undefined". Other functions in external .js are working.</p> <p>I run into this type of problems several times recently. The existing functions in external .js file are working, but the newly added ones didn't work. I had to move those functions back to the ASP program, then they worked fine. My web server is IIS 7.5. I am not sure whether this issue is related to type of web server I am using.</p> <p>I read several posts about problems with JavaScript function in external .js file. But, I have not found one that describe the same problem as mine.</p>
<p>Hi Below are the root cause</p> <p>1) check the order of the Js file. it should be in correct order.</p> <p>2) If you are using multiple Js file. Use bundling because some browser have limitation of calling concurrent HTTP Call. if the limit exceeds it will stop rendering the script</p> <p>3) It should be the caching issue also open in Incognito window.</p> <p>4) last Debug using Inspect Element.</p>
Dynamically how to set value to selected of select dropdown in angularjs depending upon value stored in array of objects <pre><code>I have multiple records which are stored in </code></pre> <p>$scope.myQuality</p> <p>variable currently in in below attached plnkr but that data will be coming from rest api. Currently i have used ng-options for display select options which i am getting from $scope.items. Depending upon the value of ("status": true) i want to make the dropdown value selected to "OK"</p> <p>If </p> <p>("status": true)</p> <p>-> selected value in dropdown should be OK </p> <p>If </p> <p>("status": false)</p> <p>-> selected value in dropdown should be KO </p> <p>If </p> <blockquote> <p>("status": null)</p> </blockquote> <p>-> selected value in dropdown should be empty</p> <p>Each record will have dropdown but it's selected value will differ depending on the value of status within </p> <blockquote> <p>$scope.myQuality</p> </blockquote> <p>Please find the below url</p> <p><a href="http://plnkr.co/edit/aW5enrHuEZ2jHiQuHQmV?p=preview" rel="nofollow">http://plnkr.co/edit/aW5enrHuEZ2jHiQuHQmV?p=preview</a></p> <blockquote> Id Date Status {{ roll. id}} {{ roll. date | date:"dd/MM/yyyy HH:mm" }} </blockquote> <p>script.js</p> <blockquote> <p>// Code goes here</p> <p>angular.module('sortApp', [])</p> <p>.controller('mainController', function($scope) { $scope.sortType = 'id'; // set the default sort type $scope.sortReverse = false; // set the default sort order $scope.searchLists = ''; // set the default search/filter term</p> <pre><code>$scope.items =[ {"value":true,"text":"OK"}, {"value":false,"text":"KO"} ]; $scope.myQuality = [ { "id": 1, "status": true, "date": 1474864500000, }, { "id": 2, "status": false, "date": 1474741800000, },{ "id": 3, "status": null, "date": 1474914600000, },{ "id": 4, "status": true, "date": 1474914600000, },{ "id": 5, "status": true, "date": 1474914600000, },{ "id": 6, "status": true, "date": 1474914600000, },{ "id": 7, "status": true, "date": 1474914600000, },{ "id": 8, "status": true, "date": 1474914600000, },{ "id": 9, "status": true, "date": 1474914600000, },{ "id": 10, "status": false, "date": 1474914600000, },{ "id": 11, "status": true, "date": 1474914600000, },{ "id": 12, "status": false, "date": 1474914600000, } ] }); </code></pre> </blockquote>
<p>Just remove the track by from your ng-options, plnkr below:</p> <p><a href="https://plnkr.co/edit/olbqvp2GiTTqr1JUyeSq?p=preview" rel="nofollow">https://plnkr.co/edit/olbqvp2GiTTqr1JUyeSq?p=preview</a></p> <pre><code>ng-options="option.value as option.text for option in items" </code></pre>
Display N/A if formula value is zero <p>I have the below formula, and I am trying to add "if 0 then show N/A" but it's not working properly.</p> <pre><code>Local StringVar x := ToText({SMPLODC.LCSCHD}, "0"); Local NumberVar c := (ToNumber(LEFT(x, 1)) + 1) * 10; x := RIGHT(x, 6); Local NumberVar y := ToNumber(ToText(c, "0") &amp; LEFT(x, 2)); x := RIGHT(x, 4); Local NumberVar m := ToNumber(LEFT(x, 2)); x := RIGHT(x, 2); Local NumberVar d :=ToNumber(x); Dateserial(y,m,d) </code></pre>
<p>An easy way to do this is to right click the formula field, select <em>Format Editor -> Common -> Display String:</em> and enter the following code:</p> <pre><code>If {@YourFormulaNameHere} = "0" Then "N/A" Else Cstr({@YourFormulaNameHere}) </code></pre>
Spring Integration Kafka Consumer Listener not Receiving messages <p>According to the documentation provided <a href="http://docs.spring.io/spring-kafka/docs/1.1.1.RELEASE/reference/html/_reference.html" rel="nofollow">here</a>, I am trying on a POC to get messages into a listener as mentioned in the the <a href="http://docs.spring.io/spring-kafka/docs/1.1.1.RELEASE/reference/html/_reference.html" rel="nofollow">same documentation</a>, Below is how I have written the configuration.</p> <pre><code>@Configuration public class KafkaConsumerConfig { public static final String TEST_TOPIC_ID = "record-stream"; @Value("${kafka.topic:" + TEST_TOPIC_ID + "}") private String topic; @Value("${kafka.address:localhost:9092}") private String brokerAddress; /* @Bean public KafkaMessageDrivenChannelAdapter&lt;String, String&gt; adapter( KafkaMessageListenerContainer&lt;String, String&gt; container) { KafkaMessageDrivenChannelAdapter&lt;String, String&gt; kafkaMessageDrivenChannelAdapter = new KafkaMessageDrivenChannelAdapter&lt;&gt;( container, ListenerMode.record); kafkaMessageDrivenChannelAdapter.setOutputChannel(received()); return kafkaMessageDrivenChannelAdapter; } @Bean public QueueChannel received() { return new QueueChannel(); } */ @Bean public KafkaListenerContainerFactory&lt;ConcurrentMessageListenerContainer&lt;String, String&gt;&gt; kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; factory = new ConcurrentKafkaListenerContainerFactory&lt;&gt;(); factory.setConsumerFactory(consumerFactory()); factory.setConcurrency(3); factory.getContainerProperties().setPollTimeout(30000); return factory; } /* * @Bean public KafkaMessageListenerContainer&lt;String, String&gt; container() * throws Exception { ContainerProperties properties = new * ContainerProperties(this.topic); // set more properties return new * KafkaMessageListenerContainer&lt;&gt;(consumerFactory(), properties); } */ @Bean public ConsumerFactory&lt;String, String&gt; consumerFactory() { Map&lt;String, Object&gt; props = new HashMap&lt;&gt;(); props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, this.brokerAddress); // props.put(ConsumerConfig.GROUP_ID_CONFIG, "mygroup"); props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); // earliest // smallest props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true); props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100"); props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000"); props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); return new DefaultKafkaConsumerFactory&lt;&gt;(props); } } </code></pre> <p>and Listener is as below,</p> <pre><code>@Service public class Listener { private Logger log = Logger.getLogger(Listener.class); @KafkaListener(topicPattern = KafkaConsumerConfig.TEST_TOPIC_ID, containerFactory = "kafkaListenerContainerFactory") public void process(String message/* , Acknowledgment ack */) { Gson gson = new Gson(); Record record = gson.fromJson(message, Record.class); log.info(record.getId() + " " + record.getName()); // ack.acknowledge(); } } </code></pre> <p>Even though I am producing messages to the same topic and this consumer is working on the same topic, Listener is not executing. </p> <p>I am running Kafka 0.10.0.1, and here is my current pom. This consumer is working as a spring boot web application unlike many command line samples.</p> <pre><code> &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.integration&lt;/groupId&gt; &lt;artifactId&gt;spring-integration-kafka&lt;/artifactId&gt; &lt;version&gt;2.1.0.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.integration&lt;/groupId&gt; &lt;artifactId&gt;spring-integration-java-dsl&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt; &lt;artifactId&gt;gson&lt;/artifactId&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt; &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>I have spent a good amount of time to figure out why this listener is not getting hit when the topic has messages, what is it I am doing wrong. </p> <p>I know that I can receive the messages using a channel (I have commented configuration part of that out in the code), But here the concurrency is handle clean. </p> <p>Is this kind of implementation is possible with a async message consumption. </p>
<p>You have to add <code>@EnableKafka</code> alongside with the <code>@Configuration</code>.</p> <p>Will <a href="https://github.com/spring-projects/spring-kafka/issues/189" rel="nofollow">add</a> some description soon.</p> <p>Meanwhile:</p> <pre><code>@Configuration @EnableKafka public class KafkaConsumerConfig { </code></pre>
How to make JavaScript indexOf() not detect substring <p>Here are two if conditions with different checks:</p> <p>CASE 1: </p> <pre><code>if(plan_name.indexOf("T1")&gt;=0 &amp;&amp; plan_name.indexOf("FLEX")&gt;=0 &amp;&amp; plan_name.indexOf("Non-VAE")&gt;=0) { //do something } </code></pre> <p>followed by (in same code/program)</p> <p>CASE 2:</p> <pre><code>if(plan_name.indexOf("T1")&gt;=0 &amp;&amp; plan_name.indexOf("Non-FLEX")&gt;=0 &amp;&amp; plan_name.indexOf("Non-VAE")&gt;=0){ //do something } </code></pre> <p>Here is the input to which above conditions get applied: </p> <p><strong>plan name</strong> = <code>iOS 7.7 - RC - T1 - Non-FLEX, Non-VAE</code></p> <p>In my code everytime the first <code>if</code> condition in CASE 1 is becoming valid because indexOf() is detecting the substring and not the <code>actual specific</code> string that I want the code to detect(that is CASE 2 should be valid). How to make such specific string match in JS? </p>
<p>One solution is split it apart and see if the string matches in the array</p> <pre><code>var str = "iOS 7.7 - RC - T1 - Non-FLEX, Non-VAE"; var parts = str.split(/[\s,]/g); console.log("FLEX", parts.indexOf("FLEX")!==-1); console.log("Non-FLEX", parts.indexOf("Non-FLEX")!==-1); </code></pre>
Polymer 1.x: How to get paper-dialog-scrollable to render and behave when not direct child of paper-dialog <p><a href="http://jsbin.com/lifamasowe/1/edit?html,output" rel="nofollow">This jsBin demos correct implementation of <code>paper-dialog-scrollable</code></a>.</p> <p><a href="http://jsbin.com/fapivoqako/1/edit?html,output" rel="nofollow">However, this jsBin demonstrates</a> that <code>paper-dialog-scrollable</code> fails to render properly when it is not a direct child of <code>paper-dialog</code> (i.e., <code>paper-dialog-scrollable</code> is inside an intermediary <code>div</code> tag, which breaks it).</p> <p>How do I get the <code>paper-dialog-scrollable</code> to render properly and display proper scrolling behavior when it is not a direct child of <code>paper-dialog</code>? Please provide a working jsBin.</p> http://jsbin.com/fapivoqako/1/edit?html,output <pre><code>&lt;!doctype html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;base href="https://polygit.org/components/"&gt; &lt;script src="webcomponentsjs/webcomponents-lite.min.js"&gt;&lt;/script&gt; &lt;link href="polymer/polymer.html" rel="import"&gt; &lt;link href="paper-dialog/paper-dialog.html" rel="import"&gt; &lt;link href="paper-dialog-scrollable/paper-dialog-scrollable.html" rel="import"&gt; &lt;/head&gt; &lt;body&gt; &lt;dom-module id="x-element"&gt; &lt;template&gt; &lt;button on-tap="open"&gt;Open&lt;/button&gt; &lt;paper-dialog id="dialog"&gt; &lt;div&gt; &lt;paper-dialog-scrollable&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam et felis sem. Fusce at sollicitudin turpis, quis malesuada risus. Praesent nibh purus, gravida at bibendum non, ultrices et ipsum. Sed eu nibh nisl. Praesent mollis faucibus lorem eu ultricies. Nunc viverra est leo, vitae bibendum massa bibendum ac. Pellentesque rhoncus dui eget metus pulvinar, ac pharetra metus luctus. Nam sodales velit a enim pharetra tincidunt. Cras justo mauris, malesuada eu hendrerit vel, scelerisque et purus. Curabitur elementum, eros quis bibendum fringilla, ante lacus consequat nunc, quis tincidunt ante felis a nunc. Pellentesque in dolor dapibus, gravida purus vitae, vulputate tellus. Phasellus non arcu vel arcu bibendum ultrices nec quis quam. Ut tellus tellus, pellentesque a auctor at, maximus at lectus. In hac habitasse platea dictumst.&lt;/p&gt;&lt;p&gt;Duis vel finibus est. Donec commodo, nibh id auctor ullamcorper, augue nunc scelerisque magna, sed volutpat velit elit malesuada augue. Sed tempus, mi eget tincidunt sodales, arcu quam maximus nunc, ut fringilla ex nibh at justo. Morbi libero felis, iaculis ac dui at, convallis sagittis leo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam convallis elit orci, sed interdum dolor egestas in. Suspendisse luctus nibh ligula, non commodo erat volutpat ut. Nam mattis risus nec dolor pretium ornare. Phasellus ornare rhoncus elit a facilisis. Nullam non facilisis libero. Maecenas cursus tristique commodo.&lt;/p&gt;&lt;p&gt;Praesent consequat, diam non faucibus dictum, nisi ex faucibus risus, sit amet maximus dolor metus eu metus. Nullam malesuada sem id libero semper, id eleifend est tincidunt. Proin euismod urna augue, ut rutrum erat tristique non. Donec nec pellentesque sem. Fusce sit amet magna quis enim dapibus mattis. Ut tempus purus non sem tincidunt bibendum. Quisque cursus pretium ipsum, id hendrerit nisl mattis id. Vestibulum ultrices malesuada nisl, a cursus lorem sollicitudin id. Proin finibus rhoncus leo, at finibus lacus consectetur eu. Nulla aliquam quis risus non ultricies. Sed suscipit odio sed turpis scelerisque, non ultricies risus posuere. Duis et convallis felis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin a volutpat lorem. Nulla eleifend erat viverra nisi venenatis porttitor.&lt;/p&gt;&lt;p&gt;Proin egestas, ex et hendrerit pellentesque, orci sem posuere est, ornare porta augue mauris vitae elit. Nunc lobortis sapien in lobortis cursus. Morbi lacinia vel ligula a varius. Morbi mauris metus, pretium sit amet nibh in, vestibulum dapibus felis. Aliquam laoreet dolor nisi, vel ornare orci ultricies vitae. Donec facilisis vehicula elementum. Donec sed ligula leo. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.&lt;/p&gt;&lt;p&gt;Suspendisse eget orci in augue vulputate eleifend non eu sem. Etiam ipsum velit, gravida a egestas a, faucibus sed mauris. Morbi sit amet euismod odio, ac scelerisque diam. Donec neque risus, malesuada vel efficitur quis, tristique non lacus. Suspendisse potenti. Curabitur placerat felis sed ipsum sodales, sit amet dignissim arcu molestie. Sed tincidunt iaculis sagittis. Phasellus aliquet, lorem sed laoreet fermentum, massa mi facilisis felis, ac mattis magna turpis eu odio. Integer gravida sem ac tellus suscipit scelerisque. Aliquam et turpis tristique, elementum dolor luctus, auctor eros. &lt;/paper-dialog-scrollable&gt; &lt;/div&gt; &lt;/paper-dialog&gt; &lt;/template&gt; &lt;script&gt; (function(){ Polymer({ is: "x-element", properties: {}, open: function() { this.$.dialog.open(); } }); })(); &lt;/script&gt; &lt;/dom-module&gt; &lt;x-element&gt;&lt;/x-element&gt; &lt;/body&gt; </code></pre>
<p>The <a href="https://elements.polymer-project.org/elements/paper-dialog-scrollable" rel="nofollow">docs for <code>paper-dialog-scrollable</code></a> state:</p> <blockquote> <p>If <code>paper-dialog-scrollable</code> is not a direct child of the element implementing <code>Polymer.PaperDialogBehavior</code>, remember to set the <code>dialogElement</code></p> </blockquote> <p>To get your example working:</p> <pre><code>// template &lt;paper-dialog id="dialog"&gt; &lt;div&gt; &lt;paper-dialog-scrollable id="scrollable"&gt; &lt;p&gt;Lorem ipsum dolor sit amet...&lt;/p&gt; &lt;/paper-dialog-scrollable&gt; &lt;/div&gt; &lt;/paper-dialog&gt; // script Polymer({ ... ready: function() { this.$.scrollable.dialogElement = this.$.dialog; } }); </code></pre> <p><a href="http://jsbin.com/setaguhama/1/edit?html,output" rel="nofollow">jsbin</a></p>
Node partial require/import <p>I am following a MS tutorials on node and trying to require part of the module only. When i execute the code i get a syntax error though VS code editor seems to import properly in intellisense. Please assist</p> <p>Index.js</p> <pre><code>'use strict'; const { doSomething } = require('./first-module'); doSomething(); </code></pre> <p>first-module.js</p> <pre><code>module.exports = { doIt: function(){ console.log('Did it'); }, doSomething: function(){ console.log('Did Something'); }, getItDone: function(){ console.log('Got it done'); } }; </code></pre> <p>Terminal Error: Running with "node index"</p> <pre><code>d:\env\node\first-module&gt;node index d:\env\node\first-module\index.js:3 const { doSomething } = require('./first-module'); ^ SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:373:25) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:974:3 </code></pre> <p>In the tutorial, however, the result was diplaying 'Did Something' in the console.</p>
<p>Get rid of the brackets around <code>doSomething</code>. Those brackets would be used if you were using an <code>import</code> statement.</p> <pre><code>import { member } from "module-name"; </code></pre> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import</a></p> <p>Note that you can't use <code>import</code> with Node.js directly.</p>
Typescript interface type with optional keys of different types and strictNullChecks <p>I am trying to create the following interface in typescript:</p> <pre><code>type MoveSpeed = "min" | "road" | "full"; interface Interval { min?: number, max?: number } interface CreepPlan { [partName: string] : Interval; move?: MoveSpeed; } </code></pre> <p>However, this syntax is invalid. The compiler says <code>Property 'move' of type '"min" | "road" | "full" | undefined' is not assignable to string index type 'Interval'.</code>.</p> <p>I am using the compiler option <code>strictNullChecks:true</code>, which is why <code>undefined</code> is included implicitly for the <code>move?</code> key.</p> <p>However, this syntax is valid:</p> <pre><code>type MoveSpeed = "min" | "road" | "full"; interface Interval { min?: number, max?: number } interface CreepPlan { [partName: string] : Interval; move: MoveSpeed; // 'move' is required } </code></pre> <p>I want to express the idea "CreepPlan consists of string:Interval pairs, except the optional 'move' key which is a string:MoveSpeed pair." Is it possible to express this in typescript?</p>
<p>You stated that all properties on <code>CreepPlan</code> have <code>Interval</code>-type values when you wrote:</p> <pre><code>interface CreepPlan { [partName: string] : Interval; } </code></pre> <p>i.e., any and every string-index-accessible property of <code>CreepPlan</code> will be an <code>Interval</code>. This applies to <code>move</code> as well, since <code>foo['move']</code> is the same as <code>foo.move</code>.</p> <p>However, looking at <code>Interval</code>, there's no required structure to it:</p> <pre><code>interface Interval { min?: number, max?: number } </code></pre> <p>There are no required fields in that contract, but it <em>does</em> require an object. It will happily accept an empty object, but it requires some object that <em>could</em> have a <code>min</code> and <code>max</code> properties.</p> <p>Your <code>MoveSpeed</code> type, on the other hand, allows <code>undefined</code>:</p> <blockquote> <p>Property 'move' <strong>of type '"min" | "road" | "full" | undefined'</strong> is not assignable to string index type 'Interval'.</p> </blockquote> <p>Thus, <code>Interval</code> must be an object with no required properties (which <code>string</code> can easily meet) but does not allow <code>undefined</code>, which <code>MoveSpeed</code> <em>does</em> allow.</p> <p>Your types are disjoint, but it's not obvious until you resolve them out once or twice.</p>
Requesting the most recent version of an entity in CRM <p>I'm updating an entity using the <a href="https://msdn.microsoft.com/en-us/library/gg328198(v=crm.5).aspx" rel="nofollow">Organization Service</a>:</p> <pre><code> _organizationService.Update(contact); </code></pre> <p>I then would like to immediately query CRM for the latest version of that record by issuing something like:</p> <pre><code>_xrmServiceContext.ContactSet.FirstOrDefault(x =&gt; x.Id == contactGuid); </code></pre> <p>I'm noticing that the _xrmServiceContext is returning old data, unless I do a Thread.Sleep(1000) before requesting the updated data. </p> <p><strong>Is there a way to "wait" until the data is updated?</strong></p> <p>I'm looking at <a href="https://msdn.microsoft.com/en-us/library/jj863604(v=crm.5).aspx" rel="nofollow">this</a> as a possible solution; however, I am not sure how I would change my implementation to match this pattern. </p>
<p><a href="https://msdn.microsoft.com/en-us/library/gg695819(v=crm.7).aspx" rel="nofollow">XrmServiceContext</a> takes in organization service as a parameter which is cached. </p> <p>Use clear changes <code>_xrmServiceContext.ClearChanges();</code></p> <p>Or alternatively you could new up another <a href="https://msdn.microsoft.com/en-us/library/gg695819(v=crm.7).aspx" rel="nofollow">XrmServiceContext</a> object by passing a newed up organizationservice.</p> <pre><code>var uncachedOrganizationService = new OrganizationService("Xrm"); var uncachedXrmServiceContext = new XrmServiceContext(uncachedOrganizationService); uncachedXrmServiceContext.ContactSet.FirstOrDefault(x =&gt; x.Id == contactGuid); </code></pre>
How to set valueAxes title as variable from JSON in amCharts? <p>I would like to change the valueAxes title from a hardcoded string to a value from a JSON property via dataprovider.</p> <p>thanks </p>
<p>You can use the <code>init</code> event to set your valueAxes title then call <code>validateNow(true)</code> (or <code>validateData()</code>). Here's a contrived example:</p> <pre><code>var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "theme": "light", "dataProvider": [{ "valueAxisTitle": "Number of visits", //can be whatever property you want "country": "USA", "visits": 2025 }, // ... ] // ... "listeners": [{ "event": "init", "method": function(e) { e.chart.valueAxes[0].title = e.chart.dataProvider[0].valueAxisTitle; e.chart.validateNow(true); } }] }); </code></pre> <p><a href="http://codepen.io/team/amcharts/pen/5160dd97014545a325cfefc1cf9a978f?editors=0010" rel="nofollow">Demo</a></p>
I only want to update one MySQL row with PHP <p>I am working on a page that I need to be able to update single records from my MySQL database using PHP. Can someone please help me? When I try to update one record all my other records are updated.</p> <pre><code> &lt;form action="" method="post"&gt; &lt;input type="hidden" name="id" value="&lt;?php echo $id; ?&gt;"/&gt; &lt;div&gt; &lt;p&gt;&lt;strong&gt;ID:&lt;/strong&gt; &lt;?php echo $id; ?&gt;&lt;/p&gt; &lt;strong&gt;Name: *&lt;/strong&gt; &lt;input class="form-control" type="text" name="name" value="&lt;?php echo $name; ?&gt;" /&gt;&lt;br/&gt; &lt;strong&gt;Month: *&lt;/strong&gt; &lt;input class="form-control" type="text" name="month" value="&lt;?php echo $month; ?&gt;" /&gt;&lt;br/&gt; &lt;strong&gt;event1: *&lt;/strong&gt; &lt;input class="form-control" type="text" name="event1" value="&lt;?php echo $event1; ?&gt;" /&gt;&lt;br/&gt; &lt;strong&gt;event2: &lt;/strong&gt; &lt;input class="form-control" type="text" name="event2" value="&lt;?php echo $event2; ?&gt;" /&gt;&lt;br/&gt; &lt;strong&gt;event3: &lt;/strong&gt; &lt;input class="form-control" type="text" name="event3" value="&lt;?php echo $event3; ?&gt;" /&gt;&lt;br/&gt; &lt;strong&gt;event4: &lt;/strong&gt; &lt;input class="form-control" type="text" name="event4" value="&lt;?php echo $event4; ?&gt;" /&gt;&lt;br/&gt; &lt;strong&gt;timesub: &lt;/strong&gt; &lt;input class="form-control" type="text" name="timesub" value="&lt;?php echo $timesub; ?&gt;" readonly /&gt;&lt;br/&gt; &lt;p&gt;* Required&lt;/p&gt; &lt;input type="submit" name="submit" value="Submit" class="btn btn-info"&gt; &lt;input type=reset name="reset" value="Reset" class="btn btn-danger"&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>That is my form, and then I follow it with this code:</p> <pre><code> &lt;?php } include('db_connect.php'); if (isset($_POST['submit'])) { // confirm that the 'id' value is a valid integer before getting the form data if (is_numeric($_POST['id'])) { $id = $_POST['id']; $name = mysql_real_escape_string(htmlspecialchars($_POST['name'])); $month = mysql_real_escape_string(htmlspecialchars($_POST['month'])); $event1 = mysql_real_escape_string(htmlspecialchars($_POST['event1'])); $event2 = mysql_real_escape_string(htmlspecialchars($_POST['event2'])); $event3 = mysql_real_escape_string(htmlspecialchars($_POST['event3'])); $event4 = mysql_real_escape_string(htmlspecialchars($_POST['event4'])); $timesub = mysql_real_escape_string(htmlspecialchars($_POST['timesub'])); // check thatfields are filled in if ($name == '' || $month == '' || $event1 == '' || $timesub == ''){ // generate error message $error = 'ERROR: Please fill in all required fields!'; //error, display form renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, $error); } else { // save the data to the database mysql_query("UPDATE announcement SET name='$name', month='$month', event1='$event1', event2='$event2', event3='$event3', event4='$event4', timesub='$timesub'") or die(mysql_error()); // once saved, redirect back to the view page header("Location: view.php"); } } else { // if the 'id' isn't valid, display an error echo 'Error!'; } } else // if the form hasn't been submitted, get the data from the db and display the form {// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0) if (isset($_GET['id']) &amp;&amp; is_numeric($_GET['id']) &amp;&amp; $_GET['id'] &gt; 0) { // query db $id = $_GET['id']; $result = mysql_query("SELECT * FROM announcement WHERE id=$id") or die(mysql_error()); $row = mysql_fetch_array($result); // check that the 'id' matches up with a row in the databse if($row) { // get data from db $name = $row['name']; $month = $row['month']; $event1 = $row['event1']; $event2 = $row['event2']; $event3 = $row['event3']; $event4 = $row['event4']; $timesub = $row['timesub']; // show form renderForm($id, $name, $month, $event1, $event2, $event3, $event4, $timesub, ''); } else {// if no match, display result echo "No results!"; } } else {// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error echo 'Error!'; } } ?&gt; </code></pre> <p>I got the code from: <a href="http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/" rel="nofollow">http://www.killersites.com/community/index.php?/topic/1969-basic-php-system-vieweditdeleteadd-records/</a></p> <p>Great article!</p> <p>Thanks in advance for the help.</p>
<p>First of all stop using <code>mysql_*</code> its deprecated and closed in PHP 7. You can use <code>mysqli_*</code> or <code>PDO</code>.</p> <p>Whats wrong with your query:</p> <p>This is very important, if you not use <code>WHERE CLAUSE</code> in your <code>UPDATE STATEMENT</code> than it will update the all rows.</p> <p>You must need to add <code>WHERE CLAUSE</code> in your query at end, something like:</p> <pre><code>WHERE id = '$id' </code></pre> <p><em>Also note that, your code is open for SQL INJECTION, you must need to prevent with SQL INJECTION, you can learn about the prepared statement. This post will help you to understand: <a href="http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php">How can I prevent SQL injection in PHP?</a></em></p> <hr> <p>*If you want to know How <code>mysqli_*</code> <em>works, this document will help you: <a href="http://php.net/manual/en/book.mysqli.php" rel="nofollow">http://php.net/manual/en/book.mysqli.php</a></em></p> <p><em>If you want to work on PDO, you can follow this manual: <a href="http://php.net/manual/en/book.pdo.php" rel="nofollow">http://php.net/manual/en/book.pdo.php</a></em></p>
Waiting for multiple async operations in Nightwatch.js <p>I am attempting to test multiple sites for section headers being in the correct order. Of course everything is asynchronous in Nightwatch, including getting text from an element. The following code leads to the timeout never being called.</p> <pre><code>client.url(`www.oneofmyrealestatesites.com`); client.waitForElementPresent("body", 5000); var _ = require("underscore"); // This is the order I expect things to be in var expected = ["Homes For Sale", "New Homes", "Apartments &amp; Rentals"]; client.elements("css selector", ".listings .module-title .label", function (data) { var listings = []; data.value.forEach(function (element) { client.elementIdText(element.ELEMENT, function (result) { listings.push(result.value); }) }) setTimeout(function () { // Some of the sites have extra sections var diff = _.intersection(listings, expected); client.assert.ok(listings == diff); }, 5000); }); </code></pre> <p>It would appear that no matter how much delay I give, listings is ALWAYS empty. If I console.log listings as it's being pushed to, it <em>is</em> getting populated, so that's not the issue. <code>client.pause</code> is always ignored as well.</p> <p>Is there a way to make sure that listings is populated before asserting the diff?</p>
<p>I'm using <code>async</code> library for such cases <a href="https://github.com/caolan/async" rel="nofollow">https://github.com/caolan/async</a> Docs: <a href="https://github.com/caolan/async/blob/v1.5.2/README.md" rel="nofollow">https://github.com/caolan/async/blob/v1.5.2/README.md</a></p> <pre><code>var async = require("async"); /*use each, eachSeries or eachLimit - check docs for differences */ async.eachSeries(data.value, function (element, cb) { client.elementIdText(element.ELEMENT, function (result) { listings.push(result.value); // this job is done cb(); }); }, function() { // Some of the sites have extra sections var diff = _.intersection(listings, expected); client.assert.ok(listings == diff); }); </code></pre>
Javascript: pass method of object as pointer <p>Here is my code: </p> <pre><code>function active_area(width, t_width, height) { this.width = width; this.height = height; this.t_width = t_width; //width of toolbar this.dotes = 20; this.gridStep = this.width/this.dotes; this.active_layer = -1; this.layers_array = []; } active_area.prototype.init = function () { this.canvas = createCanvas(this.width+this.t_width, this.height); this.canvas.parent('mapper'); this.addButton(10, 10, 'Zoom out', this.zoomOut); this.addButton(10, 50, 'Zoom in', this.zoomIn); this.addButton(30, 30, 'Add layer', this.addLayer); this.drawGrid(); }; active_area.prototype.addButton = function(x, y, name, func){ var pos_x = this.width+x; var add_layer = createDiv(); add_layer.position(pos_x, height + y); add_layer.html('&lt;paper-button&gt;'+name+'&lt;/paper-button&gt;'); add_layer.mouseClicked(func); }; active_area.prototype.zoomOut = function () { console.log('zoom out'); console.log('dotes:'+this.dotes); this.dotes = this.dotes*2; console.log('dotes:'+this.dotes); redraw(); //this.drawGrid(); }; </code></pre> <p>Problem in a method zoomOut: i cann't access this.dotes from class active_area, drawGrid cann't access to. This method calls fine, listener works, but how to access class scope?</p>
<p>You need to bind it</p> <pre><code>this.addButton(10, 10, 'Zoom out', this.zoomOut.bind(this)); this.addButton(10, 50, 'Zoom in', this.zoomIn.bind(this)); this.addButton(30, 30, 'Add layer', this.addLayer.bind(this)); </code></pre>
C# How to read items into an array <p>I can't figure out how can I read items from the text file and put them into an int array. My objective is to count what is the average grade. To do so, I need to read the number which tells me how many grades does 1 student have, and then using that amount, read the grades themselves. For example, first column shows the amount of the grades, all remaining columns shows grades:</p> <p><code>5;8;7;9;10;4 3;8;9;10 2;5;9</code></p> <p>The code I wrote:</p> <pre><code> static void ReadData(out Student[] Student, out Faculty Faculty) { using (StreamReader read = new StreamReader(@"Data", Encoding.GetEncoding(1257))) { string line = null; Student = new Student[Faculty.CMax]; Faculty = new Faculty(); while (null != (line = read.ReadLine())) { string[] values = line.Split(';'); string lastname = values[0]; string name = values[1]; string group = values[2]; int amount = int.Parse(values[3]); int grades = int.Parse(values[4]); Student studen = new Student(lastname, name, group, amount, grades); Student.Take[Faculty.AmountOfStudents++] = studen; } } } </code></pre> <p>I know that <code>int[] grades = int.Parse(values[4]);</code> is the problem. But I don't know how to fix it. Probably a newbie problem, thanks for the help.</p>
<p>After your clarification, it seems that you want to take:</p> <pre><code>Smith;John;XYZ;4;2;4;6;8 </code></pre> <p>And retrieve the array of <code>[2,4,6,8]</code> so you can get the average from that.</p> <p>If you can't do what I mention in my comment, then here's a workaround. Since the number of grades is irrelevant, just ignore it, and you'll recognize that you need an int array which contains 4 fewer items than the original. Then it's just a matter of copying them:</p> <pre><code>string[] fields = val.Split(';'); int[] grades = new int[fields.Length - 4]; for (int i = 4; i &lt; fields.Length; ++i) { grades[i - 4] = int.Parse(fields[i]); } </code></pre> <p>Or some other alternate versions if you're into LINQ:</p> <pre><code>string[] fields = val.Split(';'); int[] grades = Enumerable.Range(4, fields.Length - 4) .Select(i =&gt; int.Parse(fields[i])) .ToArray(); string[] fields = val.Split(';'); int[] grades = fields.Select((s, i) =&gt; new { s, i }) .Where(x =&gt; x.i &gt;= 4) .Select(x =&gt; int.Parse(x.s)) .ToArray(); </code></pre>
Clearing All Hidden Cells in a Range <p>Very simple question. I keep getting error messages and excel crashing. What is wrong with my code:</p> <pre><code>Sub Clear() Dim c As Range For Each c In ActiveSheet.Range("HeatPump1").Cells If c.EntireRow.Hidden = True Then c.Clear End If Next c End Sub </code></pre>
<p>Which line is throwing an error? Do you have a range named "HeatPump1" in the active sheet when the code is running?</p> <p>On a side note, c.EntireRow.Hidden is a boolean value, so you don't need to check if it is true. You can simply write:</p> <pre><code> If c.EntireRow.Hidden Then </code></pre>
Why can't class variables be used in __init__ keyword arg? <p>I can't find any documentation on when exactly a class can reference itself. In the following it will fail. This is because the class has been created but not initialized until after <code>__init__</code>'s first line, correct?</p> <pre><code>class A(object): class_var = 'Hi' def __init__(self, var=A.class_var): self.var = var </code></pre> <p>So in the use case where I want to do that is this the best solution:</p> <pre><code>class A(object): class_var = 'Hi' def __init__(self, var=None) if var is None: var = A.class_var self.var = var </code></pre> <p>Any help or documentation appreciated!</p>
<p>Python scripts are interpreted as you go. So when the interpreter enters <code>__init__()</code> the class variable <code>A</code> isn't defined yet (you are inside it), same with <code>self</code> (that is a different parameter and only available in function body).</p> <p>However anything in that class is interpreted top to bottom, so <code>class_var</code> is defined so you can simply use that one.</p> <pre><code>class A(object): class_var = 'Hi' def __init__(self, var=class_var): self.var = var </code></pre> <p>but I am not super certain that this will be stable across different interpreters...</p>
Angular2 POST Web api 404 Not Found <p>I'm building an Angular2 service to log certain events, stored in ILog objects, and send them to an API to be stored in a database.</p> <p>My log service is pretty straightforward:</p> <pre><code>import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { EnvironmentModule } from "../environment"; import { ILog } from "./log"; @Injectable() export class LogService { constructor(private _http: Http, private environment: EnvironmentModule) { } postLog(log: ILog): void { this.json = this.convertToJSON(log); this._http.post(this.environment.getWebApiUri() + 'api/Log/PostLog/', log, {}) .subscribe( () =&gt; console.log('Success') ); //goes to localhost:3304/WebAPI/Log/PostLog/, returns 404 not found } } </code></pre> <p>And it calls a WebAPI Controller that passes the data off to a service to be processed:</p> <pre><code>[RoutePrefix("api/Log")] public class LogController : ApiController { private ILogService _LogService; public LogController() : this(new LogService()) { } //constructor public LogController(ILogService LogService) { _LogService = LogService; } //constructor [HttpPost()] [Route("PostLog")] public void PostLog(Log log) { _LogService.PostLog(log); } //PostLog } //class </code></pre> <p>Yet, when my service calls the API it throws a <code>404 Not Found</code> Error.</p> <p>Navigating to the path in the browser I see this:</p> <pre><code>&lt;Error&gt; &lt;Message&gt; No HTTP resource was found that matches the request URI 'http://localhost:3304/WebAPI/api/Log/PostLog/'. &lt;/Message&gt; &lt;MessageDetail&gt; No action was found on the controller 'Log' that matches the request. &lt;/MessageDetail&gt; &lt;/Error&gt; </code></pre> <p>Can anyone help me with this? I don't understand why it's behaving this way.</p>
<p>Its because you cant post an atomic value directly to your method as json. You could turn it into an object and then post it as a corresponding object or post it as form uri encoded which also works. This is a limitation of asp.net's web api. </p> <p>There are some other similar questions all with similar answers. Here is a quick example of how you could change it to work.</p> <p>c# code</p> <pre><code>[HttpPost()] [Route("PostLog")] public void PostLog(LogContainerModel logModel) { _LogService.PostLog(logModel.log); } // model public sealed class LogContainerModel { public string log { get; set; } } </code></pre> <p>javascript code</p> <pre><code>private convertToJSON(log: ILog): string { return JSON.stringify({log: log}); } </code></pre> <hr> <h1>Option 2</h1> <p>Stringify it as an object according to this previous <a href="http://stackoverflow.com/a/36572213/1260204">SO answer</a>.</p> <p>c# code</p> <pre><code>[HttpPost()] [Route("PostLog")] public void PostLog([FromBody] string jsonString) </code></pre> <p>javascript code</p> <pre><code>private convertToJSON(log: ILog): string { return JSON.stringify({'': log}); // if that does not work try the snippet below // return JSON.stringify({'': JSON.stringify(log)}); } </code></pre> <hr> <h2>Option 3</h2> <p>Here are some options from <a href="http://bizcoder.com/posting-raw-json-to-web-api" rel="nofollow">bizcoder.com</a></p> <p>Use <code>HttpResponseMessage</code></p> <pre><code>[HttpPost()] [Route("PostLog")] public async Task PostLog(HttpRequestMessage request) { var jsonString = await request.Content.ReadAsStringAsync(); _LogService.PostLog(jsonString); } </code></pre> <p>Or use <code>json.net</code></p> <pre><code>[HttpPost()] [Route("PostLog")] public void PostLog([FromBody]JToken jsonbody) { var jsonString = jsonbody.ToString(); _LogService.PostLog(jsonString); } </code></pre> <ul> <li><a href="http://stackoverflow.com/a/13771631/1260204">SO - How to post a single string (using form encoding)</a></li> <li><a href="http://stackoverflow.com/a/36572213/1260204">SO - send single string parameter</a> - this might be the better option, good answer.</li> </ul>
Aggregate messages without List <p>I'm using spring integration and I need to pack group of messages by 10k. I don't want to store it into List since later 10k could became much bigger and persistent storage is also not my choice. I just want that several threads send messages into single thread where I can count them and write into disk into files containing 10k lines. After counter reaches 10k I create new file set counter to zero and so on. It would work fine with direct channel but how to tell several threads(I'm using</p> <pre><code> &lt;int:dispatcher task-executor="executor" /&gt; </code></pre> <p>) to send messages into single thread? Thanks</p>
<p>You can reach the task with the <code>QueueChannel</code>. Any threads can send messages to it concurrently. On the other side you should just configure <code>PollingConsumer</code> with the <code>fixed-delay</code> poller - single-threaded, as you requested. I mean that poller with the <code>fixed-delay</code> and everything downstream with the <code>DirectChannel</code> will be done only in single thread. Therefore your count and rollover logic can be reached there.</p> <p>Nothing to show you, because that configuration is straight forward: different services send messages to the same <code>QueueChannel</code>. The <code>fixed-delay</code> poller ensures single-threaded reading for you.</p>
Support for .NET 4.6.2 in Azure Web Job <p>I tried deploying an Azure Web App built against .NET Framework 4.6.2 and it seems to work fine. However, within the same app, if I deploy a web job built against .NET 4.6.2, then it does not work. I get the following error:</p> <pre><code>[10/06/2016 19:42:25 &gt; b29283: SYS INFO] Status changed to Initializing [10/06/2016 19:42:27 &gt; b29283: SYS INFO] Run script 'Run.ps1' with script host - 'PowerShellScriptHost' [10/06/2016 19:42:27 &gt; b29283: SYS INFO] Status changed to Running [10/06/2016 19:42:31 &gt; b29283: INFO] Web job execution failed. Error code: -2146232576 [10/06/2016 19:42:31 &gt; b29283: SYS INFO] Status changed to Failed [10/06/2016 19:42:31 &gt; b29283: SYS ERR ] Job failed due to exit code -1 </code></pre> <p>Run.ps1 looks as follows:</p> <pre><code>[CmdletBinding()] Param() &amp; "$PSScriptRoot\ConsoleApplication1.exe" if ($lastexitcode -ne 0) { Write-Output "Web job execution failed. Error code: $lastexitcode" exit -1 } </code></pre> <p>ConsoleApplication1.exe just prints a line to console:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello from .NET 4.6.2"); } } } </code></pre> <p>When will the support for .NET framework 4.6.2 be added to Azure web jobs?</p>
<p>I created a console application using .NET Framework v4.6.2 and publish it as WebJob, and same issue appears on my side, the execution fails. So I guess that currently Azure WebJob does not support .NET Framework v4.6.2. As a workaround, you could try to modify <a href="https://msdn.microsoft.com/en-us/library/w4atty68(v=vs.110).aspx" rel="nofollow"><code>&lt;supportedRuntime&gt;</code> element</a> sku attribute in configuration file.</p> <pre><code>&lt;startup&gt; &lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" /&gt; &lt;/startup&gt; </code></pre> <p>Besides, you could give a feedback like <a href="https://feedback.azure.com/forums/169385-web-apps-formerly-websites/suggestions/11070060-webjobs-executables-fail-when-targeting-net-4-6-1" rel="nofollow">this</a>. </p>
Using CustomCredentialsAuthProvider in JsonServiceClient <p>I try to implement my own custom CredentialsAuthProvider. The server seems to work fine with the following implementation:</p> <pre><code>public class MyCustomCredentialsAuthProvider : CredentialsAuthProvider { public override bool TryAuthenticate(IServiceBase authService, string userName, string password) { if (userName == "testuser" &amp;&amp; password == "1234") { return true; } else { return false; } } public override IHttpResult OnAuthenticated(IServiceBase authService, IAuthSession session, IAuthTokens tokens, Dictionary&lt;string, string&gt; authInfo) { session.FirstName = "Testuser Joe Doe"; authService.SaveSession(session, SessionExpiry); return null; } } </code></pre> <p>When I call on my Browser <a href="http://localhost:8088/auth/credentials?UserName=testuser&amp;Password=1234" rel="nofollow">http://localhost:8088/auth/credentials?UserName=testuser&amp;Password=1234</a> I get back a page containing a session ID and the testuser Joe Doe. Looks fine.</p> <p>Now I try to call this from my Windows WPF client. I have created a Login Page and a LoginViewModel class since I implement the MVVM pattern. But I do not understand, what I really have to set the provider property in the Authenticate class to. </p> <p>In my WPF class I have the following:</p> <pre><code>public partial class App : Application { public JsonServiceClient ServiceClient { get; private set; } public App() { this.InitializeComponent(); } // .... } </code></pre> <p>And then in my LoginViewModel I have a Login() method which is a RelayCommand implementation of the login button like so (The form contains also a field where you have to enter the name of the application server since there is more than one. This is why I compose the baseUri in the handler):</p> <pre><code> private void Login() { var baseUri = $"http://{AppServer}:8088"; ((App)Application.Current).InitServiceClient(baseUri); var client = ((App) Application.Current).ServiceClient; //var response = client.Send&lt;AuthResponse&gt;(new Auth { UserName = "Test", Password = "TestPassword" }); var authResponse = client.Post(new Authenticate { provider = CredentialsAuthProvider.Name, // &lt;-- WHAT SHOULD THIS BE??? UserName = "testuser", Password = "1234", RememberMe = true, }); // .... } </code></pre> <p><code>CredentialsAuthProvider</code> is unknown by the compiler. What do I need to pass here and what assemblies do I need? So far I have:</p> <ul> <li>ServiceStack.Ckient</li> <li>ServiceStack.Interfaces</li> <li>ServiceStack.Text</li> <li>MyService.ServiceModel //DLL containing the DTOs etc., NO implementations</li> </ul> <p>What am I missing and doing wrong here?</p>
<p><a href="https://github.com/ServiceStack/ServiceStack/blob/501ad4c5b5f077956d94c4254d981b8e4e548381/src/ServiceStack/Auth/CredentialsAuthProvider.cs#L28" rel="nofollow">CredentialsAuthProvider.Name</a> just provides typed access to the <a href="https://github.com/ServiceStack/ServiceStack/blob/501ad4c5b5f077956d94c4254d981b8e4e548381/src/ServiceStack/Auth/AuthenticateService.cs#L27" rel="nofollow">"credentials"</a> string literal, which you can use in its place, e.g:</p> <pre><code>var authResponse = client.Post(new Authenticate { provider = "credentials", UserName = "testuser", Password = "1234", RememberMe = true, }); </code></pre> <p>You can find the list of <a href="https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization#auth-provider-routes" rel="nofollow">Auth provider literals</a> in the Authentication docs.</p>
How do I store only the folder names as an array and not the while path (C#) <p>So I know how to store the full path but not just the end folder names, for example I've already got an array but is there any method to remove certain characters from all arrays or just get folder names from a path?</p> <p>Edit: string[] allFolders = Directory.GetDirectories(directory); That's what I use to get all folder names but that gets me the whole path Edit:They need to be stored in an Array</p> <p>Edit: sorry , I need an array with values such as "mpbeach","blabla","keyboard" and not E:\Zmod\idk\DLC List Generator\DLC List Generator by Frazzlee\ , so basically not the full path</p>
<p>This works.</p> <pre><code>string[] allFolders = Directory.EnumerateDirectories(directory) .Select(d =&gt; new DirectoryInfo(d).Name).ToArray(); </code></pre> <p>This also works. Difference is we are using <code>List&lt;string&gt;</code> instead of <code>string[]</code></p> <pre><code>List&lt;string&gt; allFolders = Directory.EnumerateDirectories(directory) .Select(d =&gt; new DirectoryInfo(d).Name).ToList(); </code></pre> <h3>Example 1: Uses <code>string[] allFolders</code></h3> <h3>Test Folder</h3> <p><a href="http://i.stack.imgur.com/uUk5u.png" rel="nofollow"><img src="http://i.stack.imgur.com/uUk5u.png" alt="enter image description here"></a></p> <h3>In VS IDE, in Debug Mode</h3> <p><a href="http://i.stack.imgur.com/dpBIa.png" rel="nofollow"><img src="http://i.stack.imgur.com/dpBIa.png" alt="enter image description here"></a></p> <h3>Example 2: Uses <code>List&lt;string&gt; allFolders</code></h3> <h3>Test Folder</h3> <p><a href="http://i.stack.imgur.com/uUk5u.png" rel="nofollow"><img src="http://i.stack.imgur.com/uUk5u.png" alt="enter image description here"></a></p> <h3>In VS IDE, in Debug Mode</h3> <p><a href="http://i.stack.imgur.com/VM0Sx.png" rel="nofollow"><img src="http://i.stack.imgur.com/VM0Sx.png" alt="enter image description here"></a></p> <h3>Example 2: Uses <code>string[] allFolders</code></h3>
Aggregate in R taking way too long <p>I'm trying to count the unique values of x across groups y. </p> <p>This is the function:</p> <pre><code>aggregate(x~y,z[which(z$grp==0),],function(x) length(unique(x))) </code></pre> <p>This is taking way too long (~6 hours and not done yet). I don't want to stop processing as I have to finish this tonight.</p> <p><code>by()</code> was taking too long as well</p> <p>Any ideas what is going wrong and how I can reduce the processing time ~ 1 hour? My dataset has 3 million rows and 16 columns.</p> <p>Input dataframe z </p> <pre><code>x y grp 1 1 0 2 1 0 1 2 1 1 3 0 3 4 1 </code></pre> <p>I want to get the count of unique (x) for each y where grp = 0</p> <p>UPDATE: Using @eddi's excellent answer. I have</p> <pre><code> x y 1: 2 1 2: 1 3 </code></pre> <p>Any idea how I can quickly summarize this as the number of x's for each value y? So for this it will be </p> <pre><code>Number of x y 5 1 1 3 </code></pre>
<p>Here you go:</p> <pre><code>library(data.table) setDT(z) # to convert to data.table in place z[grp == 0, uniqueN(x), by = y] # y V1 #1: 1 2 #2: 3 1 </code></pre>
Finding clusters in a python list <p>I have a sorted python list which looks like:</p> <pre><code>myList = [1,2,3,7,8,9,12,13,14,15] </code></pre> <p>The consecutive elements with difference 1 form the cluster. I need to dig these clusters out.</p> <p>In the above example the clusters would be <code>1,2,3</code>; <code>7,8,9</code>; <code>12,13,14,15</code></p> <p>Is there a way other than to write a for loop and see where the difference between consecutive elements is > 1</p> <p>Edit: The list I have is large so I want to avoid using a for loop as much as I can unless that is the only way out</p>
<p>There are many approaches to do this. One is to create a new list to map the break-points where new group starts and create the nested list based on the break points.</p> <p><strong>Approach 1:</strong></p> <pre><code>my_list = [1,2,3,7,8,9,12,13,14,15] start, new_list = 0, [] for i in range(len(my_list) - 1): if my_list[i]+1 != my_list[i+1]: new_list.append(my_list[start: i+1]) start = i + 1 else: new_list.append(my_list[start: len(my_list)]) # Value of 'new_list': [[1, 2, 3], [7, 8, 9], [12, 13, 14, 15]] </code></pre> <p><strong>Approach 2:</strong> Little dirty one</p> <pre><code>l = [1,2,3,7,8,9,12,13,14,15] group =[i+1 for i in range(len(l)-1) if l[i]+1 != l[i+1]] group = group and ([0] + group + [len(l)]) new_list = [l[group[i]: group[i+1]] for i in range(len(group) -1)] # Value of 'new_list': [[1, 2, 3], [7, 8, 9], [12, 13, 14, 15]] </code></pre>
How to add files to android emulator <p>I am using the cordova filePicker plugin (MFilechooser), I see the filechooser from emulator (cordova emulate android). However, I don't know how to transfer a file from my PC to the emulator directory so I can select it.</p> <p>Can you please give me some suggestion on how to this action.</p> <p>Thanks</p>
<p>You can use <strong>adb</strong> comand line utility from Android SDK.<br/> Example of command:<br/> adb push /local/path/to/file/on/pc /path/to/file/in/emulator</p> <p>Substitute appropriate paths in example above.</p>
Why my redux-saga is async <p>In my React-Native app I write a user log in component which send username and hash to server, compare hash with hash in database and return a result. I implemented that <code>using redux-saga</code>:</p> <pre><code>function* fetchUser(action) { try { const user = yield call(Api.fetchUser, action); yield put({type: types.USER_FETCH_SUCCEEDED, user}); } catch (e) { yield put({type: types.USER_FETCH_FAILED, message: e.message}); } } export function* watchFetchUser() { yield* takeEvery(types.USER_FETCH_REQUESTED, fetchUser); } export default function* rootSaga() { yield fork(watchFetchUser); // ... } </code></pre> <p>And I expect that <code>const user</code> will contain response from API and after will run <code>yield put({type: types.USER_FETCH_SUCCEEDED, user})</code>. But after <code>yield call(Api.fetchUser, action)</code> <code>user</code> is <code>undefined</code>. But <code>Api.fetchUser</code> returns right response. </p> <p>And I can't find where is my mistake. Why result of <code>const user = yield call(Api.fetchUser, action)</code> is <code>undefined</code> when after <code>Api.fetchUser</code> return correct response?</p> <pre><code>fetchUser(action) { const url = `${apiUrls.LOGIN_URL}`; fetch(url, 'POST', action.user) .then(response =&gt; response.json()) .then(res =&gt; res) } </code></pre>
<p>You are not returning the promise from the fetchUser function. It should be</p> <pre><code>fetchUser(action) { const url = `${apiUrls.LOGIN_URL}`; return fetch(url, 'POST', action.user) .then(response =&gt; response.json()) .then(res =&gt; res) } </code></pre>
akka.net is there a a way to get or create actor <p>For my actor hierarchy, I do not know all the actors I need until I process the data through a few actors, so I'm looking for a way to either return an existing ActorRef or create a new action. This is what I would like the code below to either create an actor if one does not exist at "my-id-1" or return the one that already exists.</p> <pre><code>Context.ActorOf(MyActor.Props(message), "my-id-1"); </code></pre> <p>The above code will (as documented) throw a <code>InvalidActorNameException</code> if the actor already exists. How can I accomplish this in Akka.net?</p>
<p>You can check if current actor has a child with provided name by using <code>Context.Child(actorName)</code> method. It will return actor ref of the target actor if it exists or <code>ActorRefs.Nobody</code> if there is no such actor.</p> <p>Code in your case could look like:</p> <pre><code>var child = Context.Child(actorName); if (Equals(child, ActorRefs.Nobody)) child = Context.ActorOf(MyActor.Props(message), actorName); </code></pre>
Store CLLocation Manager Values in Device swift <p>I'm building an app that sends (every x seconds) to an API the location values with some extra values (session, ID, etc) that is working nice (see here <a href="http://stackoverflow.com/questions/39757134/update-cllocation-manager-on-another-method">Update CLLocation Manager on another method</a>). But for improved feature, we are considering the device can lost (for some amount of time) internet connection. So I need to temporary store all values and when reconnected send them again to the API.</p> <p>I'm considering several ways to do it:</p> <ul> <li>Core Data (difficult implementation)</li> <li>Realm (very little experience)</li> <li>NSDisctionary</li> </ul> <p>Can anyone suggest (and show how, if possible) the best way to implement this feature?</p>
<p>If you want to store a some of non-sensitive values (such as a password), I suggest to use <a href="https://developer.apple.com/reference/foundation/userdefaults" rel="nofollow">NSUserDefaults</a>, you can easily use it like a dictionary:</p> <p><em>Note: Swift 2 Code.</em></p> <p>For example:</p> <pre><code> // shared instance (singleton) let userDefaults = NSUserDefaults.standardUserDefaults() // **storing**: let myString = "my string" userDefaults.setObject(myString, forKey: "kMyString") let myInt = 101 userDefaults.setInteger(myInt, forKey: "kMyInt") let myBool = true userDefaults.setBool(myBool, forKey: "kMyBool") userDefaults.synchronize() // **retrieving**: //use optional binding for objects to check if it's nil if let myRetrievedString = userDefaults.objectForKey("kMyString") as? String { print(myRetrievedString) } else { // if it's nil print("there is now value for key: kMyString") } // if there is no value for key: kMyInt, the output should be zero by default let myRetrievedInt = userDefaults.integerForKey("kMyInt") // if there is no value for key: kMyBool, the output should be false by default let myRetrievedBool = userDefaults.boolForKey("kMyBool") </code></pre>
Django user permission inside template <p>I created a custom auth permission in django via admin site, and i added that permission to a user (not a group), now i want to ask if the request user in a template has it but nothing works.It's not a duplicate, i already checked similar questions and none of this work:</p> <pre><code>{% if perms.auth.add_something %} {% if 'auth.add_something' in request.user.get_all_permissions %} {% if request.user.has_perm('add_something') %} </code></pre> <p>I add my view:</p> <pre><code>class NotificationSelectView(View): template = 'myapp/notification_read.html' def get(self, request, *args, **kwargs): t = tree(request) req_var_list = [] analist = notifications_list(request.user) level = LevelProcess.objects.get( level_hierarchical = 3 ) subprocess= Process.objects.filter(level = level) user = request.user t.update({ 'subprocess': subprocess, 'analist':analist, }) return render(request, self.template, t) </code></pre> <p>The idea it's to make it inside template, not to use more code in views. Any ideas ?, thanks in advance.</p>
<p>django in template it uses the variable perms for the permissions of the logged in user so you can use inside template</p> <pre><code>{% if perms.auth.add_something %} {{do_smth}} {% endif %} </code></pre> <p>from the django documentation <a href="https://docs.djangoproject.com/el/1.10/topics/auth/default/#topic-authorization" rel="nofollow">https://docs.djangoproject.com/el/1.10/topics/auth/default/#topic-authorization</a> there is a section Authentication data in templates which describes also permissions in templates </p>
creating subset (using a col of data frame) using for loop and finding unique values of another column <p>I am new to R and am stuck up solving a problem. Could anyone point out where I have gone wrong I have the following data*</p> <pre><code> Score TestID 1536 2 16000 18000 1 15 7 1800 738 256 </code></pre> <p>There are 25000 Test IDs and each TestID has an associated score. In this case the score ranges from 0 to 16000. I need to plot a graph of the number of unique TestIDs that are present in a particular range i.e </p> <pre><code> ScoreRange # of unique TestId 0 - 16000 ? 10 - 16000 ? 20 - 16000 ? . . . . </code></pre> <p>I have written a code wherein I am considering a step size of 10 (for range) and finding out the unique TestIDs in that range. Though I have not come up to plotting, I am struggling to get the output in the format described above.</p> <pre><code> final &lt;- matrix(0, ncol = 2, nrow = length(seq(1,max(Combined$Score), 10))) for (i in seq(1,max(df$Score), 10)) { comp &lt;- subset(Combined, Score &gt;= i) unik &lt;- length(unique(comp$TestID)) final[,c(1,2)] &lt;- c(i,unik) } </code></pre> <p>I get a very weird output for final which is essentially two values repeating over. Where am I going wrong ? </p>
<p>EDIT: Your issue is that when you write the result of your for loop into the "final" matrix, you don't specify which row of the matrix to write the results to. To fix this, I create a "counter" variable, and set it equal to 0 before your for loop, then add 1 to it for each iteration of the loop. The counter indicates which row of the matrix to write the result to. Try this: </p> <pre><code>final &lt;- matrix(0, ncol = 2, nrow = length(seq(0,max(Combined$Score), 10))) counter&lt;-0 for (i in seq(0,max(df$Score), 10)) { counter&lt;-counter+1 comp &lt;- subset(df, Score &gt;= i) unik &lt;- length(unique(comp$TestID)) final[counter,c(1,2)] &lt;- c(i,unik) } </code></pre>
Laravel - check if other people are using my API and who <p>I have an API and I'm not sure if other services are using it too. I don't want other people to use my server resources and I would like to check that.</p> <ol> <li>Assuming I have a method in a controller, how I can check who accesses this method where the request is not from my domain?</li> <li>How I can allow connections only from my website/app and refuse from any other source?</li> </ol>
<p>Each request has a <code>Host</code> header you can use that to know which domain is using your service.</p> <p>if you want to only allow your domain to access the service then edit the <code>CORS</code> settings. I'm assuming you are using <a href="https://github.com/barryvdh/laravel-cors" rel="nofollow">barryvdh package</a></p> <p>in <code>config/cors.php</code></p> <p>change the value of</p> <pre><code>'allowedOrigins' =&gt; ['*'], </code></pre> <p>to your domain instead of * wildcard</p>
Divide every value in the rows by the corresponding value in the column head in r <p>I need to divide values in the rows by the corresponding values in the column head and then get the sum of each row</p> <p>I have this data as a csv file:</p> <pre><code>df &lt;- read.table(text = "Year 2 3 4 5 6 7 8 1985 0 4 0 4 0 0 0 1986 1 3 3 0 9 7 6 1987 5 0 0 0 0 0 8 1988 7 2 0 8 0 3 0 1989 0 0 0 1 0 2 0" , check.names = FALSE) </code></pre> <p>I am looking for this results </p> <pre><code>Year 2 3 4 5 6 7 8 SUM 1985 0 1.3 0 0.8 0 0 0 2.13 1986 0.5 1 0.75 0 1.5 1 0.75 5.5 1987 2.5 0 0 0 0 0 1 3.5 1988 3.5 0.6 0 1.6 0 0.4 0 6.19 1989 0 0 0 0.2 0 0.2 0 0.49 </code></pre> <p>Then I need to save the results as csv.</p>
<p>One approach, using <code>dplyr</code> just to clean up the code, is to use <code>apply</code> and convert the column names to numeric. Note that, because you changed the row.names to a column ("YEAR") we need to handle those separately. Here, I do it by removing that column with <code>df[ ,-1]</code> then adding it back at the end (here, with mutate, but you could do it separately as well).</p> <pre><code>apply(df[,-1], 1, function(x){ x / as.numeric(colnames(df)[-1]) }) %&gt;% t %&gt;% addmargins(2) %&gt;% data.frame(check.names = FALSE) %&gt;% mutate(YEAR = df$YEAR) %&gt;% select(YEAR, everything()) </code></pre> <p>Alternatively, and probably overkill for this example (but perhaps useful more broadly) is to use <code>tidyr</code> to convert to long first, which gives some potentially more flexible options for both control and summarizing:</p> <pre><code>df %&gt;% gather(head, val, -YEAR) %&gt;% mutate(divided = val / as.numeric(head)) %&gt;% select(-val) %&gt;% spread(head, divided) %&gt;% mutate(Sum = rowSums(.[ , -1])) </code></pre> <p>Both give the same values, in roughly similar formats.</p>
Unexpected behaviour in python multiprocessing <p>I'm trying to understand the following odd behavior observed using the <code>python mutiprocessing</code>.</p> <p>Sample testClass: import os import multiprocessing </p> <pre><code>class testClass(multiprocessing.Process): def __del__(self): print "__del__ PID: %d" % os.getpid() print self.a def __init__(self): multiprocessing.Process.__init__(self) print "__init__ PID: %d" % os.getpid() self.a = 0 def run(self): print "method1 PID: %d" % os.getpid() self.a = 1 </code></pre> <p>And a little test program: from testClass import testClass </p> <pre><code>print "Start" proc_list = [] proc_list.append(testClass()) proc_list[-1].start() proc_list[-1].join() print "End" </code></pre> <p>This produces:</p> <pre><code>Start __init__ PID: 89578 method1 PID: 89585 End __del__ PID: 89578 0 </code></pre> <p>Why it does not print <code>1</code>? </p> <p>I'm guessing that it's related to the fact that <code>run</code> is actually being executed on a different process as can be seen. If this is the expected behavior how is everyone using multiprocessing where processes have an expensive <code>__init__</code> as in processes that need to open a database?</p> <p>And shouldn't this behaviour be better highlighted in multiprocessing documentation?</p>
<p>You can wrap your expensive initialization inside a context manager:</p> <pre><code>def run(self): with expensive_initialization() as initialized_object: do_some_logic_here(initialized_object) </code></pre> <p>You will have a chance to properly initialize your object before calling <code>do_some_logic_here</code>, and to properly release the resources after leaving the context manager's block.</p> <p>See <a href="https://docs.python.org/3.6/reference/datamodel.html#context-managers" rel="nofollow">documentation</a>.</p>
How can I write a query to show details of customers with duplicate names? <p>I have been looking around for quite a bit and cannot seem to find a solution that fits what I need.</p> <p>I have a table with many, many customers and the issue is that there are many, many duplicates in this table.</p> <p>I have been able to show the customers that have duplicate records and the count of how many are in the table with that same name, but now I am trying to split this up and show all of their information so we can confirm that the customer is the correct one when we look them up.</p> <p>I was using this code:</p> <pre><code>SELECT COUNT(NAME), NAME FROM DEV.ALL_CUSTOMER GROUP BY NAME HAVING COUNT(NAME) &gt; 1; </code></pre> <p>Which gives results that show like this:</p> <pre><code>COUNT(NAME) | NAME ------------|------------------- 3 | Smith, John 2 | Doe, Jane 2 | Doe, Joe 2 | Smith, Jane </code></pre> <p>I then added in all of the informational fields I needed:</p> <pre><code>SELECT COUNT(NAME), NAME, TOTAL_PURCHASED, ADDRESS, CITY, STATE_PROV, POSTAL_CODE, COUNTRY, HOME_PHONE, WORK_PHONE, WORK_EXT, OTHER_PHONE, EMAIL_ADDRESS FROM DEV.ALL_CUSTOMER GROUP BY NAME, TOTAL_PURCHASED, ADDRESS, CITY, STATE_PROV, POSTAL_CODE, COUNTRY, HOME_PHONE, WORK_PHONE, WORK_EXT, OTHER_PHONE, EMAIL_ADDRESS HAVING COUNT(NAME) &gt; 1; </code></pre> <p>But this still has them grouped and does not show the information for each record:</p> <pre><code>COUNT(NAME) | NAME | TOTAL_PURCHASED | ADDRESS | CITY ... ------------|-------------|-----------------|---------|------- .. 3 | Smith, John | 0 | (null) | (null) .. 2 | Doe, Jane | 0 | (null) | (null) .. 2 | Doe, Joe | 0 | (null) | (null) .. </code></pre> <p>But I know for a fact that one of the five "John Smith" customers have purchased stuff.</p> <p>Instead, I would like the results to come out like this:</p> <pre><code>NAME | TOTAL_PURCHASED | ADDRESS | CITY ... ------------|-----------------|---------------|------- .. Smith, John | 250 | 123 Fake St. | (null) .. Smith, John | 0 | (null) | Oshawa .. Smith, John | 300 | (null) | Toronto . Doe, Jane | 0 | (null) | (null) .. Doe, Jane | 300 | 456 Fake St. | Toronto . Doe, Joe | 11235 | (null) | (null) .. Doe, Joe | 0 | (null) | (null) .. </code></pre>
<p>Use window functions:</p> <pre><code>SELECT c.* FROM (SELECT c.*, COUNT(*) OVER (PARTITION BY NAME) as cnt FROM DEV.ALL_CUSTOMER c ) c WHERE cnt &gt; 1 ORDER BY NAME; </code></pre> <p>This will give you the rows that are duplicated on <code>NAME</code>.</p>
Get query parameters in React, Typescript <p>I have a component that looks like this:</p> <pre><code>class MyView extends React.Component&lt;{}, {}&gt; { render() { console.log((this.props as any).params); // prints empty object return ( &lt;div&gt;Sample&lt;/div&gt; ); } } </code></pre> <p>I want to print the URL query params but I get an empty object. (Yes, I know that I declared {} as Props but if I don't define it, it does not compile).</p> <p>Is there a way to pass a "default" props object to my component so that I can access <code>this.props.params</code>? Or should it be done in a different way in TypeScript?</p>
<p>You need to define the types for the props and state and then put them instead of the <code>{}</code>.<br> It's not clear where you want to get the "URL query params", so I'll just take them from the <code>window.location</code> object:</p> <pre><code>interface MyViewProperties { params: string; } interface MyViewState {} class MyView extends React.Component&lt;MyViewProperties, MyViewState&gt; { render() { console.log(this.props.params); // should print "param1=value1&amp;param2=value2...." return ( &lt;div&gt;Sample&lt;/div&gt; ); } } ReactDOM.render(&lt;MyView props={ window.location.search.substring(1) } /&gt;, document.getElementById("container")); </code></pre>
How to auto wrap function call in try / catch? <p>I have a lot of getter functions like this:</p> <pre><code>get_property_a(default=None): try: self.data.get("field_1")[0].get("a") except Exception as e: return default get_property_b(default=None): try: self.data.get("field_2")[0].get("b") except Exception as e: return default ... </code></pre> <p>Is there a way to not wrapping all the getters in try/except? It would be nice if it is some kind of annotation like this:</p> <pre><code>@silent_exec(default=None) def get_property_b(): self.data.get("field_2")[0].get("b") </code></pre> <p>Thanks</p>
<p>You <em>can</em> do this by writing your own decorator:</p> <pre><code>import functools def silent_exec(default=None): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs): except Exception: return default return wrapper return decorator </code></pre> <p>With that said, I'd be <em>very</em> wary of using this. You should <em>very rarely</em> be catching <em>all</em> exceptions (as we've done here). Normally you it's better to specify a tuple of exceptions that you actually expect and know how to handle...</p> <pre><code>import functools def silent_exec(exceptions, default=None): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs): except exceptions: return default return wrapper return decorator @silent_exec((IndexError, KeyError), default=None) def get_property_b(): self.data.get("field_2")[0].get("b") </code></pre> <p>This way, you don't end up catching/silencing <em>programming</em> errors -- those will still get raised, you can look at them in the logs or wherever they get reported and you can go back in and fix them.</p>
Arduino function variable value changes between function calls <p>I have three functions, each calls the next and passes some values. Strangely, in second function where I make multiple calls to third function, one of the values changes between the calls. And this variable is for sure local. Am I missing Something?</p> <pre><code>void functionA(...){ //Something... int i=1,j=1,k=2; functionB(i,j,k); } void functionB(int i,int j,int k){ String X=""; Serial.print(i);//Gives 1 if(j==1) X="hello world"; functionC(i,j,k,X);//Call 1 to functionC Serial.print(i);//Gives 0 !!!!!!!!!!!!!!!!!!!!!!!! if(j==2) X="hello world2"; functionC(i,j,k,X);//Call 2 to functionC } void functionC(int i, int j, int k, String X){ if(i) //Do something else //Do somethingelse } </code></pre> <p>My experiments </p> <pre><code>void functionC(int i, int j, int k, String X){ //Print i here. No difference with the result. if(i) //Do something else //Do somethingelse //But if I Print i here again, then it is working. As in, "i" does not change anymore. between each call to functionC } </code></pre>
<p>Either you're passing some pointers around or functionC is doing some funky stuff with memory. Other than those two options, there's no real reason I can see why a value in a variable would simply change like in your example.</p>
see RAM usage in R-studio before crash? <p>I am switching from Python to R for some projects, and I have a hard time understanding the RAM management in R - R-Studio.</p> <p>I have the following two simple questions</p> <ul> <li><p>can we see how much RAM is being used by R at the moment? Just like in Spyder one can see that, say, 20% of the current RAM is full. That will allow me to understand if I can move one with my code, or if a memory crash is close.</p></li> <li><p>do I need to set-up a maximum amount of RAM that R can use or everything is automatic like in Python (where Spyder eats RAM as it needs it)</p></li> </ul> <p>Many thanks!</p>
<p>Check <code>gc()</code> to check how much memory is being used.</p> <p>And I think R uses all the memory available. However, you can also set the memory limit by <code>memory.limit(size=)</code>. </p> <p>Moreover, I would recommend using <a href="https://mran.microsoft.com/open/" rel="nofollow">Microsoft R Open</a> It boosts the calculations speed as it introduces some parallel processing. Check out other Microsoft Client R and Server R as well. </p>
Why is the height of li larger than the height of the image inside it? <p>On hovering a top level li element of my navigation bar,</p> <p><a href="http://i.stack.imgur.com/a9dSC.png" rel="nofollow">I see that small space beneath the image inside the li element</a></p> <p>This bugs me when I don't define a background color for my li element because we can see that the menu subitem below seems not linked to the li element.</p> <p>By using Chrome's debugger, I found that the heights of the li and img elements are different :</p> <p><a href="http://i.stack.imgur.com/FZK6B.png" rel="nofollow">this screenshot shows the height of the li element and the image inside it</a></p> <p>I tried to find any default padding or margin values put on the li element but could not find any so I have no other clue where that space come from.</p> <p>Please note that I have disable the spacing of my UL with this css code :</p> <pre><code>nav ul { list-style: none; margin: 0; padding: 0px; } </code></pre> <p>Can you explain why this space is present and tell how to remove that unwanted space [on the li element]?</p>
<p>It's because images are inline elements, to fix this add <code>display: block;</code> to the image then use <code>margin: 0 auto;</code> to center it inside the <code>li</code>.</p>