input
stringlengths
51
42.3k
output
stringlengths
18
55k
How to properly do null checks using Kotlin extension functions on an Android Activity <p>I'm new to Kotlin and trying to convert one of the many Android Util methods we have in our existing codebase into a Kotlin extension function.</p> <p>This is the Kotlin code:</p> <pre><code>fun Activity?.isAlive(): Boolean { return !(this?.isFinishing ?: false) } </code></pre> <p>Which is meant to be the equivalent of this Java method:</p> <pre><code>public static boolean isAlive(Activity activity) { return activity != null &amp;&amp; !activity.isFinishing(); } </code></pre> <p>However, I'm still getting <code>NPEs</code> in the Kotlin code whenever an <code>Activity</code> is <code>null</code>. Any thoughts on where I'm going wrong?</p>
<p>I suppose you get NPE not in the <code>isAlive()</code> function but somewhere after, when the <code>Activity</code> is referenced. This is likely caused by the fact that <code>.isAlive()</code> returns <code>true</code> on <code>null</code> receiver.</p> <p>That's because if the receiver is <code>null</code>, <code>this?.isFinishing ?: false</code> chooses the right branch <code>false</code>, thus <code>!(this?.isFinishing ?: false)</code> is <code>true</code>.</p> <p>Try changing your function in either way so that it returns <code>false</code> on <code>null</code> receiver, for example:</p> <pre><code>fun Activity?.isAlive(): Boolean = !(this?.isFinishing ?: true) </code></pre>
R ggplot2: Add means as horizontal line in a boxplot <p>I have created a boxplot using ggplot2:</p> <pre><code>library(ggplot2) dat &lt;- data.frame(study = c(rep('a',50),rep('b',50)), FPKM = c(rnorm(1:50),rnorm(1:50))) ggplot(dat, aes(x = study, y = FPKM)) + geom_boxplot() </code></pre> <p>The boxplot shows the median as a horizontal line across each box. </p> <p><a href="https://i.stack.imgur.com/n3P8I.png" rel="nofollow"><img src="https://i.stack.imgur.com/n3P8I.png" alt="enter image description here"></a></p> <p>How do I add a dashed line to the box representing the mean of that group?</p> <p>Thanks!</p>
<p>You can add horizontal lines to plots by using <code>stat_summary</code> with <code>geom_errorbar</code>. The line is horizontal because the y minimum and maximum are set to be the same as y.</p> <pre><code>ggplot(dat, aes(x = study, y = FPKM)) + geom_boxplot() + stat_summary(fun.y = mean, geom = "errorbar", aes(ymax = ..y.., ymin = ..y..), width = .75, linetype = "dashed") </code></pre> <p><a href="https://i.stack.imgur.com/f9S5B.png" rel="nofollow"><img src="https://i.stack.imgur.com/f9S5B.png" alt="enter image description here"></a></p>
Wrap integers in quotes from json data <p>I created <a href="http://stackoverflow.com/questions/40110706/regex-wrap-all-integers-in-double-quotes">this question yesterday</a></p> <p>I've since realised there are actually a few other bits of data that cause issues with the solutions I received. Hence, I thought it best to make a new question</p> <p>Take the following example data;</p> <p><code>"87",0000,0767,"078",0785,"0723",23487, "061 904 5284","17\/10\/2016","[email protected]"</code></p> <p>Using the accepted solution form above <code>(?&lt;!")(\b\d+\b)(?!")</code></p> <p>The date string ends up having the middle number in between the two <code>\/</code> wrapped, the number in quotes with spaces breaks as well as the email address. The issues can be seen here: <a href="https://regex101.com/r/qVQYA7/6" rel="nofollow">https://regex101.com/r/qVQYA7/6</a></p> <p><strong>My Solution</strong></p> <p>The following does seem to work for me, however it seems a bit messy. I have a feeling there's a much more succinct way to achieve the same result;</p> <p><code>,(?&lt;!("|\/|\\))(\b\d+\b)(?!("|\/|\\|( \d)))</code> Replace with <code>,"$2"</code></p> <p><a href="https://regex101.com/r/qVQYA7/5" rel="nofollow">https://regex101.com/r/qVQYA7/5</a></p>
<p>By reading your both questions, what I understand is that you want to wrap in double quots some numbers that aren't, so for this I can come up with a simple regex like this:</p> <pre><code>(?&lt;=,)(\d+)(?=,) </code></pre> <p>With the replacement string: <code>"$1"</code></p> <p><strong><a href="https://regex101.com/r/qVQYA7/7" rel="nofollow">Working demo</a></strong></p> <p><a href="https://i.stack.imgur.com/daDGJ.png" rel="nofollow"><img src="https://i.stack.imgur.com/daDGJ.png" alt="enter image description here"></a></p>
How to create a subset of document using lxml? <p>Suppose you have an lmxl.etree element with the contents like:</p> <pre><code>&lt;root&gt; &lt;element1&gt; &lt;subelement1&gt;blabla&lt;/subelement1&gt; &lt;/element1&gt; &lt;element2&gt; &lt;subelement2&gt;blibli&lt;/sublement2&gt; &lt;/element2&gt; &lt;/root&gt; </code></pre> <p>I can use find or xpath methods to get something an element rendering something like:</p> <pre><code>&lt;element1&gt; &lt;subelement1&gt;blabla&lt;/subelement1&gt; &lt;/element1&gt; </code></pre> <p>Is there a way <em>simple</em> to get:</p> <pre><code>&lt;root&gt; &lt;element1&gt; &lt;subelement1&gt;blabla&lt;/subelement1&gt; &lt;/element1&gt; &lt;/root&gt; </code></pre> <p>i.e The element of interest plus all it's ancestors up to the document root?</p>
<p>I am not sure there is something built-in for it, but here is a terrible, "don't ever use it in real life" type of a workaround using the <a href="http://lxml.de/api/lxml.etree._Element-class.html#iterancestors" rel="nofollow"><code>iterancestors()</code> parent iterator</a>:</p> <pre><code>from lxml import etree as ET data = """&lt;root&gt; &lt;element1&gt; &lt;subelement1&gt;blabla&lt;/subelement1&gt; &lt;/element1&gt; &lt;element2&gt; &lt;subelement2&gt;blibli&lt;/subelement2&gt; &lt;/element2&gt; &lt;/root&gt;""" root = ET.fromstring(data) element = root.find(".//subelement1") result = ET.tostring(element) for node in element.iterancestors(): result = "&lt;{name}&gt;{text}&lt;/{name}&gt;".format(name=node.tag, text=result) print(ET.tostring(ET.fromstring(result), pretty_print=True)) </code></pre> <p>Prints:</p> <pre><code>&lt;root&gt; &lt;element1&gt; &lt;subelement1&gt;blabla&lt;/subelement1&gt; &lt;/element1&gt; &lt;/root&gt; </code></pre>
How to set page size with rave report <p>I have a project in Delphi 2010 and I'm using RaveReport to generate PDF reports through the code, my question is I want to know if it is possible and how can I set the size (height and width) of my PDF page.</p> <p>I tried it but did not resulted:</p> <pre><code>var PWidth: Double; PWidth := 20; System.BaseReport.PageWidth := PWidth; </code></pre> <p>And tried this:</p> <pre><code>System.BaseReport.SetPaperSize(DMPAPER_USER, 2100, 1400); </code></pre> <p>Any solution?</p>
<p>Solution for my problem:</p> <pre><code>procedure TfrmLogger.RvSystemBeforePrint(Sender: TObject); begin with Sender as TBaseReport do begin Units := unInch; UnitsFactor := 1; SetPaperSize(DMPAPER_USER, 21, 29.7); Units := unCM; UnitsFactor := 2.54; end; end; </code></pre>
Keras getting wrong output shape <p>For the following CNN </p> <pre><code>model = Sequential() model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 256, 256))) # now model.output_shape == (None, 64, 256, 256) # add a 3x3 convolution on top, with 32 output filters: model.add(Convolution2D(32, 3, 3, border_mode='same')) # now model.output_shape == (None, 32, 256, 256) print(model.summary()) </code></pre> <p>However model summary gives the following output</p> <pre><code>____________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ==================================================================================================== convolution2d_44 (Convolution2D) (None, 3, 256, 64) 147520 convolution2d_input_24[0][0] ____________________________________________________________________________________________________ convolution2d_45 (Convolution2D) (None, 3, 256, 32) 18464 convolution2d_44[0][0] ==================================================================================================== Total params: 165984 </code></pre> <p>Why am i getting the given output shape ?</p>
<p>It is a problem caused by the setting of <code>input_shape</code>. In your current setting, you want to input 256x256 with 3 channels. However, Keras thinks you are giving 3x256 image with 256 channels. There several ways to correct it.</p> <ul> <li><p>Option 1: Change the order in <code>input_shape</code></p></li> <li><p>Option 2: Specify <code>image_dim_ordering</code> in your layers</p></li> <li><p>Option 3: Modify the keras configuration file by changing 'tf' to 'th' in your ~/.keras/keras.json</p></li> </ul>
Get attribute's name by it's value <p>I need to return the key with a known <code>value</code> from my model.</p> <pre><code>f = Foo.find_by(name: "dave") #= returned object: {id: 1, name: "dave", age: 32} f.key("dave") # expected :name or name </code></pre> <p>This <code>value</code> will be unique. How to get the attribute? Am I asking the right question?</p> <p>What is the difference with this, please?</p> <pre><code>hash = { "a" =&gt; 100, "b" =&gt; 200, "c" =&gt; 300, "d" =&gt; 300 } hash.key(200) #=&gt; "b" </code></pre>
<p><code>f</code> is an instance of <code>Foo</code> class, which inherits from <code>ActiveRecord::Base</code>, it is not a <code>Hash</code> instance.</p> <p>To get the attribute's name by it's value (using <code>key</code>), you have to get a hash of <code>f</code>'s <a href="http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods.html#method-i-attributes" rel="nofollow">ActiveRecord::AttributeMethods#<code>attributes</code></a> first:</p> <pre><code>f.attributes.key('dave') # `attributes` method returns a Hash instance #=&gt; "name" </code></pre> <blockquote> <p>What is the difference</p> </blockquote> <p>To sum up: the difference in the instance methods defined in the object's class.</p>
Set this for required arrow-functions <p>I'm trying to set <code>this</code> in various scenarios.</p> <p>The following code executed in node.js <code>v6.8.1</code> will print what is commented at the end of each line: </p> <pre><code>function requireFromString(src) { var Module = module.constructor; var m = new Module(); m._compile(src, __filename); return m.exports; } (function(){ var f1 = (() =&gt; {console.log(this.a === 1)}); var f2 = function(){ console.log(this.a === 1) }; var f3 = requireFromString('module.exports = (() =&gt; {console.log(this.a === 1)});'); var f4 = requireFromString('module.exports = function(){ console.log(this.a === 1) };'); console.log('Body:'); console.log(this.a === 1); // true (()=&gt;console.log(this.a === 1))(); // true (()=&gt;console.log(this.a === 1)).call(this); // true (function(){console.log(this.a === 1)})(); // false (function(){console.log(this.a === 1)}).call(this); // true console.log('\nFunctions:'); f1(); // true f1.call(this); // true f2(); // false f2.call(this); // true f3(); // false [1] f3.call(this); // false [2] f4(); // false f4.call(this); // true }).apply({a:1}); </code></pre> <p>With the documentation for <a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/this" rel="nofollow">this</a> and <a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this" rel="nofollow">arrow functions</a> I can explain all cases except the ones labelled with <code>[1]</code> and <code>[2]</code>.</p> <p>Can somebody shed some light on the observed behaviour? And maybe give a hint how I can call <code>f3</code> so that the function prints true.</p> <hr> <p><strong>Notes</strong></p> <ul> <li>The <code>requireFromString</code>-function is adapted from <a href="https://stackoverflow.com/questions/17581830/load-node-js-module-from-string-in-memory">Load node.js module from string in memory</a> and is just a hack to slim down this stackoverflow question. In practice this is replaced by an ordinary <code>require(...)</code></li> </ul>
<p>The reason is because "fat arrow functions" always take their <code>this</code> lexically, from the surrounding code. They <strong><em>cannot</em></strong> have their <code>this</code> changed with <code>call</code>, <code>bind</code>, etc. Run this code as an example:</p> <pre><code>var object = { stuff: 'face', append: function() { return (suffix) =&gt; { console.log(this.stuff + ' '+suffix); } } } var object2 = { stuff: 'foot' }; object.append()(' and such'); object.append().call(object2, ' and such'); </code></pre> <p>You will only see <code>face and such</code>.</p> <p>So, as far as why that doesn't work in the case of <code>f3</code>, it's because it's a self-contained module being required. Therefore, it's base-level arrow functions will only use the <code>this</code> in the module, they cannot be bound with <code>bind</code>, <code>call</code>, etc etc as discussed. <strong>In order to use <code>call</code> on them, they must be regular functions, not arrow functions.</strong></p> <hr> <p>What does "lexical <code>this</code>" mean? <em>It basically works the same as a closure.</em> Take this code for example:</p> <p>fileA.js:</p> <pre><code>(function () { var info = 'im here!'; var infoPrintingFunctionA = function() { console.log(info); }; var infoPrintingFunctionB = require('./fileB'); infoPrintingFunctionA(); infoPrintingFunctionB(); })(); </code></pre> <p>fileB.js:</p> <pre><code>module.exports = function() { console.log(info); }; </code></pre> <p>What will be the result? An error, <code>info is not defined</code>. Why? Because the accessible variables (the scope) of a function only includes the variables that are available <em>where the function is defined</em>. Therefore, <code>infoPrintingFunctionA</code> has access to <code>info</code> because <code>info</code> exists in the scope where <code>infoPrintingFunctionA</code> is defined.</p> <p>However, even though <code>infoPrintingFunctionB</code> is being <em>called</em> in the same scope, it was not <em>defined</em> in the same scope. Therefore, it cannot access variables from the calling scope.</p> <p>But this all has to do with the variables and closures; what about <code>this</code> and arrow functions?</p> <p><strong>The <code>this</code> of arrow functions works the same as the closure of other variables in functions</strong>. Basically, an arrow function is just saying to include <code>this</code> in the closure that is created. And in the same way you couldn't expect the variables of fileA to be accessible to the functions of fileB, you can't expect the <code>this</code> of the calling module (fileA) to be able to be referenced from the body of the called module (fileB).</p> <p>TLDR: How do we define "surrounding code", in the expression "lexical <code>this</code> is taken from the surrounding code?" The surrounding code is the scope where the function is defined, not necessarily where it is called.</p>
How do I display my Wordpress custom field attribute in the excerpt of my Algolia Search page results? <p>I'm currently using Algolia's Search plugin within Worpdress. I've managed to push some custom fields and their values to custom attributes within Algolia. Now, I'm trying to include a custom attribute named 'program_description' in my search results. </p> <p>By default, the search is only returning the value of the 'post_title' and 'content' attributes. I'm interested in replacing the 'content' attribute output with with my custom attribute's output('program_description').</p> <p>I thought I would simply modify the instantsearch.php template by adding 'program_description' to the attributes array like so:</p> <pre><code>&lt;div class="ais-hits--content"&gt; &lt;h3 itemprop="name headline"&gt;&lt;a href="{{ data.permalink }}" title="{{ data.post_title }}" itemprop="url"&gt;{{{ data._highlightResult.post_title.value }}}&lt;/a&gt;&lt;/h3&gt; &lt;div class="ais-hits--tags"&gt; &lt;# for (var index in data.taxonomies.post_tag) { #&gt; &lt;span class="ais-hits--tag"&gt;{{{ data._highlightResult.taxonomies.post_tag[index].value }}}&lt;/span&gt; &lt;# } #&gt; &lt;/div&gt; &lt;div class="excerpt"&gt; &lt;p&gt; &lt;# var attributes = ['program_description', 'content', 'title6', 'title5', 'title4', 'title3', 'title2', 'title1']; var attribute_name; var relevant_content = ''; for ( var index in attributes ) { attribute_name = attributes[ index ]; if ( data._highlightResult[ attribute_name ].matchedWords.length &gt; 0 ) { relevant_content = data._snippetResult[ attribute_name ].value; } } relevant_content = data._snippetResult[ attributes[ 0 ] ].value; #&gt; {{{ relevant_content }}} &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>In doing so, none of my results are returned and I'm met with the following console error: <code>Uncaught TypeError: Cannot read property 'matchedWords' of undefined</code></p> <p>Any help would be greatly appreciated.</p>
<p><code>Cannot read property 'matchedWords' of undefined</code> tells me that your custom parameter for <code>attributes</code> may not be defined in the scope of Algolia. </p> <p>I would suggest initializing <a href="https://www.algolia.com/doc/api-client/php/parameters#attributestoindex" rel="nofollow"><code>attributesToIndex</code></a> with your custom attributes (or any attributes you'll be using)- that way you can ensure that <a href="https://www.algolia.com/doc/api-client/php/parameters#attributestohighlight" rel="nofollow"><code>attributesToHighlight</code></a> has definitions to work with.</p> <p>Check out this <a href="http://stackoverflow.com/a/40044950/6836841">answer</a>~ it might help shed light on why you're getting an <code>undefined</code> definition for your custom attribute while trying to access the <code>matchedWords</code> member of your <code>_highlightResult</code> object.</p>
How to tell Python to save files in this folder? <p>I am new to Python and have been assigned the task to clean up the files in Slack. I have to backup the files and save them to the designated folder Z drive Slack Files and I am using the open syntax below but it is producing the permission denied error for it. This script has been prepared by my senior to finish up this job.</p> <pre><code>from slacker import * import sys import time import os from datetime import timedelta, datetime root = 'Z:\Slack_Files' def main(token, weeks=4): slack = Slacker(token) total = slack.files.list(count=1).body['paging']['total'] num_pages = int(total/1000.00 + 1) print("{} files to be processed, across {} pages".format(total, num_pages)) files_to_delete = [] ids = [] count = 1 for page in range(num_pages): print ("Pulling page number {}".format(page + 1)) files = slack.files.list(count=1000, page=page+1).body['files'] for file in files: print("Checking file number {}".format(count)) if file['id'] not in ids: ids.append(file['id']) if datetime.fromtimestamp(file['timestamp']) &lt; datetime.now() - timedelta(weeks=weeks): files_to_delete.append(file) print("File No. {} will be deleted".format(count)) else: print ("File No. {} will not be deleted".format(count)) count+=1 print("All files checked\nProceeding to delete files") print("{} files will be deleted!".format(len(files_to_delete))) count = 1 for file in files_to_delete: # print open('Z:\Slack_Files') print("Deleting file {} of {} - {}".format(count, len(files_to_delete), file["name"])) print(file["name"]) count+=1 return count-1 for fn in os.listdir(r'Z:\Slack_Files'): if os.path.isfile(fn): open(fn,'r') if __name__ == "__main__": try: token = '****' except IndexError: print("Usage: python file_deleter.py api_token\nPlease provide a value for the API Token") sys.exit(2) main(token) </code></pre> <p>The error it displays is:</p> <pre><code>Traceback (most recent call last): File "C:\Users\Slacker.py", line 55, in &lt;module&gt; main(token) File "C:\Users\Slacker.py", line 39, in main print open('Z:\Slack_Files') IOError: [Errno 13] Permission denied: 'Z:\\Slack_Files' </code></pre>
<p>To iterate over files in a particular folder, we can simply use os.listdir() to traverse a single tree.</p> <pre><code>import os for fn in os.listdir(r'Z:\Slack_Files'): if os.path.isfile(fn): open(fn,'r') # mode is r means read mode </code></pre>
How to restrict IMEI number to only 15 digits without counting space after 4 digits <p>I have input field for imei number which should take only 15 digits that should only be numbers. Which I have done, my code below takes only 15 digits and leaves a space after 4 digits.</p> <p>But the main problem I am facing here is if you hold any number it will take 18 digits. because when we type fast it is couting spaces also. Here is fiddle link to <strong><a href="http://jsfiddle.net/1zLwgf66/" rel="nofollow">try here</a></strong></p> <p>IMEI </p> <pre><code>$(".imei").on('keyup', function() { var foo = $(this).val().split(" ").join(""); if (foo.length &gt; 0) { foo = foo.match(new RegExp('.{1,4}', 'g')).join(" "); } $(this).val(foo); }); $(".imei").keydown(function (e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A (e.keyCode == 65 &amp;&amp; e.ctrlKey === true) || // Allow: Ctrl+C (e.keyCode == 67 &amp;&amp; e.ctrlKey === true) || // Allow: Ctrl+X (e.keyCode == 88 &amp;&amp; e.ctrlKey === true) || // Allow: home, end, left, right (e.keyCode &gt;= 35 &amp;&amp; e.keyCode &lt;= 39)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode &lt; 48 || e.keyCode &gt; 57)) &amp;&amp; (e.keyCode &lt; 96 || e.keyCode &gt; 105)) { e.preventDefault(); } }); </code></pre>
<p>Change <code>keyup</code> to <code>keypress</code>:</p> <pre><code>$(".imei").on('keypress', function() { </code></pre> <p><code>keyup</code> will only fire when you let go of the key, while <code>keypress</code> will fire every time the key is sent to the input.</p> <p>Keep the <code>keydown</code> code as it's used to limit what's allowed.</p> <p>Updated fiddle:<a href="http://jsfiddle.net/1zLwgf66/1/" rel="nofollow">http://jsfiddle.net/1zLwgf66/1/</a></p> <hr> <p>The problem with <code>keypress</code> is that it occurs <em>before</em> the key has been sent to the input. You can get around this by adding the key to the input before running your code, or waiting until the default code has completed, by adding a simple setTimeout. With setTimeout, you'll have closure issues, so you need to copy <code>this</code>:</p> <pre><code>$(".imei").on('keypress', function() { var inp = this; setTimeout(function() { var foo = $(inp).val().split(" ").join(""); </code></pre> <p>Updated fiddle: <a href="http://jsfiddle.net/1zLwgf66/2/" rel="nofollow">http://jsfiddle.net/1zLwgf66/2/</a></p>
Enable/disable multiple textbox generated by row number of input data <p>Code:</p> <pre><code>&lt;?php include('conect.php'); $result = mysqli_query($conn,"SELECT * FROM `op` WHERE `type` = 2 ;"); echo "&lt;table class='table table-striped table-hover'id='datatables-example'&gt; &lt;tr&gt; &lt;td class='pure-table'&gt;&lt;b&gt;Title 1&lt;/b&gt;&lt;/td&gt; &lt;td class='pure-table'&gt;&lt;b&gt;Title 2&lt;/b&gt;&lt;/td&gt; &lt;td class='pure-table'&gt;&lt;b&gt;Check 1&lt;/b&gt;&lt;/td&gt; &lt;td class='pure-table'&gt;&lt;b&gt;Title 3&lt;/b&gt;&lt;/td&gt; &lt;td class='pure-table'&gt;&lt;b&gt;VCheck 2&lt;/b&gt;&lt;/td&gt; &lt;/tr&gt;"; while($row = mysqli_fetch_array($result)) { echo "&lt;tbody data-link='row' class='rowlink'&gt; &lt;tr&gt; &lt;td&gt;' . $row['Op'] . '&lt;/td&gt; &lt;td&gt; &lt;input type='text' name='T2' class='form-control'&gt; &lt;td style='text-align:center;'&gt; &lt;input type='checkbox' name='C1' id='C1' &gt; &lt;td&gt; &lt;input type='text' name='T3' id='T3' class='form-control' disabled &gt; &lt;td style='text-align:center;'&gt; &lt;input type='checkbox' name='C2'&gt; &lt;/tr&gt; &lt;/tbody&gt; } &lt;/table&gt;"; mysqli_close($conn); ?&gt; &lt;script language ="JavaScript"&gt; document.getElementById('C1').onchange = function() { document.getElementById('T3').disabled = !this.checked; }; </code></pre> <p></p> <p>I need help to solve my problem. I want Enable/disable multiple textbox generated by row number of input data. The first row works fine but the other lines not. what i do wrong?</p>
<p>None of your <code>&lt;td&gt;</code> tags are closed in the second row.</p>
Redis for session handling of symfony applications deployed on Apache httpd <p>I am new to PHP, Symfony and Redis and have a query around integration of Redis with a symfony project deployed on Apache httpd as the server for session management.</p> <p>The below is the software's and their versions that I am using</p> <p>OS - CentOS 7 Redis - 3.2.4 - Built Redis from the source code Symfony - 2.8 PHP 7 - Installed the below packages </p> <ul> <li>php70w </li> <li>php70w-cli</li> <li>php70w-common</li> <li>php70w-fpm</li> <li>php70w-opcache</li> <li>php70w-pdo</li> <li>php70w-pear</li> <li>php70w-process</li> <li>php70w-xml</li> <li>php70w-pecl-redis</li> </ul> <p>I have made the below entries in <strong>php.ini</strong> file </p> <pre><code>session.save_handler = redis session.save_path = "tcp://&lt;&lt;ip address of redis server&gt;&gt;:6379" session.auto_start = 1 </code></pre> <p>What is confusing me is do I have to write session management through my symfony code using phpredis client or should it happen automatically. </p> <p>Please let me know which method I should use to go further as the redis server does not seem to be populated with the session.</p> <p>All the above configurations have been done by referring the below link and has been made centos specific</p> <p><a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-a-redis-server-as-a-session-handler-for-php-on-ubuntu-14-04" rel="nofollow">https://www.digitalocean.com/community/tutorials/how-to-set-up-a-redis-server-as-a-session-handler-for-php-on-ubuntu-14-04</a></p> <p>Thanks.</p>
<p>You have to change default session handler. To omit Symfony session handler and use PHP instead set the <code>handler_id</code> option to null in <code>settings.yml</code>:</p> <pre><code>framework: session: handler_id: null </code></pre> <p><a href="http://symfony.com/doc/current/reference/configuration/framework.html#handler-id" rel="nofollow">http://symfony.com/doc/current/reference/configuration/framework.html#handler-id</a></p>
Async Json feed finishing later than AyncTasks to load data from sqllite DB. How to sync them or better solution? <p>Async Json feed finishing later than AyncTasks to load data from sqllite DB. How to sync them or any better solution ?</p> <p>I searched StackOverFlow but could not find this peculiar problems like mine.</p> <p>In my app, All data is shown to the user from sqllite DB, which is present in mobile itself. Data in sqlite DB is created using AsyncTask JSON feed on click of buttons. In one case of mine, AsyncTask to download data is kicked off in background but user had already landed in list fragment to see data. To ensure that user is not waiting for download to finished, i implemented this also in Async task. Now, this Async task to show data finished much before Async data to download and insert. This means that user always see old data and have to come back to see new data. Any solution for this peculiar problem would be appreciated. Thanks.</p>
<p>I am able to fix this by implementing Handler as talking mechanism between two Async tasks. I took help of this post. Once a DB inserts are over in Async Task then I am sending message to the called program to reset the Adapter of List. Thanks to everyone for help in this. <a href="http://stackoverflow.com/a/26139605/5845259">http://stackoverflow.com/a/26139605/5845259</a></p>
Entity Framework Code First navigation property through relational table <p>I'm trying to setup some navigation properties with some Entity Framework Code First models. I'd like them to look like this example:</p> <pre><code>public class Course { [Key] public int CourseId { get; set; } public string CourseName { get; set; } public virtual ICollection&lt;Student&gt; Students { get; set; } } public class Student { [Key] public int StudentId { get; set; } public string StudentName { get; set; } public virtual ICollection&lt;Course&gt; Courses { get; set; } } public class StudentCourses { [Key, Column(Order = 0)] public int StudentId { get; set; } public virtual Student Student { get; set; } [Key, Column(Order = 1)] public int CourseId { get; set; } public virtual Course Course { get; set; } } </code></pre> <p>So Student and Course relationships would be established in the StudentCourses table. An instance of the student class would automatically reference all of that students courses, and vice versa an instance of the Course class would automatically reference all of its Students. And an instance of the StudentCourses class would automatically reference its Student and Course. But when I try to Update-Database, the relationships don't seem to get properly interpreted. Is there anything I'm missing here? Perhaps some configuring needs to be done in the context class? Most of the examples of navigation properties just show one-to-many relationship navigation properties.</p>
<p>You need to construct your models as shown below when you have a <code>M : M</code> relationship. You don't need to construct junction table. EF will create one for you when you do the data migration.</p> <p><strong>Model configuration using Conventions.</strong></p> <pre><code>public class Student { public Student() { this.Courses = new HashSet&lt;Course&gt;(); } public int StudentId { get; set; } public string StudentName { get; set; } public virtual ICollection&lt;Course&gt; Courses { get; set; } } public class Course { public Course() { this.Students = new HashSet&lt;Student&gt;(); } public int CourseId { get; set; } public string CourseName { get; set; } public virtual ICollection&lt;Student&gt; Students { get; set; } } </code></pre> <p>Your context class should be like this.</p> <pre><code>public class YourDBContext : DBContext { public YourDBContext () : base("Default") { } public DbSet&lt;Student&gt; Students { get; set; } public DbSet&lt;Course&gt; Courses { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } } </code></pre>
Read data from different directories using Firebase for Android <pre><code>/users: - user1 - name: user1name - /contacts - user2 - user3 ..... - user2 - name: user2name .... </code></pre> <p>This is my current firebase database. When user1 is logged in I check which contacts he has and get their UIDs. Now that I have their UIDs I'm trying to read the names of his contacts. How can I get the names for each of his contacts? Do I have to read the entire /users directory or can I use a query that retrieves only the data that I want. (In this case: the name of user2 and user3)</p>
<p>Supposing that you already have the user selected, you can go about it in two ways: 1) Use <code>.child(String user);</code> in your database reference. 2) You may have declared a URL for your database. Add <code>+ "/" + String user;</code> to your URL.</p> <p>You can further use these ways to parse through contacts of that user.</p>
check if an window closed in angularjs <p>I need to check if an window is closed or not. Here is my example,</p> <p>I have opened a new window by calling this function,</p> <pre><code>$scope.openwind= function(){ $scope.popupWindow = $window.open("index.html#/channelintegration", "SOme Title", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no'); } </code></pre> <p>Then I have been checking if the opened window (popupWindow) is closed or not, by calling below function through a button click,</p> <pre><code>$scope.checkmywindow=function(){ console.log($scope.popupWindow); console.log($scope.popupWindow.closed); } </code></pre> <p>Now, I need to check if the window (popupWindow) is closed or not, without the button trigger. </p> <p>Pls Help on this.. Thanks..</p>
<p>You can check if the <code>window is opened or not</code>, by taking <code>window.open</code> function in a scope variable and check using the scope.</p> <pre><code>$scope.openwind= function(){ $scope.popupWindow = $window.open("index.html#/channelintegration", "SOme Title", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no'); } $scope.closewind= function(){ if ($scope.popupWindow) { $scope.popupWindow.close(); } // code for closing goes here } $scope.checkmywindow=function(){ if (!$scope.popupWindow) { document.getElementById("msg").innerHTML = "'$scope.popupWindow' has never been opened!"; } else { if ($scope.popupWindow.closed) { document.getElementById("msg").innerHTML = "'$scope.popupWindow' has been closed!"; } else { document.getElementById("msg").innerHTML = "'$scope.popupWindow' has Opened!"; } } } </code></pre> <p><a href="http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_closed" rel="nofollow">Check this link and implement</a></p>
Run an executable file through a batch file which is situated in a remote location <p>Say, I am in directory <strong>D:\Users\S\Documents\ files\test_batch</strong> and now I want to create a batch file in this directory to run a .exe file named test.exe which is situated in location <strong>D:\Users\S\Documents\s\examples\c</strong> . I want to run the test.exe file inside the c folder. How can I do this using batch file? I have tried in the following way but it is not working.</p> <pre><code>cd D:\Users\S\Documents\s\examples\c &amp;&amp; test.exe </code></pre> <p>How can i do this?</p>
<p>Try this:</p> <pre><code>pushd D:\Users\S\Documents\s\examples\c test.exe popd </code></pre> <p>The commands 'pushd' and 'popd' are used to maintain a "last in/first out" stack of current directories.</p>
Quadruple nested child elements in FactoryGirl <p>I'm trying to create dummy data with FactoryGirl. </p> <p>User has many posts, post has many videos, video has many comments. Comment belong to video and user. Video belongs to post and user. Post belongs to user.</p> <p>I would like to create at least 20 users, each with at least 10 posts, each post with at least 1 video, each video with at least 1 comment.</p> <p>Thus far I have the following factories however I can't seem to get the videos or comments to work.</p> <h1>spec/factories/comments.rb</h1> <pre><code>FactoryGirl.define do factory :comment do sequence(:body) { |n| "#{n}body" } video user end end </code></pre> <h1>spec/factories/posts.rb</h1> <pre><code>FactoryGirl.define do factory :post do sequence(:title) { |n| "#{n}title" } date Date.today.strftime('%m/%d/%Y') body Faker::Lorem.paragraph(3) tags Faker::Lorem.words(4) user trait :with_videos do after(:build) do |post| create(:video, post: post) end end end end </code></pre> <h1>spec/factories/users.rb</h1> <pre><code>FactoryGirl.define do factory :user do first_name Faker::Name.first_name last_name Faker::Name.last_name sequence(:username) { |n| "#{n}username" } sequence(:email) { |n| "#{n}[email protected]" } phone Faker::PhoneNumber.phone_number password Faker::Internet.password(6, 20) country Faker::Address.country state Faker::Address.state_abbr city Faker::Address.city zip Faker::Address.zip seeking_coach true accept_email true accept_phone true end end </code></pre> <h1>spec/factories/videos.rb</h1> <pre><code>FactoryGirl.define do factory :video do sequence(:title) { |n| "#{n}title" } sequence(:url) { |n| "https://www.youtube.com/watch?v=tYm_#{n}2oCVdSM" } embed_id { "#{url}.split('=').last" } post user trait :with_comments do after(:build) do |video| create(:comment, video: video) end end end end </code></pre>
<p>I think in factories hook should be <code>after(:create)</code> instead of <code>after(:build)</code>, e.g.:</p> <pre><code>after(:create) do |video| create(:comment, video: video) end </code></pre> <p>Here is all updated factories:</p> <p><strong>spec/factories/users.rb</strong></p> <pre><code>FactoryGirl.define do factory :user do first_name Faker::Name.first_name last_name Faker::Name.last_name sequence(:username) { |n| "#{n}username" } sequence(:email) { |n| "#{n}[email protected]" } phone Faker::PhoneNumber.phone_number password Faker::Internet.password(6, 20) country Faker::Address.country state Faker::Address.state_abbr city Faker::Address.city zip Faker::Address.zip seeking_coach true accept_email true accept_phone true trait :with_10_posts do after(:create) do |user| create_list(:post, 10, :with_videos, user: user) end end end end </code></pre> <p><strong>spec/factories/posts.rb</strong></p> <pre><code>FactoryGirl.define do factory :post do sequence(:title) { |n| "#{n}title" } date Date.today.strftime('%m/%d/%Y') body Faker::Lorem.paragraph(3) tags Faker::Lorem.words(4) user trait :with_videos do after(:create) do |post| create(:video, :with_comments, post: post) end end end end </code></pre> <p><strong>spec/factories/videos.rb</strong></p> <pre><code>FactoryGirl.define do factory :video do sequence(:title) { |n| "#{n}title" } sequence(:url) { |n| "https://www.youtube.com/watch?v=tYm_#{n}2oCVdSM" } post trait :with_comments do after(:create) do |video| create(:comment, video: video) end end end end </code></pre> <p><strong>spec/factories/comments.rb</strong></p> <pre><code>FactoryGirl.define do factory :comment do sequence(:body) { |n| "#{n}body" } video end end </code></pre> <p>And RSpec test to ensure that factories setup works:</p> <pre><code>describe 'Factories' do it 'creates 20 users, each with at least 10 posts, each post with at least 1 video, each video with at least 1 comment' do FactoryGirl.create_list(:user, 20, :with_10_posts) expect(User.count).to eq(20) user = User.take expect(user.posts.count).to be &gt;= 10 post = user.posts.take expect(post.videos.count).to be &gt;= 1 video = post.videos.take expect(video.comments.count).to be &gt;= 1 end end </code></pre> <p>Here is all the code - <a href="https://github.com/shhavel/stackoverflow_question_40136020" rel="nofollow">https://github.com/shhavel/stackoverflow_question_40136020</a></p>
Is there some feature in Visual Studio Team Services that can notify automatically when something has changed in files you monitor? <p>Is there some feature in Visual Studio Team Services (TFS) that can notify automatically when something has changed in files you work with? </p> <p>Lets say I have client-side angular app that uses client-server object models mappings to communicate with server-side code. If something is changed in C# models, on a client-side there is no way to know that.</p> <p>Any ideas?</p>
<p>Yes, you can define Checkin alerts directly in the TFS configuration. These alert notifications are then sent out by mail.</p> <p>For example you can set an alert if someone (perhaps other than yourself) does a checkin of specific files or in a specific directory. The possible criteria of the alert can be formulated in a pretty sophisticated way.</p> <p>The alerts themselves can be made visible just for you or for all team members.</p> <p>You can read more about the configuration of the alerts <a href="https://www.visualstudio.com/docs/work/track/alerts-and-notifications" rel="nofollow">here</a>.</p>
Ipython cv2.imwrite() not saving image <p>I have written a code in python opencv. I am trying to write the processed image back to disk but the image is not getting saved and it is not showing any error(runtime and compilation) The code is</p> <pre><code>""" Created on Wed Oct 19 18:07:34 2016 @author: Niladri """ import numpy as np import cv2 if __name__ == '__main__': import sys img = cv2.imread('C:\Users\Niladri\Desktop\TexturesCom_LandscapeTropical0080_2_S.jpg') if img is None: print 'Failed to load image file:' sys.exit(1) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) h, w = img.shape[:2] eigen = cv2.cornerEigenValsAndVecs(gray, 15, 3) eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2] #flow = eigen[:,:,2] iter_n = 10 sigma = 5 str_sigma = 3*sigma blend = 0.5 img2 = img for i in xrange(iter_n): print i, gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) eigen = cv2.cornerEigenValsAndVecs(gray, str_sigma, 3) eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2] x, y = eigen[:,:,1,0], eigen[:,:,1,1] print eigen gxx = cv2.Sobel(gray, cv2.CV_32F, 2, 0, ksize=sigma) gxy = cv2.Sobel(gray, cv2.CV_32F, 1, 1, ksize=sigma) gyy = cv2.Sobel(gray, cv2.CV_32F, 0, 2, ksize=sigma) gvv = x*x*gxx + 2*x*y*gxy + y*y*gyy m = gvv &lt; 0 ero = cv2.erode(img, None) dil = cv2.dilate(img, None) img1 = ero img1[m] = dil[m] img2 = np.uint8(img2*(1.0 - blend) + img1*blend) #print 'done' cv2.imshow('dst_rt', img2) cv2.waitKey(0) cv2.destroyAllWindows() #cv2.imwrite('C:\Users\Niladri\Desktop\leaf_image_shock_filtered.jpg', img2) for i in xrange(iter_n): print i, gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY) eigen = cv2.cornerEigenValsAndVecs(gray, str_sigma, 3) eigen = eigen.reshape(h, w, 3, 2) # [[e1, e2], v1, v2] x, y = eigen[:,:,1,0], eigen[:,:,1,1] print eigen gxx = cv2.Sobel(gray, cv2.CV_32F, 2, 0, ksize=sigma) gxy = cv2.Sobel(gray, cv2.CV_32F, 1, 1, ksize=sigma) gyy = cv2.Sobel(gray, cv2.CV_32F, 0, 2, ksize=sigma) gvv = x*x*gxx + 2*x*y*gxy + y*y*gyy m = gvv &lt; 0 ero = cv2.erode(img, None) dil = cv2.dilate(img, None) img1 = dil img1[m] = ero[m] img2 = np.uint8(img2*(1.0 - blend) + img1*blend) print 'done' #cv2.imwrite('D:\IP\tropical_image_sig5.bmp', img2) cv2.imshow('dst_rt', img2) cv2.waitKey(0) cv2.destroyAllWindows() #cv2.imshow('dst_rt', img2) cv2.imwrite('C:\Users\Niladri\Desktop\tropical_image_sig5.bmp', img2) </code></pre> <p>Can anyone please tell me why it is not working. cv2.imshow is working properly(as it is showing the correct image). Thanks and Regards Niladri</p>
<p>As a general and absolute rule, you <em>have</em> to protect your windows path strings (containing backslashes) with <code>r</code> prefix or some characters are interpreted (ex: <code>\n,\b,\v,\x</code> aaaaand <code>\t</code> !):</p> <p>so when doing this:</p> <pre><code>cv2.imwrite('C:\Users\Niladri\Desktop\tropical_image_sig5.bmp', img2) </code></pre> <p>you're trying to save to <code>C:\Users\Niladri\Desktop&lt;TAB&gt;ropical_image_sig5.bmp</code></p> <p>(and I really don't know what it does :))</p> <p>Do this:</p> <pre><code>cv2.imwrite(r'C:\Users\Niladri\Desktop\tropical_image_sig5.bmp', img2) </code></pre> <p>Note: the read works fine because "escaped" uppercase letters have no particular meaning in python 2 (<code>\U</code> has a meaning in python 3)</p>
Selecting nested Li elements <p>What am I doing wrong here I can't seem to target the nested list elements. I tried using a class called 'second-level' on the 2nd level of the unordered list, but it won't seem to work. Here's the bit of code that I want to effect my nested li elements: <code>.second-level li { background-color: #cf1a2b; display: block; padding: 0; margin: 0; text-align: center; padding: 10px 0; }</code> and Here's my code: <strong>HTML CODE</strong></p> <pre><code> &lt;div class="col-sm-8"&gt; &lt;ul class="top-level"&gt; &lt;li&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Products&lt;/a&gt; &lt;ul class="second-level"&gt; &lt;li id='brand'&gt;Ze&lt;span&gt;bra&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;img src="img/tie.png" alt="tie"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Asics shoes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Nike air free&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Sports Jerseys&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Nike Air Max&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Nike Shox shoes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Nike AF1 shoes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Asics shoes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Nike air free&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Shopping&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;li id="cart"&gt;&lt;a href="#"&gt;&lt;img src="img/cart.png" alt="Cart"&gt;&lt;p&gt;$35.00&lt;/p&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- end of col-sm-8 --&gt; &lt;/div&gt;&lt;!-- end of row --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>CSS CODE</strong></p> <pre><code> /****************** HEADER **********************/ .top-level { list-style-type: none; padding: 0; margin: 0; position: absolute; } .top-level &gt; li { height: auto; padding: 15px 0; display: inline-block; position: relative; vertical-align: middle; font-size: 18px; font-family: 'Helevitca Neue'; text-align: center; cursor: pointer; width: 149px; background: #fff; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; -ms-transition: all 0.2s; -o-transition: all 0.2s; transition: all 0.2s; } .top-level &gt; li:hover { background-color: #cf1a2b; } .top-level a { color: #626262; } .header li:hover a { text-decoration: none; color: #fff; } #cart p { display: inline; } .top-level li &gt; ul { background: #cf1a2b; position: absolute; top: 100%; left: 0; width: 100%; padding: 0; list-style-type: none; } .second-level li { background-color: #cf1a2b; display: block; margin: 0; text-align: center; padding: 10px 0; } li#brand { font-family: 'Helevitca Neue'; font-size: 38px; color: #fff; text-transform: uppercase; border: 1px solid #fff; border-left: none; } #brand span { color: #fec8cd; } </code></pre> <p><a href="https://i.stack.imgur.com/snWkm.png" rel="nofollow"><img src="https://i.stack.imgur.com/snWkm.png" alt="No effect from css code on nested li elements"></a></p>
<p>The issue was that I had an extra <code>*/</code> before the css code that affected the nested li elements, which prevented the change. </p> <pre><code>/*-webkit-transiton: opacity 0.2s; -moz-transition: opacity 0.2s; -ms-transition: opacity 0.2s; -o-transition: opacity 0.2s; -transition: opacity 0.2s;}*/ */ .second-level li { background-color: #cf1a2b; display: block; margin: 0; text-align: center; padding: 20px 0; } </code></pre>
Linking libraries opencv cmake <p>I am trying to link my library and opencv library. Cmake is working properly, solution is build but linker error occurs. It seems as cmake couldnt link opencv lib with my library. </p> <p><a href="https://i.stack.imgur.com/aAulM.jpg" rel="nofollow">This is an error which visual studio has.</a></p> <p><a href="https://i.stack.imgur.com/Cyqj4.jpg" rel="nofollow">CMakeLists configuration for opencv lib</a></p> <p>This is piece of CMakeLists conf responsible for linking libs.</p> <pre><code># link libs target_link_libraries(${APP_NAME} ${OpenCV_LIBS}) </code></pre> <p>I would be very grateful for you help.</p>
<p>CMakeLists.txt I use for OpenCV apps configuring.</p> <pre><code>cmake_minimum_required(VERSION 2.8) set (PROJ_NAME YourAppName) project(${PROJ_NAME}) set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/build) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}) set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}) FIND_PACKAGE(OpenCV) set(folder_source main.cpp ) set(folder_header main.h ) SOURCE_GROUP("Source Files" FILES ${folder_source}) SOURCE_GROUP("Header Files" FILES ${folder_header}) ADD_EXECUTABLE(${PROJ_NAME} ${folder_source} ${folder_header}) TARGET_LINK_LIBRARIES(${PROJ_NAME} ${OpenCV_LIBS} ) </code></pre> <p>it works fine, but check your opencv path does not contain spaces </p> <p>(it does not like paths like "C:/Documents/Visual Studio 2015/Projects/opencv_build").</p>
What does T::* signify in the declaration of a function parameter list? <p>I declare a particular keyboard callback function as this inside my code:</p> <pre><code>void keyboardEventCallback(const pcl::visualization::KeyboardEvent &amp;event, void* viewer_void, void* widget_void); </code></pre> <p>The keyboard event is the actual event passed to the callback function, the viewer_void parameter is a pointer to a PCLVisualizer class that generates a window for rendering, and widget_void is a pointer to a widget that interfaces with Qt. </p> <p>In the documentation for pcl, a registration function passes the arguments for registering the keyboard function like </p> <pre><code>boost::signals2::connection registerKeyboardCallback(void(T::*callback)(const pcl::visualization::KeyboardEvent&amp;, void*), T&amp; instance, void* cookie=nullptr) </code></pre> <p>So my question is, <strong>what is the meaning of <code>T::*</code> inside the registration function declaration</strong>, and <strong>why am I not allowed to pass this:</strong></p> <pre><code>m_vis-&gt;registerKeyboardCallback(keyboardEventCallback, (void*)&amp;m_vis, (void*)this); </code></pre> <p>where <code>m_vis</code> is a visualizer, <code>keyboardcallback</code> is the callback, and this is the widget.</p> <p>Why can I not register like this. This is for the point cloud library.</p>
<blockquote> <p>what is the meaning of T::* inside the registration function declaration</p> </blockquote> <p>This is the syntax of a pointer to member. Let's take a look at the whole type and name of the parameter:</p> <pre><code>void(T::*callback)(const pcl::visualization::KeyboardEvent&amp;, void*) </code></pre> <p>This is the declaration of a variable named <code>callback</code>. It's a <em>pointer to member function</em>. More precisely, it's a pointer to member function of the class <code>T</code>.</p> <p>If we take the name out of the type, we see things more clearly:</p> <pre><code>// class name ---v v------- parameters void(T::*)(const pcl::visualization::KeyboardEvent&amp;, void*) // ^---- return type </code></pre> <p>It's in fact, a pointer to function member of the class <code>T</code> that return <code>void</code>. It's a function that take <em>strictly</em> two parameter: a <code>const pcl::visualization::KeyboardEvent&amp;</code> and a <code>void*</code>.</p> <blockquote> <p>why am I not allowed to pass this</p> </blockquote> <p>It's simple. Look at the type of your function:</p> <pre><code>using func_type = decltype(keyboardEventCallback); // hint: the type is: void(*)(const pcl::visualization::KeyboardEvent&amp;, void*, void*) </code></pre> <p>Let's compare the two types side by side:</p> <pre><code>void(*)(const pcl::visualization::KeyboardEvent&amp;, void*, void*) void(T::*)(const pcl::visualization::KeyboardEvent&amp;, void*) </code></pre> <p>First, your function is not a member function, it's a plain function pointer. It's not the same type. Then, you got three arguments, as the type of the parameter only ask for two. This is different.</p> <hr> <p><strong>Now, how can you fix this??</strong></p> <p>You could use a lambda:</p> <pre><code>auto myCallback = [](const pcl::visualization::KeyboardEvent&amp; e, void* c) { /* ... */ } using lambdaType = decltype(myCallback); // Be careful here, we don't want our lambda to go out of scope when it is called. m_vis-&gt;registerKeyboardCallback(&amp;lambdaType::operator(), myCallback, this); </code></pre> <hr> <p>Or even simpler: just define <code>keyboardEventCallback</code> inside your class, and send it:</p> <pre><code>// don't forget: keyboardEventCallback must receive the same parameter as asked. m_vis-&gt;registerKeyboardCallback(&amp;MyClass::keyboardEventCallback, *this, this); </code></pre>
How can I block or redirect traffic referred to my site by another site? <p>I have a domain that is being sent traffic from another domain with a similar name by a scammer who is trying to look legitimate. (the scammer is masquerading as my legitimate client) </p> <p>How can I block or redirect traffic referred to my site by another site?</p> <p>i.e. any traffic that is referred from IP address xxx.xxx.xxx.xxx should be either denied or more appropriately referred to a disclaimer page. </p> <p>I've tried .htaccess mod_rewrite rules, but the apache logs don't show the referring ip address. that only appears in the "general" section of the headers when examined using chrome developer tools. </p> <p>can this be done using .htaccess or mod_security</p>
<p>There are a couple of methods you can use, <strong>IF</strong> you know the IP address you can use:</p> <p><code>deny from xxx.xxx.x.xx</code></p> <p>However, you can actually block directly from a referring website using:</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_REFERER} example\.com [NC] RewriteRule .* - [F] </code></pre> <p>This will display a <strong>403forbidden</strong> message if anyone is redirected via the scammers website.</p>
how do i find my ipv4 using python? <p>my server copy it if you want! :) how do i find my ipv4 using python? can i you try to keep it real short?</p> <pre><code>import socket def Main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.bind((host,port)) s.listen(1) c1, addr1 = s.accept() sending = "Connection:" + str(addr1) connection = (sending) print(connection) s.listen(1) c2, addr2 = s.accept() sending = "Connection:" + str(addr2) connection = (sending) print(connection) while True: data1 = c1.recv(1024).decode('utf-8') data2 = c2.recv(1024).decode('utf-8') if not data1: break if not data2: break if data2: c1.send(data2.encode('utf-8')) if data1: c2.send(data1.encode('utf-8')) s.close() if __name__== '__main__': Main() </code></pre> <p>thx for the help i appreciate it!</p>
<p>That's all you need for the local address (returns a string):</p> <pre><code>socket.gethostbyname(socket.gethostname()) </code></pre>
Symfony forms: does it omits a `false` `attr`? <p>I want to know in <code>JavaScript</code> if a particular feature is active or not.</p> <p>I have a <code>PHP</code> class that has some <code>has*</code> methods.</p> <p>So, in <code>Twig</code> I do this:</p> <pre><code>{{ form_widget(form.plan.seo, {'attr': {'class': 'feature', 'data-already-active': store.premium.hasSeo}}) }} </code></pre> <p>I expect it sets <code>data-already-active</code> to <code>0</code> or to <code>1</code> depending on the feature is active or not.</p> <p>But the generated HTML is this if the <code>has*</code> method returns <code>true</code>:</p> <pre><code>&lt;input type="checkbox" id="form_plan_seo" name="form[plan][seo]" class="feature" data-already-active="data-already-active" value="1" checked="checked"&gt; </code></pre> <p>while simply omits the <code>data-already-active</code> attribute if the <code>has*</code> method returns <code>false</code>:</p> <pre><code>&lt;input type="checkbox" id="form_plan_social" name="form[plan][social]" class="feature" value="1"&gt; </code></pre> <p>More, has you can see, the value of the attribute <code>data-already-active</code> is not <code>0</code> or <code>1</code> nor <code>true</code> or <code>false</code> but is the name of the attribute itself:</p> <pre><code>data-already-active="data-already-active" </code></pre> <p>Is this normal? Have I a better way of setting this information in the <code>checkbox</code>?</p>
<p>Yep, that seems to be the normal behavior for assigning <strong>boolean</strong> values for the twig attrs values. An easy workaround would be to modify the code a bit:</p> <pre><code>{{ form_widget(form.plan.seo, {'attr': {'class': 'feature', 'data-already-active': store.premium.hasSeo ? "1" : "0"}}) }} </code></pre> <p>or if you want to have this working with your current twig definition you can also move this boolean to string logic into the form template.</p>
Minimum Required Node Version for GraphQL? <p>I am trying to get a reference implementation of GraphQL.js working in a Node.js environment as a server. Note that I have limited experience with Node.js. Right now, I am using <code>node</code> v4.2.6, which is the latest package from Ubuntu for Ubuntu 16.04.</p> <p><a href="http://graphql.org/graphql-js/running-an-express-graphql-server/" rel="nofollow">The official documentation</a> says that this script should work:</p> <pre><code>var express = require('express'); var graphqlHTTP = require('express-graphql'); var { buildSchema } = require('graphql'); // Construct a schema, using GraphQL schema language var schema = buildSchema(` type Query { hello: String } `); // The root provides a resolver function for each API endpoint var root = { hello: () =&gt; { return 'Hello world!'; }, }; var app = express(); app.use('/graphql', graphqlHTTP({ schema: schema, rootValue: root, graphiql: true, })); app.listen(4000); console.log('Running a GraphQL API server at localhost:4000/graphql'); </code></pre> <p>That fails with a syntax error:</p> <pre><code>server.js:3 var { buildSchema } = require('graphql'); ^ SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:442:10) at startup (node.js:136:18) at node.js:966:3 </code></pre> <p><a href="https://github.com/graphql/express-graphql" rel="nofollow">The express-graphql project site</a> shows a significantly different script, but one where I have to assemble a schema separately. <a href="https://github.com/graphql/graphql-js" rel="nofollow">The GraphQL.js project site</a> has this script for assembling a schema:</p> <pre><code>import { graphql, GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql'; var schema = new GraphQLSchema({ query: new GraphQLObjectType({ name: 'RootQueryType', fields: { hello: { type: GraphQLString, resolve() { return 'world'; } } } }) }); </code></pre> <p>That too fails with a syntax error:</p> <pre><code>server.js:1 (function (exports, require, module, __filename, __dirname) { import { ^^^^^^ SyntaxError: Unexpected reserved word at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:374:25) at Object.Module._extensions..js (module.js:417:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Function.Module.runMain (module.js:442:10) at startup (node.js:136:18) at node.js:966:3 </code></pre> <p>I am guessing that perhaps v4.2.6 of Node.js is too old. Is that correct? If so, what is the minimum version of Node.js required to use GraphQL.js and <code>express-graphql</code>? And, if that's not my problem... any idea what is?</p>
<p>tThe <a href="http://graphql.org/graphql-js/#prerequisites" rel="nofollow">prerequisites</a> for that tutorial say:</p> <blockquote> <p>Before getting started, you should have Node v6 installed [...]</p> </blockquote> <p>Though to be fair it continues with:</p> <blockquote> <p>[...] , although the examples should mostly work in previous versions of Node as well.</p> </blockquote> <p>Node v4 doesn't support destructuring, which is the part it's choking on for you. You can check out <a href="http://node.green/" rel="nofollow">node.green</a> for a reference on what features are supported by what Node versions.</p> <blockquote> <p>That too fails with a syntax error:</p> </blockquote> <p><code>import|export</code> aren't supported in any version of Node. You'd have to transpile that. Or you can just use Node's module system. For that it should look something like:</p> <pre class="lang-js prettyprint-override"><code>var graphqlModule = require("graphql"); var graphql = graphqlModule.graphql; var GraphQLSchema = graphqlModule.GraphQLSchema; // ... </code></pre>
Configure Spring 4 JDBC JDBCTemplate with Connection Provider class <p>Is there a way i can configure the spring 4 JDBCTemplate data source with a Connection provider class like the one hibernate provides? </p> <p>I have connections managed by connection pool provided by a Java class. I can get connection through the provider class but i'm not sure how to configure the JDBCTemplate datasource with that.</p> <pre><code>@Configuration public class MyDataSourceConfig { /** * My data source. * * @return the data source */ @Bean(name = "myDS") @Primary public DataSource myDataSource() { // I need to add a way to get a data source object using the connection // from the class Connection conn = DBConnection.getConnection(); /** * TODO Add code to create data source with the connection provider * DBConnection.class */ return dataSource; } @Bean(name = "jdbcMydb") @Autowired public JdbcTemplate hrdbJdbcTemplate(@Qualifier("myDS") DataSource jdbcMydb) { return new JdbcTemplate(jdbcMydb); }} </code></pre>
<p>One solution would be for you to extend <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/AbstractDataSource.html" rel="nofollow">AbstractDataSource</a> and override getConnection() method and write new DataSource for you. Or to probably make easier by extending concrete classes like <a href="http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/SimpleDriverDataSource.html" rel="nofollow">SimpleDriverDataSource</a></p>
AngularJS load ng-repeat into another ng-repeat with ajax call <p>I'm new to angular and would like some help in solving the following issue. This is the code I currently have, simply getting an array of results from the server using a post request and displaying them using the ng-repeat directive:</p> <pre><code>&lt;div id="mainW" ng-controller="MediaController"&gt; &lt;div id="mediaBodyW" ng-repeat="media in medias"&gt; &lt;div class="mediaW" data-id="{{media.id}}"&gt; &lt;div class="mediaNum"&gt;{{media.num}}&lt;/div&gt; &lt;div class="mediaN"&gt;{{media.name}}&lt;/div&gt; &lt;div id="loadSubs" ng-click="loadSubMedias(media.id)"&gt;load sub medias&lt;/div&gt; &lt;div id="subMediaW"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is my controller:</p> <pre><code>app.controller("MediaController",['$scope','$http','$httpParamSerializerJQLike',function($scope,$http,$httpParamSerializerJQLike){ $scope.medias = []; try { $http({ method: 'POST', url: 'media.php', data: $httpParamSerializerJQLike({"request":"getAllMedia"}), headers: {'Content-Type':'application/x-www-form-urlencoded'} }).then(function (ans) { $scope.medias = ans.data; }, function (error) { console.error(JSON.stringify(error)); }); } catch (ex) { console.error("Error: " + ex.toString()); } }]); </code></pre> <p>Now, what I would like to achieve, is: on clicking the div with id of "loadSubs", run another $http post query which will load an array of results into the "subMediaW". Of course the query and appending of html should be unique for each media element, and each time a data is loaded for a particular element all previous results should be cleared, all this while taking into account that the loaded data will be also manipulated in the future.</p> <p>Can someone please help me understand how can I do this using AngularJS?</p>
<p>Firstly you should have a function in your controller with the name <strong>loadSubMedias</strong> and instead of simply taking media.id you can send whole media object to it (later on we will add new data into this object as an another property).</p> <pre><code>$scope.loadSubMedias = function (media) { $http({ method: 'POST', url: 'media.php', data: $httpParamSerializerJQLike({"mediaId":media.id}), headers: {'Content-Type':'application/x-www-form-urlencoded'} }).then(function (response) { // now add subDatas into main data Object media.subMedias = response.data; }); } </code></pre> <p>and in your controller just use ng-repeat like this</p> <pre><code>&lt;div id="mainW" ng-controller="MediaController"&gt; &lt;div id="mediaBodyW" ng-repeat="media in medias"&gt; &lt;div class="mediaW" data-id="{{media.id}}"&gt; &lt;div class="mediaNum"&gt;{{media.num}}&lt;/div&gt; &lt;div class="mediaN"&gt;{{media.name}}&lt;/div&gt; &lt;div id="loadSubs" ng-click="loadSubMedias(media)"&gt;load sub medias&lt;/div&gt; &lt;div id="subMediaW" ng-repeat="subMedia in media.subMedias"&gt; &lt;pre&gt;{{subMedia | json}}&lt;/pre&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
how to make my initial workbook activate based on a full pathname <p>i have the following code, need it to work:</p> <pre><code>Sheets("BigMaster").Range("A1:z999").Copy Windows("Z:\Viewpoint\Viewpoint Import\Programs\SheetsForConstructionAndImportingIntoViewpoint - FROZEN.XLSM").Activate Sheets("BigMaster").Range("A1").Paste </code></pre> <p>its failing on the activate command. how come?</p> <p>i have tried to shorten the workbook name but it is still not working. i definitely have the right path though, i took it with windows explorer.</p> <p>basically i need to copy from bigmaster on my current book to the bigmaster on the activate clause. but i get an error 9 subscript out of range.</p> <p>what am i doing wrong and how can i fix this macro</p>
<p>Assuming the destination workbook is open - if it's not then you first need to open it</p> <pre><code>ActiveWorkbook.Sheets("BigMaster").Range("A1:z999").Copy _ Workbooks("SheetsForConstructionAndImportingIntoViewpoint - FROZEN.XLSM"). _ Sheets("BigMaster").Range("A1") </code></pre>
Learn Python the Hard way ex25 - Want to check my understanding <p>total noob here confused all to hell about something in "Learn Python the Hard Way." Apologies if this has been covered; I searched and could only find posts about not getting the desired results from the code.</p> <p>My question relates to the interaction of two functions in <a href="https://learnpythonthehardway.org/book/ex25.html" rel="nofollow">exercise 25</a>:</p> <pre><code>def break_words(stuff): words = stuff.split(' ') return words </code></pre> <p>and</p> <pre><code>def sort_sentence(sentence): words = break_words(sentence) return sort_words(words) </code></pre> <p>So, near the end of the exercise Zed has you run this in the terminal:</p> <pre><code>&gt;&gt;&gt; sorted_words = ex25.sort_sentence(sentence) &gt;&gt;&gt; sorted_words ['All', 'come', ’good’, ’things’, ’those’, ’to’, ’wait.’, ’who’] </code></pre> <p>Now I assume the argument in 'sort_sentence' comes from the following, entered in the terminal at the start of the exercise:</p> <pre><code>&gt;&gt;&gt; sentence = "All good things come to those who wait." </code></pre> <p>But although we now know the above is the argument for 'sort_sentence,' 'sort_sentence' can't complete without running 'break_words', with 'sentence' again as <em>its</em> argument. Here's where I get confused: The argument for 'break_words' is labeled 'stuff.' Does this matter? Can 'sentence' just be passed into 'break_words' from 'sorted_words' no matter what the argument for 'break_words' is labeled?</p> <p>So assuming what I assumed - that the argument label doesn't matter - 'break_words' ought to run with 'sentence' as its argument and return 'words', which is the output of the function 'stuff.split' contained therein. This is where I get <em>really</em> confused - what does the 'words' returned from 'break_words' have to do with the variable 'words' defined as a part of 'sort_sentence'? I simply can't figure out how these functions work together. Thank you in advance for your help!</p>
<p>How Python functions more or less work is the following:</p> <pre><code>def function_name(parameter_name_used_locally_within_function_name): #do stuff with parameter_name_used_locally_within_function_name some_new_value = parameter_name_used_locally_within_function_name return some_new_value </code></pre> <p>Notice how the parameter is only with in the scope of the function <code>function_name</code>. As that variable will only be used in that function and not outside of it. When we return a variable from a function, we can assign it to another variable calling the function:</p> <pre><code>my_variable = function_name("hello") </code></pre> <p><code>my_variable</code> now has <code>"hello"</code> as it's value since we called the function, passing in the value <code>"hello"</code>. Notice I didn't call the function with a specify variable name? We don't care what the parameter name is, all we know is it takes one input for the function. That parameter name is only used in the function. Notice how we receive the value of <code>some_new_value</code> with out knowing the name of that variable when we called the function?</p> <p>Let me give you a more broad example of what's going on. Functions can be thought of a task you give someone to do. Lets say the function or task is to as them to cook something for us. The chef or task needs ingredients to cook with (that's our input), and we wish to get food back (our output return). Lets say I want an omelette, I know I have to give the chef eggs to make me one, I don't care how he makes it or what he does to it as long as I get my output/omelette back. He can call the eggs what he wants, he can break the eggs how he wants he can fry it in the pan how he likes, but as long as I get my omelette, I'm happy.</p> <p>Back to our programming world, the function would be something like:</p> <pre><code>def cook_me_something(ingredients): #I don't know how the chef makes things for us nor do I care if ingredients == "eggs": food = "omelette" elif ingredients == "water": food = "boiled water" return food </code></pre> <p>We call it like this: </p> <pre><code>my_food_to_eat = cook_me_something("eggs") </code></pre> <p>Notice I gave him "eggs" and I got some "omelette" back. I didn't say the eggs are the ingredients nor did I know what he called the food that he gave me. He just return <code>food</code> that contain <code>omelettes</code></p> <p>Now let's talk about chaining functions together. </p> <p>So we got the basic down about me giving something to the chef and he giving me food back based on what I gave him. So what if we gave him something that he needs to process before cooking it with. Let's say what if he doesn't know how to grind coffee beans. But his co-chef-worker knows how too. He would pass the beans to that person to grind the coffee beans down and then cook with the return process.</p> <pre><code>def cook_me_something(ingredients): #I don't know how the chef makes things for us nor do I care if ingredients == "eggs": food = "omelette" elif ingredients == "water": food = "boiled water" elif ingredients == "coffee beans" co_worker_finished_product = help_me_co_worker(ingredients) #makes coffee with the co_worker_finished_product which would be coffee grindings food = "coffee" return food #we have to define that function of the co worker helping: help_me_co_worker(chef_passed_ingredients): if chef_passed_ingredients == "coffee beans" ingredients = "coffee grinding" return ingredients </code></pre> <p>Noticed how the co worker has a local variable <code>ingredients</code>? it's different from what the chef has, since the chef has his own ingredients and the co worker has his own. Notice how the chef didn't care what the co worker called his ingredients or how he handle the items. Chef gave something to the co worker and expected the finished product. </p> <p>That's more or less how it's work. As long as functions get's their input, they will do work and maybe give an output. We don't care what they call their variables inside their functions cause it's their own items. </p> <p>So let's go back to your example:</p> <pre><code>def break_words(stuff): words = stuff.split(' ') return words def sort_sentence(sentence): words = break_words(sentence) return sort_words(words) &gt;&gt;&gt; sentence = "All good things come to those who wait." &gt;&gt;&gt; sorted_words = ex25.sort_sentence(sentence) &gt;&gt;&gt; sorted_words ['All', 'come', ’good’, ’things’, ’those’, ’to’, ’wait.’, ’who’] </code></pre> <p>Let's see if we can break it down for you to understand.</p> <p>You called <code>sorted_words = ex25.sort_sentence(sentence)</code> and set <code>sorted_words</code> to the output of the function <code>sort_sentence()</code> which is <code>['All', 'come', ’good’, ’things’, ’those’, ’to’, ’wait.’, ’who’]</code>. You passed in the input <code>sentence</code> </p> <p><code>sort_sentence(sentence)</code> get's executed. You passed in the string is now called <code>sentence</code> inside the variable. Note that you could have called the function like this and it will still work:</p> <pre><code>sorted_words = ex25.sort_sentence("All good things come to those who wait.") </code></pre> <p>And the function <code>sort_sentence()</code> will still call that string <code>sentence</code>. The function basically said what ever my input is, I'm calling it sentence. You can pass me your object named sentence, which I'm going to rename it to sentence while I'm working with it. </p> <p>Next on the stack is:</p> <pre><code>words = break_words(sentence) </code></pre> <p>which is now calling the function break_words with that the function <code>sort_sentence</code> called it's input as <code>sentence</code>. So if you follow the trace it's basically doing:</p> <pre><code>words = break_words("All good things come to those who wait.") </code></pre> <p>Next on the stack is:</p> <pre><code>words = stuff.split(' ') return words </code></pre> <p>Note that the function call it's input as <code>stuff</code>. So it took the sort_sentence's input that sort_sentence called <code>sentence</code> and function <code>break_words</code> is now calling it <code>stuff</code>. </p> <p>It splits the "sentence" up into words and stores it in a list and returns the list "words"</p> <p>Notice how the function <code>sort_sentence</code> is storing the output of <code>break_words</code> in the variable <code>words</code>. Notice how the function <code>break_words</code> is returning a variable named <code>words</code>? They are the same in this case but it doesn't matter if one called it differently. <code>sort_sentence</code> can store the output as <code>foo</code> and it still work. We are talking about different scope of variables. Outside of the function <code>break_words</code> the variable <code>words</code> can be anything, and <code>break_words</code> would not care. But inside <code>break_words</code> that variable is the output of the function. </p> <p>Under my house my rules? Outside of my house you can do what ever you want type of thing.</p> <p>Same deal with <code>sort_sentence</code> return variable, and how we store what we got back from it. It doesn't matter how we store it or what we call it. </p> <p>If you wanted you can rename it as:</p> <pre><code>def break_words(stuff): break_words_words = stuff.split(' ') return break_words_words def sort_sentence(sentence): words = break_words(sentence) return sort_words(words) #not sure where this function sort_words is coming from. #return words would work normally. &gt;&gt;&gt; sentence = "All good things come to those who wait." &gt;&gt;&gt; sorted_words = ex25.sort_sentence(sentence) &gt;&gt;&gt; sorted_words ['All', 'come', ’good’, ’things’, ’those’, ’to’, ’wait.’, ’who’] </code></pre> <p>You just have to think of local variables, and parameters as like just naming things to work with. Like our example with the chef, Chef might called the eggs, ingredients, but I called it what ever I wanted and just passed it "eggs". It's all about the scope of things, think of functions as a house, while you are in the house, you can name what ever objects you want in the house, and outside of the house those same names could be different things but inside the house, they are what you want them to be. And when you throw something out, you naming that item has nothing to do with the outside world, since the outside world will name it something else. Might name it the same thing tho...</p> <p>If I just rambled too much, ask questions I will try to clear it up for you.</p> <p>Edited</p> <p>Coming back from lunch I thought of variable as containers, They hold the values but you don't care what other people's containers are named. You only care about yours and when someone gives you something you put it in a container and name it something you care about that will help you know what inside it. When you give away an item, you don't give the container, cause you need it to store other things..</p>
Cannot debug C# RTD Server project in Visual Studio 2013 <p>As part of an attempt to figure out the various issues working with (previously) working .NET COM projects and Excel 2013 on my machine, I created a simple test C# RTDServer class in Visual Studio 2013. Creating the test RTD Server project helped me realize that my Excel 2013 was a 64 bit version and that I needed to set Target Platform to x64 for any .NET COM components to work with this version of Excel.</p> <p>This test RTD component works fine (as long as it is compiled as x64), but I cannot Debug into the code using Visual Studio. What used to work on older projects is to set the Start-Up Application to Excel.exe and then I could always hit a break point in the <code>ServerStart(IRTDUpdateEvent CallbackObject)</code> method, for example.</p> <p>However when I try this with VS 2013 project, it never hits the break point. If I set a new break point while it is running I see the message:</p> <blockquote> <p>The breakpoint will not currently be hit. No symbols have been loaded for this document.</p> </blockquote> <p>I have searched a lot for the solution to this, but not found anything that worked yet.</p>
<p>It turns out this problem was caused by an app config for Excel which we had to use when running with Excel 2003 (when we first developed this app).</p> <p>The config contained the following:</p> <p></p> <pre><code> &lt;startup&gt; &lt;supportedRuntime version="v2.0.50727"/&gt; &lt;supportedRuntime version="v1.1.4322"/&gt; &lt;requiredRuntime version="v2.0.50727"/&gt; &lt;/startup&gt; </code></pre> <p>However, this RTD Server was using .NET 4.5. Once I deleted the config file from the Office directory, it started working in debugger.</p>
How to tell what is causing seg fault when using pthread_create? <p>I'm having trouble finding the cause of this seg fault when calling pthread_create... </p> <p>GDB is giving me <code>Program received signal SIGSEGV, Segmentation fault. 0x00007ffff7bc741d in pthread_create@@GLIBC_2.2.5 () from /lib64/libpthread.so.0</code></p> <p>I'll include the part of the code that calls it and the part of the code which includes the function the threads are calling.</p> <pre><code>int main(int argc, char **argv) { /* * Declare local variables */ int i, j; // LK pthread_t *cat[NUM_CATS]; // LK pthread_t *lizard[NUM_LIZARDS]; // LK /* * Check for the debugging flag (-d) */ debug = 0; if (argc &gt; 1) if (strncmp(argv[1], "-d", 2) == 0) debug = 1; /* * Initialize variables */ numCrossingSago2MonkeyGrass = 0; numCrossingMonkeyGrass2Sago = 0; running = 1; /* * Initialize random number generator */ srandom( (unsigned int)time(NULL) ); /* * Initialize locks and/or semaphores */ sem_init(&amp;driveway, 0, 20); // LK /* * Create NUM_LIZARDS lizard threads */ // LK for(i = 0; i &lt; NUM_LIZARDS; i++) { pthread_create(lizard[i], NULL, lizardThread, (void *)(&amp;i)); } </code></pre> <p>And the function called by pthread_create...</p> <pre><code>void * lizardThread( void * param ) { int num = *(int*)param; if (debug) { printf("[%2d] lizard is alive\n", num); fflush(stdout); } while(running) { lizard_sleep(num); // LK sago_2_monkeyGrass_is_safe(num); // LK cross_sago_2_monkeyGrass(num); // LK lizard_eat(num); // LK monkeyGrass_2_sago_is_safe(num); // LK cross_monkeyGrass_2_sago(num); // LK } pthread_exit(NULL); } </code></pre>
<p>The segfault is very likely because of passing uninitialized thread ID to <code>pthread_create()</code>. The array <code>lizard</code> isn't initialized. </p> <p>Instead use an array:</p> <pre><code> pthread_t lizard[NUM_LIZARDS]; // LK ... // LK for(i = 0; i &lt; NUM_LIZARDS; i++) { pthread_create(&amp;lizard[i], NULL, lizardThread, (void *)(&amp;i)); } </code></pre> <p>Also, note that there's <a href="https://docs.oracle.com/cd/E19205-01/820-0619/geojs/index.html" rel="nofollow"><em>data race</a></em> since you pass <code>&amp;i</code> to all threads. Instead you can use an array to fix the data race.</p> <pre><code> int arr[NUM_LIZARDS]; for(i = 0; i &lt; NUM_LIZARDS; i++) { arr[i] = i; pthread_create(&amp;lizard[i], NULL, lizardThread, &amp;arr[i]); } </code></pre>
ANTLR: How to write a rule for enforcing line continuation character while writing a string? <p>I want to write a rule for parsing a string inside double quotes. I want to allow any character, with the only condition being that there MUST be a line continuation character \, when splitting the string on multiple lines.</p> <p>Example:</p> <pre><code>variable = "first line \n second line \ still second line \n \ third line" </code></pre> <p>If the line continuation character is not found before a newline character is found, I want the parser to barf.</p> <p>My current rule is this:</p> <pre><code>STRING : '"' (ESC|.)*? '"'; fragment ESC : '\\' [btnr"\\] ; </code></pre> <p>So I am allowing the string to contain any character, including bunch of escape sequences. But I am not really enforcing that line continuation character \ is a necessity for splitting text.</p> <p>How can I make the grammar enforce that rule?</p>
<h1>Solution</h1> <pre><code>fragment ESCAPE : '\\' . ; STRING : '"' (ESCAPE | ~[\n"])* '"' ; </code></pre> <h1>Explanation</h1> <p>Fragment <code>ESCAPE</code> will match escaped characters (especially backslash and a new line character acting as a continuation sign).</p> <p>Token <code>STRING</code> will match inside double quotation marks:</p> <ul> <li>Escaped characters (fragment <code>ESCAPE</code>)</li> <li>Everything except new line and double quotation marks.</li> </ul>
How to create function (number, from, to) with a returning interval of boolean + input&print out <p>I've tried searching here on Stackoverflow and on Google search engine on creating a function(number, from, to) in a interval, that returns with boolean and get their data from an input source with having the possiblity of a print out on the page. I've tried different types of combinations, but the text will not appear on the page at all. By the way, if possible I'd like to accomplish this without using php and jquery. My task is to check if a number is within the from and to interval.</p> <p>Here is my code: </p> <pre><code>&lt;!-- JS --&gt; window.onload = oppstart; function oppstart(tall, fra, til){ document.getElementById("btnVisSvaret").onclick=innenforInterval; document.getElementById("storre").innerHTML = ""; document.getElementById("mindre").innerHTML = ""; if (innenforInterval(parseInt(tall, parseInt(fra), parseInt(til) === true))) { document.getElementById("utskrift1").innerHTML = ("Ja! Tallet er innenfor intervallet!"); } else { document.getElementById("utskrift2").innerHTML = ("Nei! Tallet er ikke innenfor intervallet!"); } } function InnenforInterval(tall, fra, til){ if(tall &lt; til || tall &gt; fra){ return false; } else { return true; } } &lt;/script&gt; &lt;p&gt; Sjekk om et spesifikt tall er innenfor intervallet &lt;/p&gt; Er tallet: &lt;input id="siffere"/&gt;&lt;/input&gt; &lt;br&gt;&lt;/br&gt; Større enn: &lt;input id="storre"/&gt;&lt;/input&gt; og mindre enn: &lt;input id="mindre"/&gt;&lt;/input&gt; &lt;button id="btnVisSvaret" type="button" value="getElementById("storre")", value="getElementById("mindre")", value="getElementById("siffere")";/&gt; Vis Svaret &lt;/button&gt; &lt;p id="utskrift1"/&gt;&lt;/p&gt; &lt;p id="utskrift2"/&gt;&lt;/p&gt; </code></pre>
<p>If i understand it correctly, you want to check a number if it is inside of the given interval.</p> <p>I have stripped the code a bit and now ther are only two function which makes the code working.</p> <p>Please have a look to the button, ther is no value attribute. This is an attribute of input tag.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = oppstart; function oppstart() { document.getElementById("btnVisSvaret").onclick = innenforInterval; } function innenforInterval() { var tall = +document.getElementById('siffere').value, fra = +document.getElementById('mindre').value, til = +document.getElementById('storre').value; console.log(tall, fra, til); if (tall &gt;= fra &amp;&amp; tall &lt;= til) { document.getElementById("utskrift1").innerHTML = "Ja! Tallet er innenfor intervallet!"; } else { document.getElementById("utskrift2").innerHTML = "Nei! Tallet er ikke innenfor intervallet!"; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;Sjekk om et spesifikt tall er innenfor intervallet&lt;/p&gt; Er tallet:&lt;input id="siffere" /&gt;&lt;br&gt; Større enn: &lt;input id="storre" /&gt; og mindre enn:&lt;input id="mindre" /&gt; &lt;button id="btnVisSvaret" /&gt;Vis Svaret&lt;/button&gt; &lt;p id="utskrift1" /&gt;&lt;/p&gt; &lt;p id="utskrift2" /&gt;&lt;/p&gt;</code></pre> </div> </div> </p>
Creating two different objects through one Perl module <p>I'm writing Perl modules that allow users to create <code>file</code> and <code>directory</code> objects to manipulate the file system.</p> <p><strong>Example:</strong></p> <pre><code>use File; use Dir; my $file = File-&gt;new("path"); my $dir = Dir -&gt;new("path"); </code></pre> <p>This works out nicely, but what I would really like to be able to create both <code>file</code> and <code>directory</code> objects without having to <code>use</code> two separate modules.</p> <hr> <p>To do this I came up with the following solution...</p> <p><strong>IO.pm:</strong></p> <pre><code>use File; use Dir; use Exporter qw(import); our @EXPORT_OK = qw(file dir); sub file { my $path = shift; return File-&gt;new($path); } sub dir { my $path = shift; return Dir-&gt;new($path); } 1; </code></pre> <p><strong>test.pl:</strong></p> <pre><code>use IO qw(file dir); my $file = file("path"); my $dir = dir ("path"); </code></pre> <hr> <p>Now here's the problem, by doing this I eliminate the explicit call to <code>new</code> when the user creates a <code>file</code> or <code>directory</code> object. I'm sort of using the <code>file</code> and <code>dir</code> subroutines as constructors.</p> <p>To me this code looks very clean, and is extremely simple to use, but I haven't seen many other people writing Perl code like this so I figured I should at least pose the question:</p> <p><strong><em>Is it okay to simply return an object from a subroutine like this, or does this scream bad practice?</em></strong></p>
<p>That's perfectly fine.</p> <p>For example, Path::Class's <code>file</code> and <code>dir</code> functions return Path::Class::File and Path::Class::Dir objects respectively.</p> <p>If that was the only constructor the class provided, it would prevent (clean) subclassing, but that's not the case here.</p> <hr> <p>There is, however, the question of whether replacing</p> <pre><code>open(my $fh, "path"); opendir(my $dh, "path); </code></pre> <p>with</p> <pre><code>my $fh = file("path"); my $dh = dir("path); </code></pre> <p>is advantageous or not (assuming the functions return IO::File and IO::Dir objects).</p>
Determine which surface mesh faces are visible <p>I am working with a triangle surface mesh in C/C++. I am looking for a surface mesh library (or a good algorithm I can implement) that would allow me to select the subset of the surface's faces that are visible from a specific origin point in space.</p> <p>For simple geometries, this can be easily done by checking if the angle between the segment defined by my origin point and the centre of a face and the normal of the face is less than 90º. However, this simple test does not extend to more complex geometries where orthogonal faces could be occluded by other faces in the mesh.</p> <blockquote> <p>Note: The mesh is being imported from MATLAB and is in a simple format of an array of node coordinates and an array of node ids corresponding to each face. This is not too important, though, since I could convert it into whatever format/object necessary.</p> </blockquote> <p>I would appreciate any help finding a library with a function that can achieve this, or any hints as to what kind of algorithms I could implement. For libraries, it would also be great if the functions can be run in a GPU device, since I am using CUDA to accelerate my code.</p> <p>Thank you so much for your help!</p>
<p>Did you check the point cloud library (PCL)? <a href="http://pointclouds.org/" rel="nofollow">http://pointclouds.org/</a></p>
Replacing strings in text files <p>I'm trying to replace some text in a file. I need to change the number in the below string (spacing included):</p> <pre><code> "2016101901 ; serial number" </code></pre> <p>This number may vary, but the format is always the same (so it may be 2015100101, etc.).</p> <p>I'm not sure how to approach this using wildcards... I've tried below and it doesn't work:</p> <pre><code>{$_ -replace "* ; serial number", "2016101902 ; serial number"} </code></pre> <p>Any ideas how I'd do this?</p>
<p>The <code>-replace</code> method is using <a href="/questions/tagged/regex" class="post-tag" title="show questions tagged &#39;regex&#39;" rel="tag">regex</a>. So use this:</p> <pre><code>{$_ -replace '^\d{10}(\s*;\s*serial number)', '2016101902$1'} </code></pre>
this.props.enableEdit is not a function error while executing function <p>Trying to edit the entered text by edit button. Edit button invokes triggerEdit function that reads enableEdit property. My code goes like this:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> class App extends React.Component { constructor(){ super(); this.state={ todo:[] }; }; entertodo(keypress){ var Todo=this.refs.inputodo.value; if( keypress.charCode == 13 ) { this.setState({ todo: this.state.todo.concat({Value:Todo, checked:false}), editing:false }); this.refs.inputodo.value=null; }; }; todo(todo,i){ return ( &lt;li className={todo.checked===true? 'line':'newtodo'}&gt; &lt;div &gt; &lt;input type="checkbox" className="option-input checkbox" checked={todo.checked} /&gt; &lt;div key={todo.id} className="item"&gt; {todo.Value} &lt;span className="destroy" onClick={this.remove.bind(this, i)}&gt;X&lt;/span&gt; &lt;button onClick={this.triggerEdit.bind(this,i)}type='button'&gt;edit&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/li&gt; ); }; remove(i){ this.state.todo.splice(i,1) this.setState({todo:this.state.todo}) }; todoCompleted(i){ var todo=this.state.todo; todo[i].checked =todo[i].checked? false:true; this.setState({ todo:this.state.todo }); }; allCompleted=()=&gt;{ var todo = this.state.todo; var _this = this todo.forEach(function(item) { item.className = _this.state.finished ? "newtodo" : "line" item.checked = !_this.state.finished }) this.setState({todo: todo, finished: !this.state.finished}) }; enableEdit(i){ var todo= this.state.todo; var edittodo=todo[i]; }; triggerEdit(i) { this.props.enableEdit(i) }; render() { return ( &lt;div&gt; &lt;h1 id='heading'&gt;todos&lt;/h1&gt; &lt;div className="lines"&gt;&lt;/div&gt; &lt;div&gt; &lt;input type="text" ref= "inputodo" onKeyPress={this.entertodo.bind(this)}className="inputodo"placeholder='todos'/&gt; &lt;span onClick={this.allCompleted}id="all"&gt;^&lt;/span&gt; &lt;/div&gt; &lt;div className="mainapp"&gt; &lt;ul className="decor"&gt; {this.state.todo.map(this.todo.bind(this))} &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; ); } } ReactDOM.render(&lt;App/&gt;,document.getElementById('app'));</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code> .line { text-decoration: line-through; color: red; } .newtodo{ text-decoration: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"&gt;&lt;/script&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>I tried some ways but the error i got is <strong>this.props.enableEdit is not a function</strong></p>
<p>With how your code is written it should just be: <code>this.enableEdit(i)</code> enableEdit is a method on the component, not a prop you are passing into it</p>
Filter by a Reference Property in Appnengine <p>I am doing a blog in appengine. I want make a query to get the numbers of post by category. So I need filter by a Reference Property in appengine. Look my actual Code.</p> <p>Those are my models :</p> <pre><code>class Comment(db.Model) : user = db.ReferenceProperty(User) post = db.ReferenceProperty(Blog) subject = db.StringProperty(required = True) content = db.TextProperty(required = True) date = db.DateProperty(auto_now_add = True) last_modified = db.DateProperty() status = db.BooleanProperty(default = True) class Category(db.Model): name = db.StringProperty() date = db.DateProperty(auto_now_add=True) class Blog(db.Model) : subject = db.StringProperty(required = True) content = db.TextProperty(required = True) date = db.DateProperty(auto_now_add = True) category = db.ReferenceProperty(Category) user = db.ReferenceProperty(User) last_modified = db.DateProperty(auto_now = True) status = db.BooleanProperty() likes = db.IntegerProperty(default = 0) users_liked = db.ListProperty(db.Key, default = []) dislikes = db.IntegerProperty(default = 0) users_disliked = db.ListProperty(db.Key, default = []) </code></pre> <p>And this is my query :</p> <pre><code>def numcomments_all_category() : dic = {} category = get_category() for cat in category : dic[cat.key().id()] = Comment.all().filter("post.category =", cat.key()).ancestor(ancestor_key).count() return dic </code></pre> <p>But It seems that filter("post.category =", cat.key()) is not the correct way to do this.</p>
<p>I haven't used <code>db</code> in a while, but I think something like this will work:</p> <pre><code>count = 0 # Get all blogs of the desired category blogs = Blog.all().filter("category =", cat.key()) for blog in blogs: # For each blog, count all the comments. count += Comment.all().filter("post =", blog.key()).count() </code></pre>
bash: sorting on same values gives different orders <p>I have the following two files:</p> <p>file1:</p> <pre><code>4 rs10000009 0 71048953 G A 4 rs10000010 0 21618674 C T 4 rs10000011 0 138223055 T C 2 rs1000001 0 50711642 T G 4 rs10000005 0 85161558 G A 12 rs1000000 0 126890980 A G 4 rs10000003 0 57561647 A G 4 rs10000006 0 108826383 C T 4 rs10000007 0 114553253 C A 4 rs10000008 0 172776204 T C </code></pre> <p>file2:</p> <pre><code>4 rs10000007 C A 0.006562 762 4 rs10000008 T C 0.01575 762 4 rs10000009 G A 0 762 12 rs1000000 A G 0.2388 762 4 rs10000010 C T 0.4921 762 4 rs10000003 A G 0.2992 762 4 rs10000005 G A 0.4409 762 4 rs10000012 G C 0.1417 762 4 rs10000006 C T 0.02625 762 4 rs10000011 T C 0.03675 762 </code></pre> <p>I use sort to sort these files based on column 2, which contains the same values for both files. </p> <pre><code>sort -f -k 2 file1 &gt; file1.sorted sort -f -k 2 file2 &gt; file2.sorted </code></pre> <p>However, I get two <em>differently</em> sorted files:</p> <p>file1.sorted: </p> <pre><code>12 rs1000000 0 126890980 A G 4 rs10000003 0 57561647 A G 4 rs10000005 0 85161558 G A 4 rs10000006 0 108826383 C T 4 rs10000007 0 114553253 C A 4 rs10000008 0 172776204 T C 4 rs10000009 0 71048953 G A 4 rs10000010 0 21618674 C T 2 rs1000001 0 50711642 T G 4 rs10000011 0 138223055 T C </code></pre> <p>file2.sorted: </p> <pre><code>4 rs10000003 A G 0.2992 762 4 rs10000005 G A 0.4409 762 4 rs10000006 C T 0.02625 762 4 rs10000007 C A 0.006562 762 4 rs10000008 T C 0.01575 762 4 rs10000009 G A 0 762 12 rs1000000 A G 0.2388 762 4 rs10000010 C T 0.4921 762 4 rs10000011 T C 0.03675 762 4 rs10000012 G C 0.1417 762 </code></pre> <p>What am I missing here? How do I get these two files to be sorted in the same way? It does not matter much to me in which way, as long as I can then use join to join the two files. Many thanks!</p>
<p>Use <code>-k 2,2</code> to sort based on 2nd column alone. <code>-k 2</code> means sort starting from 2nd column</p> <pre><code>$ sort -f -k 2,2 file2 12 rs1000000 A G 0.2388 762 4 rs10000003 A G 0.2992 762 4 rs10000005 G A 0.4409 762 4 rs10000006 C T 0.02625 762 4 rs10000007 C A 0.006562 762 4 rs10000008 T C 0.01575 762 4 rs10000009 G A 0 762 4 rs10000010 C T 0.4921 762 4 rs10000011 T C 0.03675 762 4 rs10000012 G C 0.1417 762 </code></pre> <p>Use <code>-b</code> option to <strong>ignore leading blanks</strong>, for ex: <code>sort -bf -k 2,2 file2</code></p> <p><br> Further reading: <a href="http://unix.stackexchange.com/questions/104525/sort-based-on-the-third-column">Sort based on the third column</a></p>
json to case class using multiple rows in spark scala <p>i have a json file with logs:</p> <pre><code>{"a": "cat1", "b": "name", "c": "Caesar", "d": "2016-10-01"} {"a": "cat1", "b": "legs", "c": "4", "d": "2016-10-01"} {"a": "cat1", "b": "color", "c": "black", "d": "2016-10-01"} {"a": "cat1", "b": "tail", "c": "20cm", "d": "2016-10-01"} {"a": "cat2", "b": "name", "c": "Dickens", "d": "2016-10-02"} {"a": "cat2", "b": "legs", "c": "4", "d": "2016-10-02"} {"a": "cat2", "b": "color", "c": "red", "d": "2016-10-02"} {"a": "cat2", "b": "tail", "c": "15cm", "d": "2016-10-02"} {"a": "cat2", "b": "ears", "c": "5cm", "d": "2016-10-02"} {"a": "cat1", "b": "tail", "c": "10cm", "d": "2016-10-10"} </code></pre> <p>desired output:</p> <pre><code>("id": "cat1", "name": "Caesar", "legs": "4", "color": "black", "tail": "10cm", "day": "2016-10-10") ("id": "cat2", "name": "Dickens", "legs": "4", "color": "red", "tail": "10cm", "ears": "5cm", "day": "2016-10-02") </code></pre> <p>i can do it step by step using for loops and collects, but I need to do it in proper way using maps, flatmaps, aggregatebykey and other spark magic</p> <pre><code>case class cat_input(a: String, b:String, c:String, d: String) case class cat_output(id: String, name: String, legs: String, color: String, tail: String, day: String, ears: String, claws: String) object CatLog { def main(args: Array[String]) { val sconf = new SparkConf().setAppName("Cat log") val sc = new SparkContext(sconf) sc.setLogLevel("WARN") val sqlContext = new org.apache.spark.sql.SQLContext(sc) import sqlContext.implicits._ val df = sqlContext.read.json("cats1.txt").as[cat_input] val step1 = df.rdd.groupBy(_.a) //step1 = (String, Iterator[cat_input]) = (cat1, CompactBuffer(cat_input( "cat1", "name", "Caesar", "2016-10-01"), ... ) ) val step2 = step1.map(x =&gt; x._2) //step2 = Iterator[cat_input] val step3 = step2.map(y =&gt; (y.b,y.c)) //step3 = ("name", "Caesar") val step4 = step3.map( case(x,y) =&gt; { cat_output(x) = y }) // it should return cat_output(id: "cat1", name: "Caesar", legs: "4", color: "black", tail: "10cm", day: NULL, ears: NULL, claws: NULL) </code></pre> <ol> <li>step4 is obviously not working </li> <li>how to return at least this cat_output(id: "cat1", name: "Caesar", legs: "4", color: "black", tail: "10cm", day: NULL, ears: NULL, claws: NULL) </li> <li>how to check values by d column and choose newest one between them and also put newest date to into cat_output(date)?</li> </ol>
<p>Assuming data has the unique properties for each cat (cat1, cat2). Apply some logic for duplicates. You can try something like this for your case class:</p> <pre><code>#method to reduce 2 cat_output objects to one def makeFinalRec(a: cat_output, b:cat_output): cat_output ={ return cat_output( a.id, if(a.name=="" &amp;&amp; b.name!="") b.name else a.name, if(a.legs=="" &amp;&amp; b.legs!="") b.legs else a.legs, if(a.color=="" &amp;&amp; b.color!="") b.color else a.color, if(a.tail=="" &amp;&amp; b.tail!="") b.tail else a.tail, if(a.day=="" &amp;&amp; b.day!="") b.day else a.day, if(a.ears=="" &amp;&amp; b.ears!="") b.ears else a.ears, if(a.claws=="" &amp;&amp; b.claws!="") b.claws else a.claws ); } dt.map(x =&gt; (x(0), x(1), x(2))).map(x =&gt; (x._1.toString, cat_output(x._1.toString, (x._2.toString match { case "name" =&gt; x._3.toString case _ =&gt; ""}), (x._2.toString match { case "legs" =&gt; x._3.toString case _ =&gt; ""}), (x._2.toString match { case "color" =&gt; x._3.toString case _ =&gt; ""}), (x._2.toString match { case "tail" =&gt; x._3.toString case _ =&gt; ""}), (x._2.toString match { case "day" =&gt; x._3.toString case _ =&gt; ""}), (x._2.toString match { case "ears" =&gt; x._3.toString case _ =&gt; ""}), (x._2.toString match { case "claws" =&gt; x._3.toString case _ =&gt; ""}) ) )).reduceByKey((a,b) =&gt; makeFinalRec(a,b)).map(x=&gt;x._2).toDF().toJSON.foreach(println) Output: {"id":"cat2","name":"Dickens","legs":"4","color":"red","tail":"15cm","day":"","ears":"5cm","claws":""} {"id":"cat1","name":"Caesar","legs":"4","color":"black","tail":"20cm","day":"","ears":"","claws":""} </code></pre> <p>Also note, I didnt apply the actual "date" because there are duplicates. It needs another map() &amp; max logic to get max for each key then join both datasets.</p>
Merge map of maps(nested maps) by retaining all values of same keys es6 <p>I am trying to merge 2 maps which have keys and values(are maps again).</p> <p>_.merge works fine for 2 regular maps but not working for map of maps or nested maps.</p> <pre><code>map1 = {k1: {c1: v1, c2: v2}, k2: {c1: v1, c2: v2}}; map2 = {k1: {c3: v3, c4: v4}, k2: {c3: v3, c4: v4}}; </code></pre> <p>Expecting</p> <pre><code>mergedMap = {k1: {c1: v1, c2: v2, c3: v3, c4: v4}, k2: {c1: v1, c2: v2, c3: v3, c4: v4}}; </code></pre>
<p>Use <a href="https://lodash.com/docs/4.16.4#mergeWith" rel="nofollow"><code>_.mergeWith()</code></a> recursively.</p> <p>ES6 solution:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const recursiveMerge = (...args) =&gt; _.mergeWith({}, ...args, (objValue, srcValue) =&gt; { if(typeof srcValue === 'object') { return recursiveMerge(objValue, srcValue); } }); const map1 = {k1: {c1: 'v1', c2: 'v2'}, k2: {c1: 'v1', c2: 'v2'}}; const map2 = {k1: {c3: 'v3', c4: 'v4'}, k2: {c3: 'v3', c4: 'v4'}}; const result = recursiveMerge(map1, map2); console.log(result);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>ES5 solution:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function recursiveMerge() { var args = [].slice.call(arguments, 0); var params = [{}].concat(args).concat([ function(objValue, rcValue) { if (typeof srcValue === 'object') { return recursiveMerge(objValue, srcValue); } }]); return _.mergeWith.apply(_, params); } var map1 = {k1: {c1: 'v1', c2: 'v2'}, k2: {c1: 'v1', c2: 'v2'}}; var map2 = {k1: {c3: 'v3', c4: 'v4'}, k2: {c3: 'v3', c4: 'v4'}}; var result = recursiveMerge(map1, map2); console.log(result);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
how to set limits on rounded facet wrap y axis? <p>I have this plot and I need to round the y axis so what appears is acceptable EXCEPT for the fact that I would like to not just show 1 value on the y axis. I'd like to add the "limit" to the "scale_y_continuous" function so that the limits for each facet plot are unique to the individual facet.</p> <p>here is the plot only showing 60 and 80 on the y axis</p> <pre><code>dat = data.frame(x = c(1,2,3,1,2,3),A=c(80.6, 82,83,60,61,62),A_up =c(81,84,85,62,63,64), A_low =c(79,78,81,59,58,57), group = c("z","z","z","y","y","y")) ggplot(data=dat , aes(x=as.factor(x), y=A, group = 1)) + #, color =Group, group = Group geom_line() + geom_point() + # facet_wrap(~COUNTERPARTY_STRATEGY ,ncol=2) geom_errorbar(aes(ymax = A_up ,ymin = A_low), width = .25) + scale_y_continuous(breaks = seq( floor( (min(dat$A_low)-11) /10)*10 , ceiling( (max(dat$A_up)+11) /10)*10,10 ), labels = seq( floor( (min(dat$A_low)-11) /10)*10 , ceiling( (max(dat$A_up)+11) /10)*10,10 ) ) + facet_wrap(~group ,ncol=2, scales = "free_y") </code></pre> <p>Now I add the limit in the scale y continuous and it applies the limit globally.</p> <pre><code>dat = data.frame(x = c(1,2,3,1,2,3),A=c(80.6, 82,83,60,61,62),A_up =c(81,84,85,62,63,64), A_low =c(79,78,81,59,58,57), group = c("z","z","z","y","y","y")) ggplot(data=dat , aes(x=as.factor(x), y=A, group = 1)) + #, color =Group, group = Group geom_line() + geom_point() + # facet_wrap(~COUNTERPARTY_STRATEGY ,ncol=2) geom_errorbar(aes(ymax = A_up ,ymin = A_low), width = .25) + scale_y_continuous(breaks = seq( floor( (min(dat$A_low)-11) /10)*10 , ceiling( (max(dat$A_up)+11) /10)*10,10 ), labels = seq( floor( (min(dat$A_low)-11) /10)*10 , ceiling( (max(dat$A_up)+11) /10)*10,10 ), # limits = c( floor( min(dat$A_low[dat$group =="z"]) /10)*10 ,ceiling(max(dat$A_up[dat$group =="z"])/10)*10 ) #limits = c( floor( min(dat$A_low[dat$group =="z"]) /10)*10 ,ceiling(max(dat$A_up[dat$group =="z"])/10)*10 ) limits = c( floor( min(dat$A_low) /10)*10 ,ceiling(max(dat$A_up)/10)*10 ) ) + facet_wrap(~group ,ncol=2, scales = "free_y") </code></pre> <p>i.e. </p> <p><code>c( floor( min(dat$A_low) /10)*10 ,ceiling(max(dat$A_up)/10)*10 )</code></p> <p>is 50 and 90</p> <p>but I would like the limit to be unique to each facet plot so something like</p> <p>so the right plot would have limits of </p> <p><code>c( floor( min(dat$A_low[dat$group =="y"]) /10)*10 ,ceiling(max(dat$A_up[dat$group =="y"])/10)*10 )</code></p> <p>50 and 70 </p> <p>and the left plot would have limit of </p> <p><code>c( floor( min(dat$A_low[dat$group =="z"]) /10)*10 ,ceiling(max(dat$A_up[dat$group =="z"])/10)*10 )</code></p> <p>70 and 90</p> <p>how can the limits be adjusted to be specific to the individual facet plots?</p>
<p>I don't have ggplot installed, but maybe a simple <code>if () else</code> could solve your problem. My first attempt would be this:</p> <pre><code>if { (dat$group =="y") c( floor( min(dat$A_low[dat$group =="y"]) /10)*10, ceiling(max(dat$A_up[dat$group =="y"])/10)*10 ) else c( floor( min(dat$A_low[dat$group =="z"]) /10)*10, ceiling(max(dat$A_up[dat$group =="z"])/10)*10 ) } </code></pre>
Format parse exception “EEE MMM dd HH:mm:ss Z yyyy” <p>My date string is: "Wed Oct 19 14:34:26 BRST 2016" and I'm trying to parse it to "dd/MM/yyyy", but I'm getting the following exception:</p> <pre><code>java.text.ParseException: Unparseable date: "Wed Oct 19 14:34:26 BRST 2016" (at offset 20) </code></pre> <p><strong>the method</strong></p> <pre><code>public String dataText(int lastintervalo) { Date mDate = new Date(); String dt = mDate.toString(); SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.getDefault()); Calendar c = Calendar.getInstance(); try { c.setTime(sdf.parse(dt)); } catch (ParseException e) { e.printStackTrace(); } sdf.applyPattern("dd/MM/yyyy"); c.add(Calendar.DATE, lastintervalo); return sdf.format(c.getTime()); } </code></pre> <p>I already searched on google and stackoverflow questions, but nothing seems to work</p>
<p>Since the error message is complaining about offset 20, which is the <code>BRST</code> value, it seems that it cannot resolve the time zone.</p> <p>Please try this code, that should ensure that the Brazilian time zone is recognized:</p> <pre><code>SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("America/Sao_Paulo")); System.out.println(sdf.parse("Wed Oct 19 14:34:26 BRST 2016")); </code></pre> <p>Since I'm in Eastern US, that prints this for me:</p> <pre><code>Wed Oct 19 12:34:26 EDT 2016 </code></pre>
Using jsp in Reactjs app <p>I have 2 questions which are related:</p> <p>1.) I have a react app, which is loading using index.html Can I do this index.html as index.jsp? When I simply change it like that, then run my npm server, go to localhost:8080/index.jsp, then this file doesn't open but downloads it. </p> <p>2.) Can I simply run a jsp file in an npm server?</p>
<ol> <li><p>Yes, you can use React in a HTML page rendered from any source, including JSP.</p></li> <li><p>No. This is why your attempt at 1) failed - JSP are <strong>Java</strong> Server Pages. You need a Java application server to execute JSP and serve the HTML output.</p></li> </ol>
How to extend string with additional characters before and after special characters in string <p>A field on my form contains a string which is the formula for a math function. With this string I take data from database.</p> <p>But the problem is, if some of this string in the database is NULL then my formula does not work. </p> <p>Example of formula is </p> <pre><code>amount_injuries+amount_employment+health_insurance </code></pre> <p>This formula is PHP part in MySQL she looks like </p> <pre><code>SELECT SUM(amount_injuries+amount_employment+health_insurance) FROM ... ! </code></pre> <p>The result which I want is </p> <pre><code>select sum((COALESCE(amount_injuries,0)+(COALESCE(amount_employment,0))+(COALESCE(health_insurance,0)))) from ... </code></pre> <p>How can I add the <code>COALESCE</code> part to the existing string in PHP?</p>
<p>If I understand correctly, the different parts of the string from your form (amount_injuries, etc.) are column identifiers that you're using in a math expression in your query.</p> <p>There are a few different ways to do this. The simplest way is to use a regular expression replacement on anything that is a valid column identifier.</p> <pre><code>$coalesce = preg_replace('/(\\w+)/', '(COALESCE(\\1,0))', $string_from_form); </code></pre> <p>There are problems with this, though. Concatenating a user-supplied string into your SQL statement, is an injection vulnerability. This also assumes that all the columns have been entered correctly, are valid column names without backticks, and that only valid math operators have been used.</p> <p>A better way would be to split the string on valid math operators (using <code>PREG_SPLIT_DELIM_CAPTURE</code> in order to capture the operators as well) and then validate the columns given against a list of acceptable columns as you apply the <code>COALESCE</code> modification.</p> <pre><code>$columns = preg_split('|([+-/*])|', $string_from_form, null, PREG_SPLIT_DELIM_CAPTURE); $accepted_columns = ['amount_injuries', 'amount_employment', 'health_insurance']; $columns = array_map(function($x) use ($accepted_columns) { if (in_array($x, ['+', '-', '/', '*'])) { return $x; } else { // validate the column; stop if column is invalid if (in_array($x, $accepted_columns)) { return sprintf('(COALESCE(`%s`,0))', $x); } else { // handle error } } }, $columns); $columns = implode('', $columns); </code></pre> <p>An approach like this should be able to handle most simple math expressions. It's still very naive, though; it doesn't do much to determine whether the expression provided is valid mathematically, or that it can be handled by MySQL, it doesn't handle parentheses, etc. To go farther with it you'd need to look into math expression parsers, and I'm not familiar enough with any to recommend one.</p>
NameResolutionFailure vs ConnectFailure issue <p>So a rather peculiar issue, but a pretty bad one nonetheless. When a user enters our app with no internet at all, we get back a <code>NameResolutionFailure</code> as the error message for trying to make a API call via <code>HttpClient</code>. Okay, that's fine. The issue though is, when the user then connects to internet, goes back to app, and attempts to make another API call, we get the same error message. It appears that some kind of DNS caching is happening? </p> <p>On the flip side, if a user HAS internet access while in app, then loses it, when we try to make an API call we get a <code>ConnectFailure(Network is unreachable)</code> error from the API call. And as soon as the user connects to the internet, they can make API calls instantenously. </p> <p>The issue I'm trying to figure out is, A) What's the difference between <code>NameResolutionFailure</code> and <code>ConnectFailure</code> ? and B) Is there anything we can do in app to force it to completely retry the API call without using any cache? It's not obvious to me if the DNS is being cached or not, but we have a hinting feeling that's what's happening. </p> <p>Here's part of the code (if you need more let me know, I figured this is the only code needed)</p> <pre><code>using(var client = new HttpClient()) { client.Timeout = TimeSpan.FromSeconds(MaximumWebRequestTime); HttpResponseMessage response = null; try { response = await client.GetAsync(URL); if (response.IsSuccessStatusCode) .... </code></pre>
<p>I just filed a bug on this recently: <a href="http://bugzilla.xamarin.com/show_bug.cgi?id=45383" rel="nofollow">http://bugzilla.xamarin.com/show_bug.cgi?id=45383</a></p> <p>This is a regression in Xamarin Android version >= 7.0. You can workaround it by downgrading to Xamarin Android 6.1.2.21. And since it is a regression, it should be a priority and get fixed relatively quickly. </p> <p><em>Note: I am a MS/Xamarin support engineer</em> </p>
Failed to install the ibm-mfp-push cordova plugin <p>Seems like a recent update to the <a href="https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-core" rel="nofollow">ibm-mfp-core</a> plugin (2 days ago) has lead to the impossibility to install the <code>ibm-mfp-push</code> plugin.</p> <p>An <a href="https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-push/issues/28" rel="nofollow">issue</a> has been raised on the plugin's Github repo.</p> <p>I know that some people from the support team are also looking at Stack Overflow, so posting the issue here as well.</p> <p>We have an app almost ready to go on prod that is depending on this plugin.</p>
<p>The Plugin is currently being updated. I've contacted/escalated this issue to the Push team and will notify you when it is released.</p>
Training of chess evaluation function <p>I am about to write a chess engine based on reinforcement learning. I'd like to train an evaluation function and figure out what are the weights of the board's most important features.</p> <p>I'm not an expert of machine learning, I'm trying to learn from books and tutorials. In each tutorial, the reward is quite straightforward, often 1, 0, maybe -1, but there's no such obvious reward in chess (regardless the check-mate positions). For instance, assume I have a situation on the board. I make 10 (random) moves and at that point I should calculate the reward, the difference (or error) between the starting position and the current one. How to do such thing, when my only evaluation function is under training?</p> <p>I'd like to avoid using other engines' scoring system, because I feel that would rather be supervised learning, which is not my goal.</p>
<p>You can't really do that directly. </p> <p>A few approaches that I can suggest:</p> <ul> <li>Using scoring from an external source is not bad to at least kick start your algorithm. Algos to evaluate a given position are pretty limited though and your AI won't achieve master level using that alone. </li> <li>Explore the possibility of evaluating the position using another chess playing AI (open source ideally). Say you have a "teacher" AI. You start 2 instances of it and start the game from the position you want to evaluate. Let them play against each other from there until the end of the game. Was this move successful? Reward your own AI given the outcome. </li> <li>To add some variability (you don't want to be better than a single AI), do the same against other AIs. Or even, your own AI playing against itself. For the latter to work though, it probably needs to be already decent playing at chess, not playing entirely randomly. You can replay the same move many times and complete the game allowing your AI some random exploration of new moves and strategies (example: trying the 2nd best move down the road). </li> <li>Feed your ML using datasets of games between real players. Each move by the winning and losing players can be thus "reinforced"</li> <li>Have your AI learn by playing against real players. Reinforce both you AI moves (losing and winning ones) and that of the players. </li> </ul>
How to keep nav menu highlighted after click using js in sidebar <p>I have created a nav menu in Wordpress and placed it in sidebar.php in my child theme. </p> <p>My nav menu is in the correct location and functions and looks as it should with the exception of the JS, which I have tried to get right but seem to be failing. </p> <p>Each menu item takes you to a different page. I want the menu item to stay highlighted to show which page you are on once you have linked to that page. I have used CSS to highlight the li using :hover. </p> <p>I cant work out how or where to place the js to keep it the menu highlighted. </p> <ol> <li>Is my JS correct?</li> <li>Where do I place it? directly in sidebar.php under the html? or somewhere else?</li> </ol> <p>Thank you!</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.main-nav-list').on('click', function () { $('li.active').removeClass('active'); $(this).addClass('active'); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.main-nav .main-nav-list li:hover { background-color: #323840; width: 150px; border-radius: 20px; } .main-nav .main-nav-list li:active { background-color: #323840; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="sidebar sidebar-main &lt;?php echo $sidebar_classes; ?&gt;"&gt; &lt;div class="inner-content widgets-container"&gt; &lt;?php generated_dynamic_sidebar($sidebar_name);?&gt; &lt;div class="nav nav-pills nav-stacked main-nav"&gt; &lt;div class="main-nav-holder"&gt; &lt;ul class="main-nav-list"&gt; &lt;li class="active"&gt; &lt;a id="sidebar-questions" href="/dwqa-questions"&gt;QUESTIONS&lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a id="sidebar-ask" href="/dwqa-ask-question"&gt;ASK A QUESTION&lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a id="sidebar-ama" href="/ask-me-anything"&gt;AMAs&lt;/a&gt; &lt;/li&gt; &lt;li class=""&gt; &lt;a id="sidebar-jobs" href="/jobs"&gt;JOBS&lt;/a&gt; &lt;/li&gt; &lt;li class=“"&gt; &lt;a id="sidebar-find" href="/find-a-health-professional"&gt;FIND A HEALTH PRO&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt;</code></pre> </div> </div> </p>
<p>I assume that you don't use any router to remain on the same page. If so, then once a user clicks on any link, a browser will load completely new page and so this code of yours </p> <pre><code>$('.main-nav-list').on('click', function () { $('li.active').removeClass('active'); $(this).addClass('active'); }); </code></pre> <p>has no effect, because it modified the previous page that is now replaced by the new page. The one thing I think you can do on page load is to read <code>pathname</code> and highlight a corresponding link. Here is an example of how this can be done</p> <pre><code>&lt;script&gt; jQuery(function () { var pathname = document.location.pathname; console.log('the pathname is: ', pathname); jQuery('.main-nav-list a').each(function () { var value = jQuery(this).attr('href'); if (pathname.indexOf(value) &gt; -1) { jQuery(this).closest('li').addClass('active'); return false; } }) }); &lt;/script&gt; </code></pre> <p>And remove <code>active</code> class from all <code>li</code> elements in html.</p> <p>I used <code>jQuery</code> instead of <code>$</code> because of this:</p> <blockquote> <p>"When WordPress’ jQuery is loaded, it uses compatibility mode, which is a mechanism for avoiding conflicts with other language libraries. </p> <p>What this boils down to is that you can’t use the dollar sign directly as you would in other projects. When writing jQuery for WordPress you need to use jQuery instead. "</p> </blockquote>
Get values from a boost::multi_index <p>I have created a <code>boost::multi_index</code> successfully and inserted values too. I have two hashed indices to the multi_index. Both are member functions, but one is unique and the other one is non-unique. </p> <p>I am trying to figure out the way to get the values from the container using the values of the hashes. I could not understand how I should do that. I searched online, and I see there are a lot of people have asked this question. But I dont understand what needs to be done. I saw a few solutions in C++11 but I dont use C++11 and I dont understand whats being done. Can someone please explain to me how to use it? Given below is my code,</p> <pre><code>#include "stdafx.h" #include&lt;multi_index_container.hpp&gt; #include&lt;boost/multi_index/hashed_index.hpp&gt; #include&lt;boost/multi_index/mem_fun.hpp&gt; #include&lt;boost/multi_index/tag.hpp&gt; class RetClass { int a, b; }; class StoreMe { RetClass ex; std::string exStr; int id; public: void setId(RetClass a) { ex = a; }; virtual const RetClass&amp; getId() const { return ex; } virtual std::string getIdString() const { return exStr; } int getUniqueId() const { return id; } }; struct IndexByStringId{}; struct IndexByUniqueId{}; typedef boost::multi_index_container&lt; StoreMe, boost::multi_index::indexed_by&lt; boost::multi_index::hashed_unique&lt; boost::multi_index::tag&lt;IndexByStringId&gt;, boost::multi_index::const_mem_fun&lt;StoreMe, std::string, &amp;StoreMe::getIdString&gt; &gt;, boost::multi_index::hashed_non_unique&lt; boost::multi_index::tag&lt;IndexByUniqueId&gt;, boost::multi_index::const_mem_fun&lt;StoreMe, int, &amp;StoreMe::getUniqueId&gt; &gt; &gt; &gt; mi_storeMe; int _tmain(int argc, _TCHAR* argv[]) { return 0; } </code></pre> <p>I want to be able to,</p> <ol> <li>Get the values non-unique Id maps to</li> <li>Get the value (if it exists) that the unique Id maps to</li> </ol> <p>Please let me know the correct/simplest way to get this done. Also I don't use C++11.</p>
<p>Here's how you'd retrieve from the string-based index:</p> <pre><code>mi_storeMe container; std::string needle = whatToSearchFor(); auto iterator = container.get&lt;IndexByStringId&gt;().find(needle); if (iterator != container.get&lt;IndexByStringId&gt;().end()) found(*iterator); else notFound(); </code></pre> <p>For the ID-based index, it's very similar:</p> <pre><code>mi_storeMe container; RetClass needle = whatToSearchFor(); auto range = container.get&lt;IndexByUniqueId&gt;().equal_range(needle); processRangeFromTo(range.first, range.second); </code></pre> <p>The answer uses <code>auto</code> from C++11 so that I can avoid spelling out the types involved. If you do not have access to C++11, please do the type deduction yourself by reading Boost's <code>multi_index</code> documentation. I cannot vouch for correctness, but I believe the iterator type can be spelled as</p> <pre><code>mi_storeMe::index&lt;IndexByStringId&gt;::type::iterator </code></pre> <hr> <p>Tangentially related: how to do printf-style debugging of multi-index containers without C++11.</p> <p>First off, remember thatwhile you don't have <code>auto</code>, you still have type deduction in templates. No need to spell out types if a function template can deduce them:</p> <pre><code>template &lt;class It&gt; void printContainerItems(It from, It to) { for (; from != to; ++from) print(*from); } printContainerItems(container.begin(), container.end()); </code></pre> <p>Second, you can easily iterate over an index:</p> <pre><code>const mi_Container::index&lt;IndexByIdString&gt;::type&amp; index = container.get&lt;IndexByIdString&gt;(); for ( mi_Container::index&lt;IndexByIdString&gt;::type::iterat‌​or it = index.begin(), end = index.end(); it != end; ++it ) { operate_on(*it); } </code></pre>
angular2 & typescript & reactiveX : how to cast http get result <p>Lets suppose we have a rest api at this url <code>/api/stuffs/</code> where we can get a list of <code>Stuff</code>.</p> <p>here is the code to http get the list of <code>Stuff</code>:</p> <pre><code>getStuffs(): Observable&lt;Stuff[]&gt; { return this.http.get(this.url) .map(this.extractStuffs) .catch(this.handleError); } private extractStuffs(res: Response) { let stuffs = res.json() as Stuff[]; return stuffs || new Array&lt;Stuff&gt;(); } </code></pre> <p>everything works fine with this code, except the fact that the <code>stuffs</code> array in the <code>extractStuffs</code> function is not an array of <code>Stuff</code> but and array of <code>Object</code> instead, even if the signature of the function is <code>Observable&lt;Stuff[]&gt;</code> and the result from the api is casted to <code>Stuff[]</code>. What's weird is that typescript compiler is not throwing any error (even if result type is different from signature), witch is totally normal if we take a look at the generated JS file :</p> <pre><code>StuffService.prototype.extractStuffs = function (res) { var stuffs = res.json(); return stuffs || new Array(); }; </code></pre> <p>So obviously casting the result into <code>Stuff[]</code> is not even considered by the compiler.</p> <p>Is there any way to cast it properly without doing it manually ?</p> <p>Thanks.</p>
<p>Every time I am in a similar situation I do casting through a loop (which I guess you define manually).</p> <p>This is an example with Customers instead of Stuffs</p> <pre><code>getCustomers(code: string) { let url = environment.baseServicesUrl + 'customer'; let jsonParam = {code: code}; return this.http.post(url, jsonParam, this.getOptions()) .map(this.extractData) .map((customerJsons) =&gt; { let customers = new Array&lt;Customer&gt;(); customerJsons.forEach((customerJson) =&gt; { customers.push(&lt;Customer&gt;customerJson); }) return customers }) .catch(this.handleError); } </code></pre> <p>The casting type Customer is an interface.</p> <p>Here is the code of <strong>Customer.interface.ts</strong></p> <pre><code>import {Relationship} from './relationship.interface'; export interface Customer { customerId: string; name: string; lastName: string; code: string; relationships: Array&lt;Relationship&gt;; } </code></pre> <p>Here is the code for <strong>Relationship.interface.ts</strong></p> <pre><code>export interface Relationship { id: string; type: string; } </code></pre>
npm install from a git repository not working <p>I am trying to install modules hosted on github using <code>npm install</code>. For example </p> <pre><code>npm install git+https://github.com/balderdashy/enpeem.git </code></pre> <p>But this is not placing the module in the <code>node_modules</code> folder. If I run with <code>--verbose</code> flag, I can see that the module is getting fetched and going to <code>appData</code> folder.</p> <blockquote> <p>node -v v4.6.1 </p> <p>npm -v 2.15.9</p> </blockquote> <p><a href="https://i.stack.imgur.com/2SnhG.png" rel="nofollow"><img src="https://i.stack.imgur.com/2SnhG.png" alt="enter image description here"></a></p> <p>What am I doing wrong here?</p>
<p>Updating node to v6.9.0 solved the problem.</p>
Back propagation of error in Feed forward neural network <p>**I am trying to develop a feedforward NN in MATLAB. I have a dataset of 12 inputs and 1 output with 46998 samples. while back propagating error, 1). I am getting NaN in Updated weight matrix between hidden and outer layer. 2). In the last equation of the code, I am getting error with matrix multiplication(not getting required matrix dimension).</p> <pre><code> deltatotalerror_deltaweights_intohidden = deltatotalerror_outhidden * deltaouthidden_inhidden * deltainhidden_deltaweights_intohidden; deltatotalerror_outhidden is a (46998*25) matrix deltaouthidden_inhidden is a (46998*25) matrix deltainhidden_deltaweights_intohidden is a (46998*13) matrix and deltatotalerror_deltaweights_intohidden should be (25*13) matrix in order to update the weights.** %% Clear Variables, Close Current Figures, and Create Results Directory clc; clear all; close all; mkdir('Results//'); %Directory for Storing Results %% Configurations/Parameters load 'Heave_dataset' nbrOfNeuronsInEachHiddenLayer = 24; nbrOfOutUnits = 1; unipolarBipolarSelector = -1; %0 for Unipolar, -1 for Bipolar learningRate = 0.08; nbrOfEpochs_max = 50000; %% Read Data Input = Heave_dataset(:, 1:length(Heave_dataset(1,:))-1); TargetClasses = Heave_dataset(:, length(Heave_dataset(1,:))); %% Calculate Number of Input and Output NodesActivations nbrOfInputNodes = length(Input(1,:)); %=Dimention of Any Input Samples nbrOfLayers = 2 + length(nbrOfNeuronsInEachHiddenLayer); nbrOfNodesPerLayer = [nbrOfInputNodes nbrOfNeuronsInEachHiddenLayer nbrOfOutUnits]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Forward Pass %%%%%%%%%%% %% Adding the Bias to Input layer Input = [ones(length(Input(:,1)),1) Input]; %% Weights leading from input layer to hidden layer is w1 w1 = rand(nbrOfNeuronsInEachHiddenLayer,(nbrOfInputNodes+1)); %% Input &amp; output of hidde layer hiddenlayer_input = Input*w1'; hiddenlayer_output = -1 + 2./(1 + exp(-(hiddenlayer_input))); %% Adding the Bias to hidden layer hiddenlayer_output = [ones(length(hiddenlayer_output(:,1)),1) hiddenlayer_output]; %% Weights leading from input layer to hidden layer is w1 w2 = rand(nbrOfOutUnits,(nbrOfNeuronsInEachHiddenLayer+1)); %% Input &amp; output of hidde layer outerlayer_input = hiddenlayer_output*w2'; outerlayer_output = outerlayer_input; %% Error Calculation TotalError = 0.5*(TargetClasses-outerlayer_output).^2; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Backward Pass %%%%%%%%%%% % % % % % % % % % % % % % % % % % % % % % % % outer layer to hidden layer %% Total error change w.r.t output of outer layer deltatotalerror_deltaOutouter = (outerlayer_output-TargetClasses); %% Change in output of outer layer w.r.t input of outer layer % Since it is a linear transfer function, it's derivative w.r.t input will be 1. deltaOutouter_deltainouter = 1; %% Change in input of outer layer w.r.t Weights leading to output layer deltainouter_deltaweights_hiddentoouter = hiddenlayer_output; %% Total error change w.r.t Weights leading to output layer deltatotalerror_deltaweights_hiddentoouter = deltaOutouter_deltainouter * deltatotalerror_deltaOutouter' * deltainouter_deltaweights_hiddentoouter; %% updated weights from hidden layer to outer layer w2_updated = w2 -(learningRate*deltatotalerror_deltaweights_hiddentoouter); % % % % % % % % % % % % % % % % % % % % % % % Hidden layer to input layer % % 1. change in total error w.r.t output hidden neurons = (change in total error % w.r.t output of outer layer ) * (change in output of outer layer w.r.t % input of outer layer) * (change in input of outer layer w.r.t output of hiddenlayer) deltainouter_outhidden = w2; deltatotalerror_outhidden = deltatotalerror_deltaOutouter * deltaOutouter_deltainouter * w2; % % change in output of hiddenlayer w.r.t input of hiddenlayer deltaouthidden_inhidden = 0.5 .* (1 + hiddenlayer_output) .* (1 - hiddenlayer_output); % % change in input of hiddenlayer w.r.t Weights leading to hidden layer deltainhidden_deltaweights_intohidden = Input; % % change in total error w.r.t Weights leading to hidden layer deltatotalerror_deltaweights_intohidden = deltatotalerror_outhidden * deltaouthidden_inhidden * deltainhidden_deltaweights_intohidden; </code></pre>
<p>You should try vectorize your algorithm. First arrange your data in a 46998x12 matrix X.Add bias to X like X=[ones(46998,1 X]. Then the weights leading from input layer to first hidden layer must be arranged in a matrix W1 with dimensions numberofneuronsinfirsthiddenlayer(24)x(input + 1). Then X<em>W1' is what you feed in your neuron function (either is it sigmoid or whatever it is). The result (like sigmoid(X</em>W') is the output of neurons at hidden level 1. You add bias like before and multiply by weight matrix W2 (the weights that lead from hidden layer 1 to hidden layer 2) and so on. Hope this helps to get you started vectorizing your code at least for the feedforward part. The back-propagation part is a little trickier but luckily involves the same matrices. <br> I will shortly recite the feedforward process so that we use same language talking about backpropagation.<br> There is the data called X.(dimensions 46998x12)<br> A1 = [ones(46998,1 X] is the input including bias. (46998x13)<br> Z2 = A1*W1' (W1 is the weight matrix that leads from input to hidden layer 1)<br> A2 = sigmoid(Z2);<br> A2 = [ones(m,1) A2]; adding bias again<br> Z3 = A2 * W2';<br> A3 = sigmoid(Z3);<br> Supposing you only have one hidden layer feedforward stops here. I'll start backwards now and you can generalize as appropriate.<br> d3 = A3 - Y; (Y must is part of your data, the actual values of the data with which you train your nn)<br> d2 = (d3 * W2).* A2 .* (1-A2); ( Sigmod function has a nice property that d(sigmoid(z))/dz = sigmoid(z)*(1-sigmoid(z)).)<br> d2 = d2(:,2:end);(You dont need the first column that corresponds in the bias)<br> D1 = d2' * A1;<br> D2 = d3' * A2;<br> W1_grad = D1/m + lambda*[zeros(size(W1,1),1) W1(:,2:end)]/m; (lamda is the earning rate, m is 46998)<br> W2_grad = D2/m + lambda*[zeros(size(W2,1),1) W2(:,2:end)]/m;<br> Everything must be in place now except for the vectorized cost function which have to be minimized. Hope this helps a bit...</p>
http0.0000000.000000www .. On Wordpress Log Out Redirect <p>I try to create a logout link which redirect to home url. I've tried this function:</p> <p><code>wp_logout_url(site_url)</code></p> <p>but, the output resulting strange prefix.</p> <p><code>http://example.com/wp-login.php?action=logout&amp;redirect_to=http0.0000000.000000www.example.com&amp;_wpnonce=f2c0bef0b0</code></p> <p>then I trying to hardcode the <code>site_url()</code>, but that prefix still exist and redirecting to wrong url.</p> <p>How to solve it?</p> <p>Thanks,</p> <p>Wildan</p>
<p>I need to put <code>urldecode()</code> function. don't know why. So, it'll look like:</p> <p><code>urldecode(wp_logout_url(site_url))</code></p>
SQLite - Return 0 if null <p>I have an assignment in Database Management Systems in which I have to write queries for given problems. I have 4 problems, of which I solved 3 and stuck with the last one.</p> <p><strong>Details:</strong></p> <ul> <li><em>Using version 1.4 of the Chinook Database</em> (<a href="https://chinookdatabase.codeplex.com/" rel="nofollow">https://chinookdatabase.codeplex.com/</a>). </li> <li><em>SQLite DB Browser</em></li> <li><strong><em>Chinook Sqlite AutoIncrementPKs.sqlite</em></strong> file​ in the directory with Chinook files is the database I am working on</li> </ul> <p><strong>Problem Statement:</strong> Write a query to generate a ranked list of employees based upon the amount of money brought in via customer invoices for which they were the support representative. The result set (see figure below) should have the following fields (in order) for all employees (even those that did not support any customers): ID (e_id), first name (e_first name), last name (e_last_name), title (e_title), and invoice total (total_invoices). The rows should be sorted by the invoice total (greatest first), then by last name (alphabetically), then first name (alphabetically). The invoice total should be preceded by a dollar sign ($) and have two digits after the decimal point (rounded, as appropriate); in the case of employees without any invoices, you should output a $0.00, not NULL. You may find it useful to look at the IFNULL, ROUND, and PRINTF functions of SQLite. </p> <p>Desired Output: </p> <p><a href="https://i.stack.imgur.com/rIJW6.png" rel="nofollow"><img src="https://i.stack.imgur.com/rIJW6.png" alt="enter image description here"></a></p> <p><strong>My Query:</strong></p> <pre><code>Select Employee.EmployeeId as e_id, Employee.FirstName as e_first_name, Employee.LastName as e_last_name, Employee.Title as e_title, '$' || printf("%.2f", Sum(Invoice.Total)) as total_invoices From Invoice Inner Join Customer On Customer.CustomerId = Invoice.CustomerId Inner Join Employee On Employee.EmployeeId = Customer.SupportRepId Group by Employee.EmployeeId Having Invoice.CustomerId in (Select Customer.CustomerId From Customer Where Customer.SupportRepId in (Select Employee.EmployeeId From Employee Inner Join Customer On Employee.EmployeeId = Customer.SupportRepId) ) order by sum(Invoice.Total) desc </code></pre> <p>My Output:</p> <p><a href="https://i.stack.imgur.com/wJUFW.png" rel="nofollow"><img src="https://i.stack.imgur.com/wJUFW.png" alt="enter image description here"></a></p> <p><strong>As you can see, the first three rows are correct but the later rows are not printed because employees don't have any invoices and hence EmployeeID is null.</strong></p> <p>How do I print the rows in this condition? I tried with <strong>Coalesce</strong> and <strong>ifnull</strong> functions but I can't get them to work.</p> <p>I'd really appreciate if someone can modify my query to get matching solutions. Thanks!</p> <p><strong>P.S</strong>: This is the schema of Chinook Database</p> <p><a href="https://i.stack.imgur.com/iKtya.png" rel="nofollow"><img src="https://i.stack.imgur.com/iKtya.png" alt="enter image description here"></a></p>
<p>It often happens that it is simpler to use subqueries:</p> <pre><code>SELECT EmployeeId, FirstMame, LastName, Title, (SELECT printf("...", ifnull(sum(Total), 0)) FROM Invoice JOIN Customer USING (CustomerId) WHERE Customer.SupportRepId = Employee.EmployeeId ) AS total_invoices FROM Employee ORDER BY total_invoices DESC; </code></pre> <p>(The inner join could be replaced with a subquery, too.)</p> <p>But it's possible that you are supposed to show that you have learned about <a href="https://en.wikipedia.org/wiki/Join_(SQL)#Outer_join" rel="nofollow">outer joins</a>, which generate a fake row containing NULL values if a matching row is not found:</p> <pre><code>... FROM Employee LEFT JOIN Customer ON Employee.EmployeeId = Customer.SupportRepId LEFT JOIN Invoice USING (CustomerID) ... </code></pre> <p>And if you want to be a smartass, replace <code>ifnull(sum(...), 0)</code> with <a href="http://www.sqlite.org/lang_aggfunc.html#sumunc" rel="nofollow"><code>total(...)</code></a>.</p>
An image thats responsive but square as an <img> element <p>I am using Ionic 1.x and Angular 1.x, I display an avatar image thats usually square but not always, I want it to be full width, and then square, so if the screen is 720px wide, I want a 720px tall and wide image, if the image is larger than this size, it should hide the excess (ideally in a smart way).</p> <p>I have only included the ionic styles, and a few of my own, so bootstrap isnt included in this project.</p> <p>I would be happy applying a class with width: 100% to the image, and a height: auto, but the height should not be more than the width.</p> <p>As mentioned it needs to be responsive as it will be shown on a variety of screen sizes, so the image I wont always know to set the size for... I could use some JS to manually calculate and set the sizes, but is that not a bit clunky?</p> <p>I had a look for directives but could find none.</p>
<p>One way to do this is to create a responsive square element and then use a CSS background image rather than an HTML img <code>src</code>:</p> <ul> <li><p>You can make a responsive element of any given <a href="https://en.wikipedia.org/wiki/Aspect_ratio_(image)" rel="nofollow">aspect ratio</a> with <code>height: 0</code>, <code>width: x%</code>, and <code>padding-bottom: y%</code> (or <code>padding-top</code>), where <code>x</code>/<code>y</code> is the aspect ratio. (This works because <a href="http://stackoverflow.com/a/17621322/1241736">percentage padding is relative to width</a>). In your case, to make a full-width square use <code>height: 0; width: 100%; padding-bottom: 100%;</code>.</p></li> <li><p>Because you're using an <code>&lt;img&gt;</code>, you'll get a "missing image" outline that can't be removed with CSS. Hack around this by using a single transparent pixel as your <code>src</code> image. Base64 encoded, that's <code>src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"</code> (<a href="https://css-tricks.com/snippets/html/base64-encode-of-1x1px-transparent-gif/" rel="nofollow">thanks to Chris Coyier</a> for saving us the trouble of making our own)</p></li> <li><p>Now add your image as an inline <code>background-image</code>. Center it with <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-position" rel="nofollow"><code>background-position: center</code></a>, and use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-size" rel="nofollow"><code>background-size: cover</code></a> to make scale to fit the <code>&lt;img&gt;</code>. You can use the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background" rel="nofollow"><code>background</code> shorthand</a> to say that in one CSS property, with <code>background: position/size</code>.</p></li> </ul> <hr> <p>Here it is all together. I'm using a wrapper element just to make things fit in the snippet results window; the second image demos successfully turning a non-square image into a square.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>img { width: 100%; height: 0; padding-bottom: 100%; background: no-repeat center/cover; } #wrapper-for-demo { width: 200px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="wrapper-for-demo"&gt;&lt;!-- just to fit nicely in the stacksnippets results window --&gt; &lt;!-- an image with a square source --&gt; &lt;img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" style="background-image:url(http://placehold.it/400x400)" /&gt; &lt;!-- an image with a non-square source --&gt; &lt;img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" style="background-image:url(http://placehold.it/400x600)" /&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
How to count number of social shares on web page locally <p>I have a Facebook share button on a page, And now the user shares a post on his/her timeline, Now what i want to do is count the number of times that specific user shares it in that session. </p> <p>For Example the count will be initialized to 0 for all users , What i want is Each time a person shares a post successfully the count to increment. </p> <p>We create a variable count and initialize to 0, now the share button works fine, How can i increment the count each time the post is successfully shared? What variables would be needed and how can this be done? </p> <pre><code>&lt;?php session_start(); $fbcount = $_SESSION['count']; function incrememnt() { $fbcount++; } ?&gt; &lt;script&gt; document.getElementById('shareBtn').onclick = function() { FB.ui({ method: 'share', display: 'popup', href: 'https://developers.facebook.com/docs/', }, function(response){}); } &lt;/script&gt; </code></pre>
<p>I'm not sure of the exact syntax without seeing the properties on the response object, but you should be able to do something like: </p> <pre><code> document.getElementById('shareBtn').onclick = function() { FB.ui({ method: 'share', display: 'popup', href: 'https://developers.facebook.com/docs/', }, function(response){ if(response.statusCode == '200'){ increment(); } }); } </code></pre> <p>You will likely have to change response.statusCode to whatever property you actually have on the response object.</p> <p>This would also be a good place for error handling. Maybe throw an else after the if to do something if it's anything but 200.</p>
Boost intrusive pointer <p>I'm a little confused about boost's intrusive pointer. The definition says:</p> <blockquote> <p>"Every new <code>intrusive_ptr</code> instance increments the reference count by using an unqualified call to the function <code>intrusive_ptr_add_ref</code>, passing it the pointer as an argument. Similarly, when an <code>intrusive_ptr</code> is destroyed, it calls <code>intrusive_ptr_release</code>; this function is responsible for destroying the object when its reference count drops to zero. The user is expected to provide suitable definitions of these two functions. "</p> </blockquote> <p>Does this mean that I HAVE TO implement these methods, or that I CAN do it? The point is, that we're using it because a function requires an intrusive pointer. We've used shared pointer the other places, so were just worried if the pointer is managed, and is going to be deleted when theres no more references to it.</p>
<p>You <em>have to</em> provide these functions. This is how <code>boost::intrusive_ptr</code> operates.</p> <p>Let's compare it with <code>boost::shared_ptr</code>. <code>shared_ptr</code> manages the reference count itself in the control block associated with the pointee. Creating a <code>shared_ptr</code> increments the refcount. Destroying a <code>shared_ptr</code> decrements the refcount. When the refcount goes to 0, the pointee is destroyed.</p> <p><code>intrusive_ptr</code> works in exactly the same way, but does not manage the reference count itself. It just signals to its client "now the refcount must be incremented" and "now the refcount must be decremented." It does that by calling the two functions mentioned, <code>intrusive_ptr_add_ref</code> and <code>intrusive_ptr_release</code>. If you do not define them, you will get a compilation error.</p> <p>Think of these functions as the interface to the reference counter. Using <code>intrusive_ptr</code> indicates that the refcount is managed somewhere outside the pointer (usually in the pointee itself), and the pointer just <em>intrudes</em> on that refcount, using it for its purposes.</p>
rvest cannot find node with xpath <p>This is the website I scapre <a href="http://www.cpppc.org:8082/efmisweb/ppp/projectLivrary/toPPPList.do" rel="nofollow">ppp projects</a></p> <p>I want to use xpath to select the node like below <a href="https://i.stack.imgur.com/hdIUl.png" rel="nofollow"><img src="https://i.stack.imgur.com/hdIUl.png" alt="enter image description here"></a></p> <p>The xpath I get by use inspect element is "//*[@id="pppListUl"]/li<a href="http://www.cpppc.org:8082/efmisweb/ppp/projectLivrary/toPPPList.do" rel="nofollow">1</a>/div<a href="https://i.stack.imgur.com/hdIUl.png" rel="nofollow">2</a>/span<a href="https://i.stack.imgur.com/hdIUl.png" rel="nofollow">2</a>/span"</p> <p>My scrpits are like below:</p> <pre><code>a &lt;- html("http://www.cpppc.org:8082/efmisweb/ppp/projectLivrary/toPPPList.do") b &lt;- html_nodes(a, xpath = '//*[@id="pppListUl"]/li[1]/div[2]/span[2]/span') b </code></pre> <p>Then I got the result </p> <pre><code>{xml_nodeset (0)} </code></pre> <p>Then I check the page source, I didn't even find anything about the project I selected. </p> <p>I was wondering why I cannot find it in the page source, and in turn, how can I get the node by rvest.</p>
<p>It makes an XHR request for the content. Just work with that data (it's pretty clean):</p> <pre><code>library(httr) POST('http://www.cpppc.org:8082/efmisweb/ppp/projectLivrary/getPPPList.do?tokenid=null', encode="form", body=list(queryPage=1, distStr="", induStr="", investStr="", projName="", sortby="", orderby="", stageArr="")) -&gt; res content(res, as="text") %&gt;% jsonlite::fromJSON(flatten=TRUE) %&gt;% dplyr::glimpse() </code></pre> <p>(StackOverflow isn't advanced enough to let me post the output of that as it thinks it's spam).</p> <p>It's a 4 element list with fields <code>totalCount</code>, <code>list</code> (which has the actual data), <code>currentPage</code> and <code>totalPage</code>.</p> <p>It looks like you can change the <code>queryPage</code> form variable to iterate through the pages to get the whole list/database, something like:</p> <pre><code>library(httr) library(purrr) library(dplyr) get_page &lt;- function(page_num=1, .pb=NULL) { if (!is.null(.pb)) pb$tick()$print() POST('http://www.cpppc.org:8082/efmisweb/ppp/projectLivrary/getPPPList.do?tokenid=null', encode="form", body=list(queryPage=page_num, distStr="", induStr="", investStr="", projName="", sortby="", orderby="", stageArr="")) -&gt; res content(res, as="text") %&gt;% jsonlite::fromJSON(flatten=TRUE) -&gt; dat dat$list } n &lt;- 5 # change this to the value in `totalPage` pb &lt;- progress_estimated(n) df &lt;- map_df(1:n, get_page, pb) </code></pre>
Are implicits private? <p>Given the following code:</p> <pre><code>class Foo[R](i: Int)(implicit ev: Ordering[R]) { final type T = ev.type } </code></pre> <p>I get the following error:</p> <blockquote> <p>Error:(13, 16) private value ev escapes its defining scope as part of type Foo.this.ev.type type T = ev.type</p> </blockquote> <p>Which makes me think implicits declared in a constructor are private. Given that <code>T</code> is final it won't be overridable, so it shouldn't cause any problem. What am I missing here? </p>
<p>All parameters declared in a <code>class</code> constructor are <code>private</code> unless you tell the compiler they are not. This differs from a <code>case class</code> where all parameters in the first argument list are by default <code>public</code> unless you tell the compiler otherwise. </p> <p>So, yes, unless you specifically add <code>val</code> or some other public-like modifier to the value, it is by default <code>private</code>. Hence, it is telling you that a private member is being made public via the way you are defining that <code>type</code>.</p>
Cross browser vertical text alignment <p>Can anyone explain why vertical text alignment is so different between browsers?</p> <p>See code below:</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;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;p style="background: grey; font-size: 400%;"&gt;Test text &amp;lArr;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>This displays quite differently between Firefox and Internet Explorer. Is there some css setting I can use to make this the same across all browsers?</p>
<p>You can use this library to normalize their web pages across browsers.</p> <p><a href="https://necolas.github.io/normalize.css/" rel="nofollow">Normalize</a></p> <p>I have helped you in any way</p>
Wrong use of CSS content attribute? <p>I wanted to add an icon via the content attribute of CSS. I just copied the code written in the first answer here for a telephone icon:<br> <a href="http://stackoverflow.com/questions/20782368/use-font-awesome-icon-as-css-content">Use font awesome icon as css content</a></p> <p>But I don't see any telephone icon. Instead, I'm seeing an empty square- why is that?<br> This is the full code I used: </p> <p>index.html </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;link rel="stylesheet" type="text/css" href="format.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#"&gt;This is a link&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>format.css: </p> <pre><code>body { font-family: Arial; font-size: 13px; } a { text-decoration: none; color: #515151; } a:before { font-family: FontAwesome; content: "\f095"; display: inline-block; padding-right: 3px; vertical-align: middle; } </code></pre>
<p>The content tag is actually a reference to a webfont file, .woff. The empty square is occurs because the reference could not be resolved.</p> <p>You should make sure that the css and woff resources found here - <a href="http://fontawesome.io/get-started/" rel="nofollow">http://fontawesome.io/get-started/</a> - are added as references.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css"&gt; &lt;link rel="stylesheet" type="text/css" href="format.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#"&gt;This is a link&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
C# design related query (better refactoring) <p>I am working on a functionality where I feel there is room for improvement.</p> <p><strong><em>Scenario:</em></strong></p> <p>I have a different types of buttons in an physical instrument. Each button type has a certain functionality (say volume up or volume down etc).</p> <p>I have got a task to implement - getting functionality of a new button type depending on certain actions (short press, medium press and long press). I followed the approach that is used to getting functionality for other button types.</p> <p><strong><em>End result:</em></strong></p> <p>End result should be that the new button type class should return all the functionalities that the button supports.</p> <p><strong><em>Implementation:</em></strong></p> <p>I have created a class "<em>InstrumentButtonType4</em>" inheriting from "<em>InstrumentButtonBase</em>".</p> <p>"<em>InstrumentButtonType4</em>" class has a method <em>GetButtonTypeFunctionalities()</em>, that first checks if button is available and enable.</p> <p>Then adds button functionality depending of actions.</p> <p>Now I have three actions short press, long press and medium press.</p> <p><strong><em>Main logic :-</em></strong></p> <p>I get the current value stored in the instrument for each of the actions "<em>int shortPress = _instrumenrData.GetValue(3);</em>" and call a static Mapper "<em>InstructionButtonFunctionalityMapper</em>" to get the corresponding functionality mapped to the given "<em>shortPress</em>" value.</p> <p><strong><em>Want to refactor in a better way</em></strong></p> <p>I want to improve these three methods if it can be written in a better way</p> <ol> <li>AddFunctionalityForShortPress()</li> <li>AddFunctionalityForMediumPress()</li> <li>AddFunctionalityForVeryLongPress()</li> </ol> <p>Can the logic in these three methods be written in some better design. Can we eliminate somehow the Mapper and make the implementation simpler/flexible and scallable?</p> <p>I have pasted the whole class code below. <em>Code can be compiled in a console application.</em> Your expert advice will really help me to learn and achive this in a better way.</p> <pre><code>public interface IInstrumentData { int GetValue(int location); } public abstract class InstrumentButtonBase { public abstract bool IsAvailable(); public abstract bool IsEnable(); public abstract IDictionary&lt;ButtonType, IDictionary&lt;ButtonAction, ButtonFunctionality&gt;&gt; GetButtonTypeFunctionalities(); } public class InstrumentButtonType4 : InstrumentButtonBase { private readonly IInstrumentData _instrumenrData; public InstrumentButtonType4(IInstrumentData instrumenrData) { _instrumenrData = instrumenrData; } public override IDictionary&lt;ButtonType, IDictionary&lt;ButtonAction, ButtonFunctionality&gt;&gt; GetButtonTypeFunctionalities() { var instrumentMaps = new Dictionary&lt;ButtonType, IDictionary&lt;ButtonAction, ButtonFunctionality&gt;&gt;(); var buttonFunctionality = new Dictionary&lt;ButtonAction, ButtonFunctionality&gt;(); if (!IsAvailable() &amp;&amp; !IsEnable()) { return instrumentMaps; } AddButtonFunctionality(buttonFunctionality); instrumentMaps.Add(ButtonType.Volume, buttonFunctionality); return instrumentMaps; } private void AddButtonFunctionality(Dictionary&lt;ButtonAction, ButtonFunctionality&gt; buttonFunctionality) { AddFunctionalityForShortPress(buttonFunctionality); AddFunctionalityForMediumPress(buttonFunctionality); AddFunctionalityForVeryLongPress(buttonFunctionality); } private void AddFunctionalityForVeryLongPress(Dictionary&lt;ButtonAction, ButtonFunctionality&gt; buttonFunctionality) { // Get v int veryLongPress = _instrumenrData.GetValue(1); // gets the data from the instrument itself // calls mapper to get the corresponding functionality ButtonFunctionality functionality = InstructionButtonFunctionalityMapper.Mapper["InstrumentButtonType1" + veryLongPress]; buttonFunctionality.Add(ButtonAction.ShortPress, functionality); } private void AddFunctionalityForMediumPress(Dictionary&lt;ButtonAction, ButtonFunctionality&gt; buttonFunctionality) { int mediumPress = _instrumenrData.GetValue(2); // gets the data from the instrument itself // calls mapper to get the corresponding functionality ButtonFunctionality functionality = InstructionButtonFunctionalityMapper.Mapper["InstrumentButtonType1" + mediumPress]; buttonFunctionality.Add(ButtonAction.MediumPress, functionality); } private void AddFunctionalityForShortPress(Dictionary&lt;ButtonAction, ButtonFunctionality&gt; buttonFunctionality) { int shortPress = _instrumenrData.GetValue(3); // gets the data from the instrument itself // calls mapper to get the corresponding functionality ButtonFunctionality functionality = InstructionButtonFunctionalityMapper.Mapper["InstrumentButtonType1" + shortPress]; buttonFunctionality.Add(ButtonAction.ShortPress, functionality); } public override bool IsAvailable() { // checks some logic and returns tru or false return true; } public override bool IsEnable() { // checks some logic and returns tru or false return true; } } public static class InstructionButtonFunctionalityMapper { private static Dictionary&lt;string, ButtonFunctionality&gt; _mapper; public static Dictionary&lt;string, ButtonFunctionality&gt; Mapper { get { return _mapper ?? (_mapper = FillMapper()); } } private static Dictionary&lt;string, ButtonFunctionality&gt; FillMapper() { var mapper = new Dictionary&lt;string, ButtonFunctionality&gt; { {"InstrumentButtonType1" + "VeryLongPress" + "0", ButtonFunctionality.DoAction1}, {"InstrumentButtonType1" + "VeryLongPress" + "1", ButtonFunctionality.DoAction2}, {"InstrumentButtonType1" + "VeryLongPress" + "2", ButtonFunctionality.DoAction3}, {"InstrumentButtonType1" + "0", ButtonFunctionality.ProgramDown}, {"InstrumentButtonType1" + "1", ButtonFunctionality.ProgramUp}, {"InstrumentButtonType1" + "2", ButtonFunctionality.VolumeDown}, {"InstrumentButtonType1" + "3", ButtonFunctionality.VolumeUp}, {"InstrumentButtonType1" + "4", ButtonFunctionality.DoAction1}, {"InstrumentButtonType1" + "5", ButtonFunctionality.DoAction4}, {"InstrumentButtonType1" + "6", ButtonFunctionality.DoAction5} }; return mapper; } } public enum ButtonFunctionality { VolumeUp, VolumeDown, ProgramUp, ProgramDown, DoAction1, DoAction2, DoAction3, DoAction4, DoAction5 } public enum ButtonAction { ShortPress, MediumPress, LongPress, } public enum ButtonType { PushButton, Volume } </code></pre> <p>Thank you very much !!</p>
<ol> <li>Try to avoid "Magic numbers" like 1,2 etc. Use enum or constants instead.</li> <li>Try to use explicit enum value like ShortPress = 0 ... It doing code more readable.</li> <li>"InstrumentButtonType1" should be constant.</li> <li>AddFunctionalityForMediumPress, AddFunctionalityForShortPress... have same behaviour. Better way is creating one method AddFunctionalityForPress and put different values as parameters.</li> <li>AddButtonFunctionality, AddFunctionalityForShortPress do these methods as extension methods. And then you can see logic sequence like buttonFunctionality.AddButtonFunctionality(short).AddButtonFunctionality(long) ... etc.</li> </ol>
Prevent TablewViewHeader to show when [tableView reloadData] is performed <p>does anyone know if there is a way to prevent my table view header to show (in this case a <strong>UISearchBar</strong>) when a <code>[tableView reloadData]</code> is performed.</p> <p>I want to avoid this behaviour. The only way to show the search bar is when the user scrolls down the table.</p> <p>Thanks</p>
<p>After <code>[tableView reloadData];</code></p> <p>Setting content offset(y position) of tableView might help.</p> <pre><code>CGFloat nSearchBarHeight = 40; CGPoint point = (CGPoint){0,nSearchBarHeight}; tableView.contentOffset = point; </code></pre> <p>Hope that helps.</p>
Capybara selenium xvfb throwing end of file error after recent update of Ubuntu 16.04 <p>Currently in my Ruby on Rails application cucumber test are being run with the <a href="https://github.com/jnicklas/capybara" rel="nofollow">capybara</a> gem and using selenium.</p> <p>Recently after a system update to Ubuntu 16.04 the tests started failing with <code>EOFError: end of file reached</code> errors</p> <p>Additionally, it also occasionally includes the following error.</p> <pre><code>session not created exception from unknown error: Runtime.executionContextCreated has invalid 'context': {"auxData": "frameId":"14314.1","isDefault":true},"id":1,"name":"","origin":"://"} (Session info: chrome=54.0.2840.59) (Driver info: chromedriver=2.21.371461 (633e689b520b25f3e264a2ede6b74ccc23cb636a),platform=Linux 4.4.0-43-generic x86_64) (Selenium::WebDriver::Error::SessionNotCreatedError) </code></pre> <p><a href="http://stackoverflow.com/questions/40011762/eoferror-what-happen-to-my-minitest-selenium-test-how-to-fix-it">This question</a> also refers to something similar but with minitest.</p> <p>This what I believe to be the relevant part of the capybara <code>env.rb</code> file:</p> <pre><code>require 'cucumber/rails' require 'capybara' require 'capybara/cucumber' require 'capybara-screenshot' require 'capybara-screenshot/cucumber' require 'rails/test_help' require 'minitest/rails' require 'mocha/mini_test' require 'headless' require 'selenium-webdriver' require 'rack_session_access/capybara' require 'webmock/cucumber' WebMock.allow_net_connect! include Sprig::Helpers ActionController::Base.allow_rescue = false Dir.mkdir('test_result') unless File.exist?('test_result') # Remove/comment out the lines below if your app doesn't have a database. # For some databases (like MongoDB and CouchDB) you may need to use :truncation instead. begin DatabaseCleaner.strategy = :truncation, { only: [] } DatabaseCleaner.clean_with :truncation, { only: [] } rescue NameError raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it." end Capybara.register_driver :selenium do |app| client = Selenium::WebDriver::Remote::Http::Default.new client.timeout = 15 Capybara::Selenium::Driver.new(app, browser: :chrome, http_client: client) end Capybara.default_driver = :selenium Capybara.javascript_driver = :selenium Capybara.raise_server_errors = true Capybara.default_selector = :css Capybara.default_max_wait_time = 15 Capybara.save_and_open_page_path = 'tmp/capybara' </code></pre> <p>I've looked over at a <a href="https://github.com/thoughtbot/capybara-webkit/issues/782" rel="nofollow">thread in the capybara-webkit gem</a> that looks related, but I'm not actually using webkit.</p> <p>Any help would be appreciated.</p>
<p>Turns out I'm using a gem called <a href="https://github.com/flavorjones/chromedriver-helper" rel="nofollow">chromedriver-helper</a> that was using rbenv to override the version of chromedriver that was actually being used by capybara and selenium to run the tests. The gem readme said to try running <code>chromedriver-update</code> in the context of the rails app, which cleared everything up.</p>
find/replace in SQL server <p>I have a query that I want to use every month, but the table it will point to will change slightly. I want to use a function analogous to find/replace to just update a portion of the table names referenced. Each table will just change its name by the Month_Year for the file. I have tried a local variable with declare/set and it does not work. This is what I would like to do...</p> <pre><code>declare @file_name varchar(max) SET @file_name = 'oct_16' --set as month_year used in table name alter table sp_panel_@file_name add LFDOB varchar(max) </code></pre>
<p>You need dynamic query</p> <pre><code>exec ('alter table sp_panel_+'@file_name+' add LFDOB varchar(max)') </code></pre>
Drawing on python and pycharm <p>I am a beginner on Python. I draw a square with this code.</p> <pre><code>import turtle square=turtle.Turtle() print(square) for i in range(4): square.fd(100) square.lt(90) turtle.mainloop() </code></pre> <p>However, there is another code for drawing square with this code in the book. Apparently, I tried to copy the exact same thing but it didn't work out. Can someone help me to figure out the problem?</p> <pre><code>def drawSquare(t,sz): """Make turtle t draw a square of sz.""" for i in range(4): t.forward(sz) t.left(90) turtle.mainloop() </code></pre>
<p>You need to call the function so it will start:</p> <pre><code>import turtle def drawSquare(t, size): for i in range(4): t.forward(size) t.left(90) turtle.mainloop() drawSquare(turtle.Turtle(), 100) </code></pre>
ASP.Net MVC Authentication - Hide Element in View based on roles <p>Is there a possibility to hand over the Result of the Authorize-Attribute to the View?</p> <p>Let's assume I want to hide 5 links in my Index view based on the memberships of a User.</p> <pre><code>[Authorize(Roles = "Admin")] public ActionResult Index(){ .... } </code></pre> <p>The code above will prevent all users that are not part of the Admin-Group from visiting the Index page.</p> <pre><code>@{ if(User.IsInRole("Admin"){ &lt;a href="#"&gt;Some link to be hidden&lt;/a&gt; } } </code></pre> <p>This code will hide the link if the User is not part of the Admin role. This is basically what I want BUT using this method I have to change the role name on every hidden link if the role would change.</p> <p>Isn't there something like a combination of both? (Schema see below)</p> <pre><code>[Authorize(Roles = "Admin")] //This will pass true to the View if the User is a member of the group "Admin" public ActionResult Index(){ .... } @{ if(User.IsAuthenticated){ //This will read the "Token" and if it's true the if statement will get executed. &lt;a href="#"&gt;Some link to be hidden&lt;/a&gt; } } </code></pre> <p>So - if the User is in Role "Admin" the link will be shown. Is this possible?</p>
<p>You could use <code>ViewBag</code> and <code>ViewData</code> among other things, but I'd suggest passing a model back to the view with properties indicating whether to display the links or not.</p> <pre><code>public class YourViewModel() { public bool ShowHiddenLinks { get; set; } // ... whatever other properties } </code></pre> <p>In your controller you'd then do:</p> <pre><code>[Authorize(Roles = "Admin")] public ActionResult Index() { var yourVm = new YourViewModel(); yourVm.ShowHiddenLinks = true; return View(yourVm); } </code></pre> <p>And your view becomes:</p> <pre><code>@model YourViewModel /* ShowHiddenLinks is true &amp; this view is meant for admins only, so show admin-related links */ @if (Model.ShowHiddenLinks) { &lt;a href="#"&gt;Some link to be hidden&lt;/a&gt; } </code></pre> <p>I've named the viewmodel property <code>ShowHiddenLinks</code> on purpose, so that it becomes re-usable for views meant for other users as well. You can of course extend the viewmodel to feature properties for other roles (e.g. a view which is accessible by admins and moderators, each with their own distinct set of hidden links), or create one viewmodel per role—it all depends on the scenario.</p>
Work with a row in a pandas dataframe without incurring chain indexing (not coping just indexing) <p>My data is organized in a dataframe:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) </code></pre> <p>Which looks like this (only much bigger):</p> <pre><code> Col1 Col2 Col3 Col4 R1 4 10 100 AAA R2 5 20 50 BBB R3 6 30 -30 AAA R4 7 40 -50 CCC </code></pre> <p>My algorithm loops through this table rows and performs a set of operations. </p> <p>For cleaness/lazyness sake, I would like to work on a single row at each iteration without typing <code>df.loc['row index', 'column name']</code> to get each cell value</p> <p>I have tried to follow the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">right style</a> using for example:</p> <pre><code>row_of_interest = df.loc['R2', :] </code></pre> <p>However, I still get the warning when I do:</p> <pre><code>row_of_interest['Col2'] = row_of_interest['Col2'] + 1000 SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame </code></pre> <p>And it is not working (as I intended) it is making a copy</p> <pre><code>print df Col1 Col2 Col3 Col4 R1 4 10 100 AAA R2 5 20 50 BBB R3 6 30 -30 AAA R4 7 40 -50 CCC </code></pre> <p>Any advice on the proper way to do it? Or should I just stick to work with the data frame directly?</p> <p>Edit 1:</p> <p>Using the replies provided the warning is removed from the code but the original dataframe is not modified: The "row of interest" <code>Series</code> is a copy not part of the original dataframe. For example:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) row_of_interest = df.loc['R2'] row_of_interest.is_copy = False new_cell_value = row_of_interest['Col2'] + 1000 row_of_interest['Col2'] = new_cell_value print row_of_interest Col1 5 Col2 1020 Col3 50 Col4 BBB Name: R2, dtype: object print df Col1 Col2 Col3 Col4 R1 4 10 100 AAA R2 5 20 50 BBB R3 6 30 -30 AAA R4 7 40 -50 CCC </code></pre> <p>Edit 2:</p> <p>This is an example of the functionality I would like to replicate. In python a list of lists looks like:</p> <pre><code>a = [[1,2,3],[4,5,6]] </code></pre> <p>Now I can create a "label" </p> <pre><code>b = a[0] </code></pre> <p>And if I change an entry in b:</p> <pre><code>b[0] = 7 </code></pre> <p>Both a and b change.</p> <pre><code>print a, b [[7,2,3],[4,5,6]], [7,2,3] </code></pre> <p>Can this behavior be replicated between a pandas dataframe labeling one of its rows a pandas series?</p>
<p>This should work:</p> <pre><code>row_of_interest = df.loc['R2', :] row_of_interest.is_copy = False row_of_interest['Col2'] = row_of_interest['Col2'] + 1000 </code></pre> <p>Setting <code>.is_copy = False</code> is the trick</p> <p>Edit 2:</p> <pre><code>import pandas as pd import numpy as np data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']} df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4']) row_of_interest = df.loc['R2'] row_of_interest.is_copy = False new_cell_value = row_of_interest['Col2'] + 1000 row_of_interest['Col2'] = new_cell_value print row_of_interest df.loc['R2'] = row_of_interest print df </code></pre> <p>df:</p> <pre><code> Col1 Col2 Col3 Col4 R1 4 10 100 AAA R2 5 1020 50 BBB R3 6 30 -30 AAA R4 7 40 -50 CCC </code></pre>
I am new to swift and I don't understand this function declaration <pre><code>public func computeAxis(var yMin yMin: Double, var yMax: Double) </code></pre> <p>what is a "var yMin yMin: Double" declaration?</p>
<p>It's the old Swift 2, the <code>var</code> means the <code>yMin</code> can be changed in the function (which is deprecated and Swift 3 has <code>inout parameter</code> concept) and the first <code>yMin</code> is <code>argument label</code> you should use when calling <code>computeAxis</code> function which in this case as it is the same as <code>parameter name</code> could be omitted (in the second parameter it is) and both parameters are of type <code>Double</code> and you should call the function like:</p> <pre><code>computeAxis(yMin: 1.2, yMax: 3.7) </code></pre>
Bring another application into foreground when WPF XAML window is in Maximized <p>I have a WPF application in which the main window is set to full screen via <code>WindowState="Maximized"</code> in the <code>Window</code> tag. In the application, I'm opening PowerPoint through the Office Interop libraries with the intention that PowerPoint opens in the foreground, on top of the WPF application. However, PowerPoint is not consistently coming to the foreground (particularly on Windows 7 machines). In these cases I have to press the Windows key to bring up the Windows Taskbar and click on the PowerPoint icon. </p> <p>I've tried a few things, such as using <code>SetForegroundWindow()</code> from the Win32 API, the <code>.Activate()</code> function in the PowerPoint Interop library, and the <code>AutomationElement</code> class (here's some code for the last one):</p> <pre><code>Process process = System.Diagnostics.Process.GetProcessesByName("POWERPNT").FirstOrDefault(); AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle); if (element != null) { element.SetFocus(); } </code></pre> <p>However, none of these seem to consistently bring PowerPoint to the front. Does anyone know why exactly this behavior is occurring and how best to get PowerPoint into the foreground?</p>
<pre><code> [DllImport("user32.dll")] public static extern bool ShowWindowAsync(HandleRef hWnd, int nCmdShow); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr WindowHandle); public const int SW_RESTORE = 9; static void Main(string[] args) { Process process = System.Diagnostics.Process.GetProcessesByName("POWERPNT").FirstOrDefault(); IntPtr hWnd = IntPtr.Zero; hWnd = process.MainWindowHandle; ShowWindowAsync(new HandleRef(null, hWnd), SW_RESTORE); SetForegroundWindow(process.MainWindowHandle); } </code></pre> <p>works fine with me.</p>
How to get Relative Path from Files of one choosen Folder? <p><a href="https://i.stack.imgur.com/Ij5yM.png" rel="nofollow">enter image description here</a></p> <p><a href="https://i.stack.imgur.com/04F12.png" rel="nofollow">enter image description here</a> I get only the relative path of the directory/folders but not of the files in it? I can't really find the bug... . I do not understand why it won't get the relative path of the files but of the folders it will.</p>
<p>From <a href="https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx" rel="nofollow">MSDN</a> :</p> <p>Directory.GetFiles Method (String)</p> <blockquote> <p>Returns the names of files (including their paths) in the specified directory.</p> </blockquote> <p>So you should do this:</p> <pre><code>foreach(string filename in Directory.GetFiles(path)) { result.Append(Path.GetFileName(filename), "FILE"); } </code></pre>
JQuery and Ajax: How to store returned data in variables? <p>I have the following code:</p> <pre><code> window.onload = function() { var eMail = "&lt;?php echo $log; ?&gt;"; var aRticleid = "&lt;?php echo $articleid1; ?&gt;"; $.ajax({ type: "GET", url: 'aquireLikes.php?email='+eMail+'&amp;id='+aRticleid+'', success: function(data){ } }); }; </code></pre> <p>This executes a php script. There is three variables in the PHP script that gets set to true if certain conditions are met. I want to store the returned value of these variable in a set of JavaScript variables on my page that call the aquireLikes.php page. How can I do this? It would be something like this but actually works:</p> <pre><code> window.onload = function() { var eMail = "&lt;?php echo $log; ?&gt;"; var aRticleid = "&lt;?php echo $articleid1; ?&gt;"; $.ajax({ type: "GET", url: 'aquireLikes.php?email='+eMail+'&amp;id='+aRticleid+'', success: function(data){ var liked = aquirelikes.php.$liked; } }); }; </code></pre> <p>I know above is complete nonsense but you get the hint. So how can I store the returned values in javascript variables? Here is my aquireLikes file:</p> <pre><code> &lt;?php $email = $_GET["email"]; $articleid1 = $_GET["id"]; $done = false; $thing = mysql_query("SELECT `id` FROM likes WHERE id=(SELECT MAX(id) FROM likes)"); $lastrow = mysql_fetch_row($thing); $lastid = $lastrow[0]; if($lastid == null || $lastid == '0'){ $lastid = '1'; } $state1 = ''; for ($i=1; $i &lt;= $lastid+1; $i++) { $current = mysql_query("SELECT * FROM likes WHERE id=$i"); while ($row = mysql_fetch_array($current)) { $id1 = $row[0]; $userid1 = $row[1]; $state1 = $row[2]; $articleid1 = $row[3]; if($done == false){ if($email == $userid1 &amp;&amp; $articleid1 == $id &amp;&amp; $state1 == '1'){ $liked = true; $disliked = false; $done = true; echo "&lt;script&gt;console.log('Liked!');&lt;/script&gt;"; break; }else{ $liked = false; } if($email == $userid1 &amp;&amp; $articleid1 == $id &amp;&amp; $state1 == '0'){ $disliked = false; $liked = false; $done = true; echo "&lt;script&gt;console.log('NONE!');&lt;/script&gt;"; break; } if($email == $userid1 &amp;&amp; $articleid1 == $id &amp;&amp; $state1 == '2'){ $disliked = true; $liked = false; $done = true; echo "&lt;script&gt;console.log('disliked!');&lt;/script&gt;"; break; }else{ $disliked = false; } } } } ?&gt; </code></pre>
<p>Your ajax would look like this:</p> <pre><code> var liked; $.ajax({ type: "GET", url: 'aquireLikes.php?email='+eMail+'&amp;id='+aRticleid+'', type: 'json', success: function(data){ liked = data.liked; } }); </code></pre> <p>And in php you would have to return:</p> <pre><code>echo json_encode($data) </code></pre> <p>Php file has to output only json data!</p> <p>This is just example of implementation.</p>
Java input from text file with an unusual format <p>So I realize this text format may not be very unusual. However, I've been trying many ideas to read this correctly into the objects needed and know there has to be a better way. Here is what the file looks like:</p> <pre><code>S S n B 1 E 2 B N n C 2 F 3 C N n D 2 GA 4 D N n GA 1 E N n B 1 F 3 H 6 F N n I 3 GA 3 C 1 A N g H B b U 2 GB 2 F 1 I N n GA 2 GB 2 GB N g </code></pre> <p>So the first line of each pair is the name of the node S, whether its a starting node N/s then whether its a goal node g/n The second line is the children of node S, and their distance weight. For example, Node S has child node B with a distance of 1, and child node E with a distance of 2</p> <p>I'm working with two object types, Nodes, and Edges. Example below. (Constructors ommitted)</p> <p>Does anyone have tips on how to read this type of input efficiently?</p> <pre><code>public class Edge { public String start; public String end; public int weight; public class Node { public String name; public boolean start = false; public boolean goal = false; public ArrayList&lt;Edge&gt; adjecentNodes = new ArrayList&lt;Edge&gt;(); </code></pre>
<p>Actually your question is almost too broad and unspecific, but I am in the mood to give you some starting points. But please understand that you could easily fill several hours of computer science lectures on this topic; and that is not going to happen here.</p> <p>First, you have to clarify some requirements (for yourself; or together with the folks working on this project):</p> <ol> <li>Do you really need to focus on <strong>efficient</strong> reading/building of your graph? I rather doubt that: building the graph happens <strong>once</strong>; but the computations that you probably do later on may run for a much longer time. So one primary focus should be on designing that object/class model that allows you to <strong>efficiently</strong> solve the problems that you want to solve on that graph! For example: it might be beneficial to already <em>sort</em> edges by distance/weight when creating the graph. Or maybe not. Depends on later use cases! And even when you are talking about <strong>huge</strong> files that need efficient processing ... that still means: you are talking about <strong>huge</strong> graphs; so all the more reason to find a good <strong>model</strong> for that graph.</li> <li>Your description of the file is not clear. For example: is this a (un)directed graph? Meaning - can you travel on any edge in <em>both</em> direction? And sorry, I didn't get what a "goal" node is supposed to be. (I guess you have <em>directed</em> edges that go one way only, as that would explain those rows in the example where nodes do not have any children). Of course, sometimes requirements become clear in that moment when you start writing real code. But this here is really about concepts/data/algorithms. So the earlier you answer all such questions, the better for you. </li> </ol> <p>Secondly, a suggestion in which order to do things:</p> <ol> <li>As said, clarify all your requirements. Spend some serious time just <strong>thinking</strong> about the properties of the graphs you are dealing with; and what problems you later have to solve on them. </li> <li>Start coding; ideally you use TDD/unit testing here. Because all of the things you are going to do can be nicely sliced into small work packages, and each one could be tested with unit-tests. Do <strong>not</strong> write all your code first, to then, after 2 days running your first experiments! The first thing you code: your Node/Edge classes ... because you want to play around with things like: what arguments do my constructors need? how can I make my classes immutable (data is pushed in by constructors only)? Do I want distance to be a property of my Edge; or can I just go with <strong>Node</strong> objects (and represent edges as <code>Map&lt;Node, Integer&gt;</code> --- meaning each node just knows its neighbors and the distance to get there!)</li> <li>Then, when you are <strong>convinced</strong> that that Node/Edge fit your problem, then you start writing code that takes <strong>strings</strong> and builds Node/Edges out of those strings.</li> <li>You also went to spent some time on writing good <em>dump</em> methods; ideally you call graph.dump() ... and that produces a string matching your input format (makes a nice test later on: reading + dumping should result in identical files!)</li> <li>Then, when "building from strings" works ... then you write the few lines of "file parsing code" that uses some BufferedReader, FileReader, Scanner, Whatever mechanism to dissect your input file into strings ... which you then feed into the methods you created above for step 3.</li> </ol> <p>And, seriously: if this is for school/learning:</p> <ul> <li>Try to talk to your peers often. Have them look at what you are doing. Not too early, but also not too late.</li> <li>Really, seriously: consider throwing away stuff; and starting from scratch again. For each of the steps above, or after going through the whole sequence. It is an incredible experience to do that; because typically, you come up with new, different, interesting ideas each time you do that. </li> </ul> <p>And finally, some specific hints:</p> <p>It is tempting to use "public" (writable) fields like start/end/... in your classes. But: consider not doing that. Try to <em>hide</em> as much of the internals of your classes. Because that will make it easier (or <em>possible</em>!) later on to change one part of your program without the need to change anything else, too. </p> <p>Example: </p> <pre><code>class Edge { private final int distance; private final Node target; public Edge(int distance, Node target) { this.distance = distance; this.target = target; } ... </code></pre> <p>This creates an <strong>immutable</strong> object - you can't change its core internal properties after the object was created. That is very often helpful. </p> <p>Then: <em>override</em> methods like <em>toString()</em>, <em>equals()</em>, <em>hashCode()</em> in your classes; and use them. For example, toString() can be used to create a nice, human-readable dump of a node.</p> <p>Finally: if you liked all of that, consider remembering my user id; and when you reach enough reputation to "upvote", come back and upvote ;-)</p>
Search for a combination in dataframe to change cell value <p>I want to replace values in a column if the a combination of values in two columns is valid. Lets say I have the following <code>DataFrame</code></p> <pre><code>df = pd.DataFrame([ ['Texas 1', '111', '222', '333'], ['Texas 1', '444', '555', '666'], ['Texas 2', '777','888','999'] ]) 0 1 2 3 0 Texas 1 111 222 333 1 Texas 1 444 555 666 2 Texas 2 777 888 999 </code></pre> <p>And if I want to replace the value in <code>column 2</code> if <code>column 0 = Texas 1</code> and the value of <code>column 2 = 222</code>I'm doing the following:</p> <pre><code>df.ix[ (df.Column 0=='Texas 1')&amp;(df.Column 2 =='222'),Column 2] = "Success" </code></pre> <p>That works fine for a few combinations. The part where I'm lost is how to do this for over 300 combinations? I thought maybe I could use a <code>dict</code> and store the key, which would be <code>'Success'</code> or whatever other value. And the list could be the combination. Kind of like this. </p> <pre><code>a["Success"] = [Texas 1, 222] &gt;&gt;&gt; a {"Success": [Texas 1, 222]} </code></pre> <p>But I'm not sure how to do that in a <code>DataFrame</code>.</p>
<p>You have all almost all your code, just create <code>dictionary</code> or <code>list</code> and iterate over it and you are done.</p> <pre><code>import pandas as pd combinations = [['key1', 'key2', 'msg']] combinations.append(['Texas 1', '222', 'triple two']) combinations.append(['Texas 1', '555', 'triple five']) df = pd.DataFrame([ ['Texas 1', '111', '222', '333'], ['Texas 1', '444', '555', '666'], ['Texas 2', '777','888','999'] ]) for c in combinations: df.ix[(df[0] == c[0]) &amp; (df[2] == c[1]), 1] = c[2] </code></pre> <p>Output:</p> <pre><code> 0 1 2 3 0 Texas 1 triple two 222 333 1 Texas 1 triple five 555 666 2 Texas 2 777 888 999 </code></pre>
'DataFrame' object is not callable <p>I'm trying to create a heatmap using Python on Pycharms. I've this code:</p> <pre><code>import numpy as np import pandas as pd import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt data1 = pd.read_csv(FILE") freqMap = {} for line in data1: for item in line: if not item in freqMap: freqMap[item] = {} for other_item in line: if not other_item in freqMap: freqMap[other_item] = {} freqMap[item][other_item] = freqMap[item].get(other_item, 0) + 1 freqMap[other_item][item] = freqMap[other_item].get(item, 0) + 1 df = data1[freqMap].T.fillna(0) print(df) </code></pre> <p>My data is stored into a CSV file. Each row represents a sequence of products that are associated by a Consumer Transaction.The typically Basket Market Analysis:</p> <pre><code>99 32 35 45 56 58 7 72 99 45 51 56 58 62 72 17 55 56 58 62 21 99 35 21 99 44 56 58 7 72 72 17 99 35 45 56 7 56 62 72 21 91 99 35 99 35 55 56 58 62 72 99 35 51 55 58 7 21 99 56 58 62 72 21 55 56 58 21 99 35 99 35 62 7 17 21 62 72 21 99 35 58 56 62 72 99 32 35 72 17 99 55 56 58 </code></pre> <p>When I execute the code, I'm getting the following error:</p> <pre><code>Traceback (most recent call last): File "C:/Users/tst/PycharmProjects/untitled1/tes.py", line 22, in &lt;module&gt; df = data1[freqMap].T.fillna(0) File "C:\Users\tst\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 1997, in __getitem__ return self._getitem_column(key) File "C:\Users\tst\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2004, in _getitem_column return self._get_item_cache(key) File "C:\Users\tst\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\generic.py", line 1348, in _get_item_cache res = cache.get(item) TypeError: unhashable type: 'dict' </code></pre> <p>How can I solve this problem? </p> <p>Many thanks!</p>
<p>You are reading a csv file but it has no header, the delimiter is a space not a comma, and there are a variable number of columns. So that is three mistakes in your first line.</p> <p>And data1 is a DataFrame, freqMap is a dictionary that is completely unrelated. So it makes no sense to do data1[freqMap].</p> <p>I suggest you step through this line by line in jupyter or a python interpreter. Then you can see what each line actually does and experiment.</p>
How to make two labels consecutively? Second label correctly show new line? <p>How to make two labels consecutively, so that the second end of the label at the screen moved the remainder of the text on a new line?</p> <p>Example. First label - "I got it. Take me to the" Second label - "Home Screen"</p> <p><a href="https://i.stack.imgur.com/uc4vl.png" rel="nofollow"><img src="https://i.stack.imgur.com/uc4vl.png" alt="enter image description here"></a></p>
<pre><code>&lt;Grid Padding="0, 10, -10, 10" RowSpacing="0"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.GestureRecognizers&gt; &lt;TapGestureRecognizer Command="{Binding OpenHomePageCommand}"/&gt; &lt;/Grid.GestureRecognizers&gt; &lt;controls:ExtendedLabel x:Name="SimpleLabel" Grid.Row="0" Grid.Column="0" FontFamily="OpenSans-Semibold" FontSize="16.4" InputTransparent="True" Text="I got it. Take me to the " TextColor="{StaticResource Onahau}" VerticalOptions="EndAndExpand" /&gt; &lt;controls:ExtendedLabel x:Name="UnderlineLabel" Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" FontFamily="OpenSans-Semibold" FontSize="16.4" InputTransparent="True" IsUnderline="True" Text="Home Screen" TextColor="{StaticResource Onahau}" VerticalOptions="EndAndExpand" /&gt; &lt;/Grid&gt; </code></pre>
Better way of passing data between pages: HTML5 storage vs Angular service <p>I am trying to pass data between two pages which are having Angular controllers. </p> <p>Now I came across 2 different ways to pass data:</p> <blockquote> <ol> <li>via Angular service (similar to <a href="http://stackoverflow.com/a/20181543/3098658">here</a>) </li> <li>using HTML5 storage option (either Local/Session <a href="http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage">as shown here</a>)</li> </ol> </blockquote> <p>From development perspective I wanted to know as which is more preferred method of passing data? Can this scenario change if we are dealing with large JSON data ?</p>
<p>This answer - <a href="http://stackoverflow.com/questions/28846266/ionic-local-storage-vs-using-service">Ionic local storage vs using service</a> - gives a good summary of the differences: local storage should be used primarily for data that will be used across a number of sessions or persists for a long time, whereas data in an Angular service is tied to that page. </p>
Homebrew install the old version of flow <p>I cd to my react-native project directory, and run <code>flow</code>, it prompts me <code>Launching Flow server for /Users/... Wrong version of Flow. The config specifies version ^0.32.0 but this is version 0.33.0</code>. How do I install the previous version flow with Homebrew?</p>
<p>If you run <code>brew info flow</code> in the console, you'll see a line similar to the following:</p> <pre><code>flow: stable 0.33.0 (bottled), HEAD </code></pre> <p>This means that the person managing the flow homebrew formula is removing old versions as the version gets updated, so it's impossible for you to access any old versions, barring performing some behind the scenes business I'm unaware of.</p> <hr> <p>Luckily, there's a solution for you. I assume you're using npm, in which case you can try the following:</p> <pre><code>npm install [email protected] -g </code></pre> <p>This will install a binary wrapper for flow, packaged through npm, in which previous versions are all available. By installing globally, you can use the <code>flow</code> commands in the command line.</p> <hr> <p>If you don't want to install globally, for fear of conflicting with other projects, etc., you can still install locally and use flow:</p> <pre><code> npm install [email protected] </code></pre> <p>Now, add the following to <code>package.json</code>:</p> <pre><code>"scripts": { ... "flow": "flow ." }, </code></pre> <p>And now, you'll be able to run flow on your project with the command:</p> <pre><code>npm run flow </code></pre>
Why on iMac bash doesn't see some files <p>I have iMac and my bash on terminal has .bashrc, .bash_profile,.bash_login. My questions are:</p> <ol> <li>what should be in each file</li> <li>when I try <code>ls -ltr</code> or <code>grep something .bashrc</code> it says: <code>NO SUCH FILE OR DIRECTORY</code></li> </ol>
<ol> <li>See the <a href="https://www.gnu.org/software/bash/manual/html_node/Bash-Startup-Files.html" rel="nofollow">documentation</a>. In short, they are scripts to customize your command-line environment. Also, don't forget <code>.profile</code>.</li> <li>The files do not exist by default. You need to create them.</li> </ol>
MongoDB is not marshaling a value before storing it <p>I'm using a custom JSON marshaller/unmarshaller for a mapping between integers and strings in Go. The problem is that values are being stored in the database as integers instead of strings. In the example below, I would expect this to be stored in the MongoDB database:</p> <pre><code>{ "_id" : "id123", "desc" : "Red Delicious", "value" : "apple" } </code></pre> <p>Instead I get:</p> <pre><code>{ "_id" : "id123", "desc" : "Red Delicious", "value" : 1 } </code></pre> <p>As the test shows, marshalling and unmarshalling are working fine. What's going on?</p> <p>Here's an example as a Go test (save to unmarshal_test.go and "go test"). </p> <pre><code>package testunmarshal import ( "fmt" "testing" "encoding/json" mgo "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) type Const int const ( Apple Const = 1 Banana = 2 Cherry = 4 ) type Record struct { Id string `bson:"_id" json:"id"` Desc string `bson:"desc" json:"desc"` Value Const `bson:"value" json:"value` } func (intValue Const) Code() string { switch intValue { case Apple: return "apple" case Banana: return "banana" case Cherry: return "cherry" } return "invalid" } func (intValue *Const) UnmarshalJSON(data []byte) (err error) { switch string(data) { case `"apple"`: *intValue = Apple case `"banana"`: *intValue = Banana case `"cherry"`: *intValue = Cherry default: return fmt.Errorf("Invalid fruit %s", data) } return nil } func (intValue *Const) MarshalJSON() ([]byte, error) { return []byte(fmt.Sprintf(`"%s"`, intValue.Code())), nil } func TestMarshalJSON(t *testing.T) { var orig = Record { Id: "id456", Desc: "Cavendish", Value: Banana, } var copy Record bytes, err := json.Marshal(&amp;orig) if err != nil { t.Errorf("Marshal failed: %s", err.Error()) return } err = json.Unmarshal(bytes, &amp;copy) if err != nil { t.Errorf("Unmarshal failed: %s", err.Error()) return } if orig.Value != copy.Value { t.Errorf("Expected %d=%s, got %d=%s", orig.Value, orig.Value.Code(), copy.Value, copy.Value.Code()) } } func TestMarshalBSON(t *testing.T) { var orig = Record { Id: "id456", Desc: "Cavendish", Value: Banana, } var copy Record bytes, err := bson.Marshal(&amp;orig) if err != nil { t.Errorf("Marshal failed: %s", err.Error()) return } err = bson.Unmarshal(bytes, &amp;copy) if err != nil { t.Errorf("Unmarshal failed: %s", err.Error()) return } if orig.Value != copy.Value { t.Errorf("Expected %d=%s, got %d=%s", orig.Value, orig.Value.Code(), copy.Value, copy.Value.Code()) } } func TestMongo(t *testing.T) { var rec1 = Record { Id: "id123", Desc: "Red Delicious", Value: Apple, } var rec2 Record sess, err := mgo.Dial("localhost") if err != nil { t.Errorf(err.Error()) return } db := sess.DB("test") if db == nil { t.Fatal("Failed to connect to database") return } col := db.C("fruit") if col == nil { t.Fatal("Failed to open collection") return } // defer col.DropCollection() err = col.Insert(&amp;rec1) if err != nil { t.Fatal("Failed to insert: %s", err.Error()) return } err = col.Find(bson.M{}).One(&amp;rec2) if err != nil { t.Fatal("Failed to retrieve stored object: %s", err.Error()) return } if rec1.Value != rec2.Value { t.Errorf("Expected %d=%s, got %d=%s", rec1.Value, rec1.Value.Code(), rec1.Value, rec2.Value.Code()) } } </code></pre> <p><strong>Edit</strong>: Added more tests to demonstrate that marshalling and unmarshalling are working.</p>
<p>The bson encoder does not use the JSON marshaling interfaces. Implement the <a href="https://godoc.org/gopkg.in/mgo.v2/bson#Getter" rel="nofollow">Getter</a> interface:</p> <pre><code>func (intValue Const) GetBSON() (interface{}, error) { return intValue.Code(), nil } </code></pre> <p>You will also want to implement the <a href="https://godoc.org/gopkg.in/mgo.v2/bson#Setter" rel="nofollow">Setter</a> interface. </p> <pre><code>func (intValue *Const) SetBSON(raw bson.Raw) error { var data int if err := raw.Unmarshal(&amp;data); err != nil { return err } switch data { case `"apple"`: *intValue = Apple case `"banana"`: *intValue = Banana case `"cherry"`: *intValue = Cherry default: return fmt.Errorf("Invalid fruit %s", data) } return nil } </code></pre>
ionic 2 ionicViewLoad() not firing <p>I am creating a mock ionic project, where I am using Google maps, the data is fetched from the remote server and the view is rendered only after the data is received so when I call the loadMap() method in ngOnInit() lifecycle hook It throws an error but it doesn't, when I use ionViewLoad() method.However,this method doesn't gets fired at all. The component code snippet,</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>ionViewLoaded(){ this.loadMap(); console.log('map called'); } loadMap() { let latLng = new google.maps.LatLng(11.0168445, 76.95583209999995); let mapOptions: Object = { center: latLng, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP } this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions); console.log(this.post.loc[0].pin.lat); }</code></pre> </div> </div> </p>
<p>API have changed. In Ionic 2 RC.1 it is changed to "<code>ionViewDidLoad</code>". For more information, look <a href="https://ionicframework.com/docs/v2/api/navigation/NavController/" rel="nofollow">here</a>.</p>
How to compare versions of an Amazon S3 object? <p>Versioning of Amazon S3 buckets is nice, but I don't see any easy way to compare versions of a file - either through the console or through any other app I found.</p> <p>S3Browser seems to have the best versioning support, but no comparison.</p> <p>Is there a way to compare versions of a file on S3 without downloading both versions and comparing them manually?</p> <p>--</p> <p>EDIT: I just started thinking that some basic automation should not be too hard, see snippet below. Question remains though: is there any tool that supports this properly? This script may be fine for me, but not for non-dev users.</p> <pre><code>#!/bin/bash # s3-compare-last-versions.sh if [[ $# -ne 2 ]]; then echo "Usage: `basename $0` &lt;bucketName&gt; &lt;fileKey&gt; " exit 1 fi bucketName=$1 fileKey=$2 latestVersionId=$(aws s3api list-object-versions --bucket $bucketName --prefix $fileKey --max-items 2 | json Versions[0].VersionId) previousVersionId=$(aws s3api list-object-versions --bucket $bucketName --prefix $fileKey --max-items 2 | json Versions[1].VersionId) aws s3api get-object --bucket $bucketName --key $fileKey --version-id $latestVersionId $latestVersionId".js" aws s3api get-object --bucket $bucketName --key $fileKey --version-id $previousVersionId $previousVersionId".js" diff $latestVersionId".js" $previousVersionId".js" </code></pre>
<p>You can't view file contents at all via S3, so you definitely can't compare the contents of files via S3. You would have to download the different versions and then use a tool like <code>diff</code> to compare them.</p>
Creating growth series in R <p>Consider the Loblolly dataset in the MASS package.</p> <pre><code>head(Loblolly) height age Seed 1 4.51 3 301 15 10.89 5 301 29 28.72 10 301 43 41.74 15 301 57 52.70 20 301 71 60.92 25 301 </code></pre> <p>For each seed I would like to create new variables height1, age1 and height2,age 2. The output would be something like...</p> <pre><code>height1 age1 height2 age2 Seed 4.51 3 10.89 5 301 10.89 5 28.72 10 301 28.72 10 41.74 15 301 </code></pre> <p>Forgive me if this has been asked before but I have been searching around and cannot find anything similar.</p>
<p>If I understand your question correctly, you should be able to do something like this:</p> <pre><code># get data frame length n &lt;- dim(Loblolly)[1] df &lt;- NULL # combine appropriate vectors df$height1 &lt;- Loblolly$height[1:(n-1)] df$age1 &lt;- Loblolly$age[1:(n-1)] df$height2 &lt;- Loblolly$height[2:n] df$age2 &lt;- Loblolly$age[2:n] df$Seed &lt;- Loblolly$Seed[1:(n-1)] # flatten list as data.frame head(data.frame(df)) </code></pre>
How to embed video within a javascript slidetoggle <p>I'm attempting to achieve a javascript slide toggle with a youtube video embedded after the text once the button is clicked but it just won't work. Does anyone know what I'm doing wrong?</p> <p>HTML:</p> <pre><code>&lt;h2&gt; What Is Black Ballad? &lt;/h2&gt; &lt;p&gt; This is some text. &lt;/p&gt; &lt;p class="reveal1"&gt; This is some more text and then an embedded video. &lt;div class="video-container"&gt; &lt;iframe width="560" height="315" src="https://www.youtube.com/embed/JfHXbPv9cUg" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;/p&gt; &lt;div id="more1" align="center" title="View More"&gt; &lt;img src="http://www.blackballad.co.uk/wp-content/uploads/2016/10/drop.png" width="20px" height="20px"&gt; &lt;/div&gt; </code></pre> <p>JavaScript:</p> <pre><code>$(document).ready(function(){ $("#more1").click(function(){ $(".reveal1").slideToggle("slow"); }); }); </code></pre> <p>CSS:</p> <pre><code>.reveal1 { display: none; } </code></pre>
<p>Its working in this code snippet i made.It seems you had a weird issue with the <p> tag wrapping the iframe.</p> <p>Check it out. </p> <h2> What Is Black Ballad? </h2> <p> This is some text. </p> <p> This is some more text and then an embedded video.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){ $("#more1").click(function(){ $(".reveal1").slideToggle("slow"); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.reveal1 { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"&gt;&lt;/script&gt; &lt;h2&gt; What Is Black Ballad? &lt;/h2&gt; &lt;p&gt; This is some text. &lt;/p&gt; &lt;div class="reveal1"&gt; This is some more text and then an embedded video. &lt;div class="video-container"&gt; &lt;iframe width="560" height="315" src="https://www.youtube.com/embed/JfHXbPv9cUg" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="more1" align="center" title="View More"&gt; &lt;button&gt; Click me &lt;/button&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
From which row a data.frame variable have a constant value <p>I would like to calculate the mean of a variable on a data.frame in R from the row which another variable start to have a constant value. I usually use dplyr for this database kind of task but I dont figure out how to do this, here is an example:</p> <pre><code>s&lt;-"no Spc PSize 2 0 6493 2 0 9281 2 12 26183 2 12 36180 2 12 37806 2 12 37765 3 12 36015 3 12 26661 3 0 14031 3 0 5564 3 1 17701 3 1 20808 3 1 31511 3 1 44746 3 1 50534 3 1 54858 3 1 58160 3 1 60326" d&lt;-read.delim(textConnection(s),sep="",header=T) mean(d[1:10,3]) sd(d[1:10,3]) </code></pre> <p>From the row 11 the variable spc have a constant value, so this is the place I want to split the data.frame </p> <pre><code>mean(d[11:18,3]) sd(d[11:18,3]) </code></pre> <p>I can calculate it by hand, but that is not the idea...</p>
<p><strong>Option 1:</strong> Using <code>rleid</code> from the <code>data.table</code> package:</p> <pre><code>d %&gt;% group_by(rlid = rleid(Spc)) %&gt;% summarise(mean_size = mean(PSize), sd_size = sd(PSize)) %&gt;% slice(n()) </code></pre> <p>gives:</p> <pre><code># A tibble: 1 × 3 rlid mean_size sd_size &lt;int&gt; &lt;dbl&gt; &lt;dbl&gt; 1 4 42330.5 16866.59 </code></pre> <hr> <p><strong>Option 2:</strong> Using <code>rle</code>:</p> <pre><code>startrow &lt;- sum(head(rle(d$Spc)$lengths, -1)) + 1 d %&gt;% slice(startrow:n()) %&gt;% summarise(mean_size = mean(PSize), sd_size = sd(PSize)) </code></pre> <p>gives:</p> <pre><code> mean_size sd_size 1 42330.5 16866.59 </code></pre> <hr> <p><strong>Option 3:</strong> If you want to calculate for two groups (last and others) you should use <code>group_by</code> instead of <code>filter</code> and create a new grouping vector (<code>rep_vec</code>) with <code>rle</code>:</p> <pre><code>rep_vec &lt;- c(sum(head(rle(d$Spc)$lengths, -1)), tail(rle(d$Spc)$lengths, 1)) d %&gt;% group_by(grp = rep(c('others','last_group'), rep_vec)) %&gt;% summarise(mean_size = mean(PSize), sd_size = sd(PSize)) </code></pre> <p>which gives:</p> <pre><code> grp mean_size sd_size (chr) (dbl) (dbl) 1 last_group 42330.5 16866.59 2 others 23597.9 13521.32 </code></pre> <p>If you want to include the rows, you can change the code to:</p> <pre><code>d %&gt;% mutate(rn = row_number()) %&gt;% group_by(grp = rep(c('others','last_group'), rep_vec)) %&gt;% summarise(mean_size = mean(PSize), sd_size = sd(PSize), rows = paste0(range(rn), collapse=':')) </code></pre> <p>which gives:</p> <pre><code> grp mean_size sd_size rows &lt;chr&gt; &lt;dbl&gt; &lt;dbl&gt; &lt;chr&gt; 1 last_group 42330.5 16866.59 11:18 2 others 23597.9 13521.32 1:10 </code></pre>
executing multimatch ElasticSearch with boolean operations in query <p>Can I execute multimatch search with ElasticSearch and NEST in a way I can pass query with boolean operations inside the query? It appears all terms I passed to multimatch are by default linked with OR (which can be changed to other operator).</p> <p>I'd like ES to evaluate boolean operators from the query, ex. "A &amp;&amp; B || C" and the same search multiple fields. </p>
<p>Yes you can <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html#operator-min" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html#operator-min</a></p> <pre><code>{ "multi_match" : { "query": "Will Smith", "type": "best_fields", "fields": [ "first_name", "last_name" ], "operator": "and" } } </code></pre>
Passing Powershell argument to Provider=Microsoft.Jet.OLEDB.4.0 connection <p>I am trying to create a Powershell script that will be used to add a single table with two fields and add a value to one of those fields within a Access DB. I would like to be able to pass the DB path and value as an argument to the script. </p> <p>However, I keep getting errors with the DB path. At first I got this error:</p> <p><code>Exception calling "Open" with "1" argument(s): "Could not find file 'H:\$DB'." At C:\users\user1\Desktop\Read_PCRes_DB.ps1:8 char:1 + $conn.Open('Provider=Microsoft.Jet.OLEDB.4.0; Data Source=$DB;') + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : COMException</code></p> <p>This happened no matter how I entered the argument; with quotes, without, or with a path with no spaces.</p> <p>So then I disconnected my mapped H:\ drive. Now I get this error:</p> <p><code>Exception calling "Open" with "1" argument(s): "Cannot start your application. The workgroup information file is missing or opened exclusively by another user." At C:\users\user1\Desktop\Read_PCRes_DB.ps1:8 char:1 + $conn.Open('Provider=Microsoft.Jet.OLEDB.4.0; Data Source=$Database;' ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : COMException</code></p> <p>I feel like this a simple reordering of things or an escape character needed around $database or a delay is needed somewhere.</p> <p>It works fine if I hard code the path and value. Below is the PowerShell script:</p> <pre><code>param ([string]$Database = "C:\pcres.mdb", [string]$BranchName = 'BLANK') $adOpenStatic = 3 $adLockOptimistic = 3 $conn=New-Object -com "ADODB.Connection" $rs = New-Object -com "ADODB.Recordset" $conn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='$Database';") $conn.execute('Create Table Location (ID AUTOINCREMENT PRIMARY KEY, Branch TEXT)') $rs.Open("SELECT * FROM Location",$conn,$adOpenStatic,$adLockOptimistic) $rs.AddNew() $rs.Fields.Item("Branch").value = $BranchName $rs.Update() $conn.Close $rs.Close </code></pre> <p>Which is a slightly modified version of this: <a href="http://stackoverflow.com/questions/25277690/create-blank-access-database-using-powershell">Create Blank Access Database Using Powershell</a></p> <p>I am primarily running it like this:</p> <p><code>.\Read_PCRes_DB.ps1 -Database C:\Users\user1\desktop\pcres.mdb -BranchName "Main"</code></p> <p>I am testing this using Powershell 5.0 but it will be used with Powershell 2.0 in production. This is driving me crazy and it shouldn't.</p>
<p>Nevermind... I rebooted and it worked. How ridiculous... plays automated recording from IT Crowd</p>
Android Java - Saving Object Lists to file <p>I'm newbie in programing, and I'm trying to save Object lists to a save file, but nothing seems to work. I get no errors or anything else, but values just won't save (For example : I click button "Money" and earn money, it need to be saved, but when I restart app, "money" again are 0) <strong>In Java my version was working, now i'm converting my code in android and it wont work</strong></p> <p><strong>My SaveFile Class:</strong></p> <pre><code> public void SaveFile(){ try{ File SaveFile = new File("SaveFile.sav"); if(!SaveFile.exists()) { SaveFile.createNewFile(); } FileOutputStream saveFileSub = new FileOutputStream(SaveFile); ObjectOutputStream save = new ObjectOutputStream(saveFileSub); save.writeObject(CarMain.main); save.writeObject(Box.boxes); save.writeObject(CarFrame.frames); save.writeObject(Part.parts); save.writeObject(CarsLv1.cars); save.writeObject(CarsLv2.cars); save.writeObject(CarsLv3.cars); save.writeObject(CarsLv4.cars); save.writeObject(CarsLv5.cars); save.writeObject(CarsLv6.cars); save.writeObject(CarsLv7.cars); save.writeObject(CarsLv8.cars); save.writeObject(CarsLv9.cars); save.writeObject(CarsLv10.cars); save.writeObject(Statistic.statistic); save.close(); } catch(Exception exc){ exc.printStackTrace(); } } </code></pre> <p><strong>My LoadFile class:</strong> </p> <pre><code> public void LoadFile(){ try{ File SaveFile = new File("SaveFile.sav"); FileInputStream SaveFileSub = new FileInputStream(SaveFile); ObjectInputStream load = new ObjectInputStream(SaveFileSub); CarMain.main = (Integer[]) load.readObject(); Box.boxes = (Integer[]) load.readObject(); CarFrame.frames = (Integer[]) load.readObject(); Part.parts = (Integer[]) load.readObject(); CarsLv1.cars = (Integer[]) load.readObject(); CarsLv2.cars = (Integer[]) load.readObject(); CarsLv3.cars = (Integer[]) load.readObject(); CarsLv4.cars = (Integer[]) load.readObject(); CarsLv5.cars = (Integer[]) load.readObject(); CarsLv6.cars = (Integer[]) load.readObject(); CarsLv7.cars = (Integer[]) load.readObject(); CarsLv8.cars = (Integer[]) load.readObject(); CarsLv9.cars = (Integer[]) load.readObject(); CarsLv10.cars = (Integer[]) load.readObject(); Statistic.statistic = (Integer[]) load.readObject(); load.close(); } catch(Exception exc){ exc.printStackTrace(); } } </code></pre> <p><strong>And my Game Loop in "OnCreate" class :</strong></p> <pre><code> LoadFile(); GameLoop= new Thread() { @Override public void run() { try { int waited = 1; while (waited &gt; 0) { sleep(100); waited += 1; SaveFile(); } SaveFile(); } catch (InterruptedException e) { // do nothing } finally { SaveFile(); } } }; GameLoop.start(); </code></pre>
<p>I noticed that you are saving integer arrays, if you dont have a lot data, try to use sharedPreference to save and get data </p> <pre><code>public void saveIntegerArray(Integer[] arr){ if (mSharedPreferences!=null){ mSharedPreferences.edit().putString(yourKey,Arrays.toString(arr)).apply(); } } public Integer[] getIntegerArray(){ if (mSharedPreferences!=null){ String s = mSharedPreferences.getString(yourKey, null); return getIntegers(s); } else return null; } public static int[] getIntegers(String s) { int[] result; ArrayList&lt;Integer&gt; helper = new ArrayList&lt;&gt;(); StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; s.length(); i++) { if (s.charAt(i) == ' ' ^ i == s.length() - 1) { if (i == s.length() - 1) { sb.append(s.charAt(i)); } if (sb.toString().length() &gt; 0) { try { helper.add(Integer.parseInt(sb.toString())); } catch(NumberFormatException nfe) { // Ignore non-integers } sb.setLength(0); continue; } } sb.append(s.charAt(i)); } result = new int[helper.size()]; int i = 0; for (Integer n : helper) { result[i++] = n; } return result; } </code></pre>
regex How to match duplicate attribute names inside a single element (<>) <p>I am trying to use regex to search for elements with duplicate style or class attributes. I can only get matching lines but I'd like more defined matching to the actual element (inside the &lt;>). Anyone have an example? Below is some HTML and a search should only match the top div because it has two style attributes.</p> <pre><code>&lt;div style="width:100%;" style="height:100%;"&gt; &lt;div class="thisclass"&gt;Inner DIV&lt;/div&gt; &lt;span class="thisstyle"&gt;Test Code&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I can get all lines that have duplicate attributes by using <code>&lt;.+(class)=("|').+?\2.+?\1.+&gt;</code> but that gives some false positives if there are multiple brackets/elements on the line.</p>
<p>A comprehensive solution would be this:</p> <pre><code>&lt;[^&gt;]+((class|style)(?:\s*=\s*("|')?(?(3)(?:(?!(?&lt;!\\)\3).)*+\3|[\w{@#():,*!!\[\]}]*+)|(?=[^\w{@#():,*!!\[\]}])))[^&gt;]+?(\2(?:\s*=\s*("|')?(?(5)(?:(?!(?&lt;!\\)\5).)*+\5|[\w{@#():,*!!\[\]}]*+)|(?=[^\w{@#():,*!!\[\]}])))&gt; </code></pre> <p>It will make you sure, that you <strong>correctly capture cases</strong> like:</p> <ol> <li><code>&lt;div style = "font-family:\"Open Sans\"" style= "font-size:2em"&gt;</code></li> <li><code>&lt;div class='one' width=20 class&gt;</code></li> <li><code>&lt;div style="color:white" style=color:black!important&gt;</code></li> </ol> <p>Capturing groups <strong>#1</strong> and <strong>#4</strong> give you the 1st and 2nd occurence of your attributes with its values.</p> <p>Take a look at it visually and interactively <a href="https://regex101.com/r/M0XbwA/4" rel="nofollow">here</a>.</p> <p><a href="https://i.stack.imgur.com/d8aBL.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/d8aBL.jpg" alt="Check regular expression online visually and interactively"></a></p> <p><strong>P.S.:</strong> The following explains the usage of <code>[\w{@#():,*!!\[\]}]</code> in regular expression:</p> <blockquote> <p><code>&lt;div rel={@#():,*!![[]]}&gt;&lt;/div&gt;</code></p> <p>This looks weird, but none of these characters are problematic and no browser has any problem with that. (<a href="https://css-tricks.com/problems-with-unquoted-attributes/" rel="nofollow">source</a>)</p> </blockquote>
basic laravel route with other pages <p>I am making a blog in laravel. I set slug after my base url:</p> <pre><code>Route::get('/{slug}',['as'=&gt;'blog.single','uses'=&gt;'blogController@getSingle']) -&gt;where('slug','[\w\d-\_]+'); </code></pre> <p>the problem is I want to open admin panel like this:</p> <blockquote> <p>www.mydomainname.com/admin</p> </blockquote> <p>but whenever I write admin the above route call and my app understand admin is also a slug, same case with other pages like contact us and about us and any others. I want to open pages like this: </p> <blockquote> <p>www.mydomainname.com/contact<br> www.mydomainname.com/abouts-us</p> </blockquote> <p>and I want to open slugs like this:</p> <blockquote> <p>www.mydomainname.com/my-slug</p> </blockquote>
<p>Try moving the declaration of your admin route above the route looking for a slug:</p> <pre><code>Route::get('/admin', ['as'=&gt;'admin.index', 'uses' =&gt; 'AdminController@index']); Route::get('/{slug}',['as'=&gt;'blog.single','uses'=&gt;'blogController@getSingle']) -&gt;where('slug','[\w\d-\_]+'); </code></pre> <p>In general it would be a good idea to keep your <code>{slug}</code> route at the very end of your routes file to prevent it 'stomping' on your other routes.</p>
How to upgrade my facebook Graph API app from v2.1 to v2.8 directly? <p>Facebook message :Currently you has access to Graph API v2.1 which will reach the end of its 2-year lifetime on 30 October, 2016. To ensure a smooth transition, please migrate all calls to Graph API v2.2 or <strong>higher</strong>.</p>
<p>There is no way to do that, app will upgrade one step at a time but specify the API version explicitly in all calls. If SDK is being used , that should be configurable in one specific place. If not, modification is needed in multiple places.</p>
Is it possible to re-create AWS resources using CloudFormation? <p>Lets say an AWS stack was created using CloudFormation. Now one of those resources was modified <em>outside</em> CloudFormation.</p> <p>1) Is it possible to have CloudFormation specifically create those resources? Based on my understanding, we can't do that because CloudFormation does not identify a difference, and so does not create the modified resources. Is my observation correct?</p> <p>2) Also, what options do I have to revert a stack to its original state, if modified outside CloudFormation?</p>
<p>Unfortunately the answer for both your questions is <strong>NO</strong>.</p> <ol> <li>If you modify the resources in the stack after stack creation status is COMPLETE, there is nothing CF can do since it doesn't keep track of modification to resources</li> <li>You have no option other than deleting the current stack and create a new one</li> </ol>
Radio & Dropdown to same observable - Knockout <p>I have same observable value assigned for radio list "checked" databind and for drop down list "value" databind</p> <pre><code> &lt;select name="controls" data-bind="options: cars(), optionsText:'make', optionsValue:'id', value: $root.selectedId, optionsCaption: 'Select One'"&gt; &lt;/select&gt; &lt;div data-bind="foreach: cars"&gt; &lt;div&gt; &lt;input type="radio" name="controls" data-bind="checked: $root.selectedId, checkedValue: id, value: id"&gt;&lt;div data-bind="text:make"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Since, drop down always holds some value by default 'Select One' or selected value. Not allowing the user to make selection on radio button list. When user clicks on radio buttonn its not getting checked/selection.</p> <p>I can fix by two different observables, but due to some reason I want to stay with same observable </p> <p>jsFiddle - <a href="https://jsfiddle.net/9vm01e3r/2/" rel="nofollow">https://jsfiddle.net/9vm01e3r/2/</a></p>
<p>For the provided fiddle I identify two different problems in your html</p> <ol> <li>Inside a <code>foreach</code> binding context is changed to current item, you need to use <code>$parent</code> to access to <code>selectedCar</code> property.</li> <li>Input/radio was inside a label with a text binding, when this binding is processed is replacing all inner content</li> </ol> <p>Your html should looks something like this </p> <pre><code> &lt;div data-bind="foreach: cars"&gt; &lt;label data-bind="text:name"&gt;&lt;/label&gt; &lt;input type="radio" data-bind="checked: $parent.selectedCar, checkedValue: id, value: id" /&gt; &lt;/div&gt; </code></pre> <p><strong>Edit</strong></p> <p>Ok I know what is happening, when you click an option from radios that item is not a valid item for select tag because isn't in <code>options</code> array, then knockout sets <code>value</code> to undefined causing radios to be deselected.</p> <p>So one alternative will be to use <code>valueAllowUnset: true</code> on select tag (documentation <a href="http://knockoutjs.com/documentation/value-binding.html#using-valueallowunset-with-select-elements" rel="nofollow">here</a>)</p> <p>Please se this updated fiddle <a href="https://jsfiddle.net/tbdo4rxq/" rel="nofollow">https://jsfiddle.net/tbdo4rxq/</a></p>
Reformat JSON file? <p>I have two JSON files.</p> <p>File A:</p> <pre><code> "features": [ { "attributes": { "NAME": "R T CO", "LTYPE": 64, "QUAD15M": "279933", "OBJECTID": 225, "SHAPE.LEN": 828.21510830520401 }, "geometry": { "paths": [ [ [ -99.818614674337155, 27.782542677671653 ], [ -99.816056346719051, 27.782590806976135 ] ] ] } } </code></pre> <p>File B:</p> <pre><code> "features": [ { "geometry": { "type": "MultiLineString", "coordinates": [ [ [ -99.773315512624, 27.808875128096 ], [ -99.771397939251, 27.809512259374 ] ] ] }, "type": "Feature", "properties": { "LTYPE": 64, "SHAPE.LEN": 662.3800009247, "NAME": "1586", "OBJECTID": 204, "QUAD15M": "279933" } }, </code></pre> <p>I would like File B to be reformatted to look like File A. Change "properties" to "attributes", "coordinates" to "paths", and remove both "type": "MultiLineString" and "type": "Feature". What is the best way to do this via python?</p> <p>Is there a way to also reorder the "attributes" key value pairs to look like File A? </p> <p>It's a rather large dataset and I would like to iterate through the entire file.</p>
<p>Manipulating JSON in Python is a good candidate for the <a href="https://en.wikipedia.org/wiki/IPO_model" rel="nofollow">input-process-output model</a> of programming.</p> <p>For input, you convert the external JSON file into a Python data structure, using <a href="https://docs.python.org/2/library/json.html#json.load" rel="nofollow"><code>json.load()</code></a>.</p> <p>For output, you convert the Python data structure into an external JSON file using <a href="https://docs.python.org/2/library/json.html#json.dump" rel="nofollow"><code>json.dump()</code></a>.</p> <p>For the processing or conversion step, do whatever it is that you need to do, using ordinary Python <code>dict</code> and <code>list</code> methods.</p> <p>This program might do what you want:</p> <pre><code>import json with open("b.json") as b: b = json.load(b) for feature in b["features"]: feature["attributes"] = feature["properties"] del feature["properties"] feature["geometry"]["paths"] = feature["geometry"]["coordinates"] del feature["geometry"]["coordinates"] del feature["geometry"]["type"] del feature["type"] with open("new-b.json", "w") as new_b: json.dump(b, new_b, indent=1, separators=(',', ': ')) </code></pre>
Git clone repo in Dockerfile lags <p>I'm trying to clone a private repo hosted by bitbucket to a docker container. My Dockerfile is as follow</p> <pre><code>RUN git clone git@deploy:&lt;blabla&gt;.git /src/&lt;blabla&gt; WORKDIR /src/&lt;blabla&gt; RUN cd /src/&lt;blabla&gt; RUN git pull --all --tags RUN git checkout v1.1.2 RUN pip install . </code></pre> <p>The problem I have: I am said that the tag <code>v1.1.2</code> does not exist. To confirm that, I change the Dockerfile with </p> <pre><code>RUN git clone git@deploy:&lt;blabla&gt;.git /src/&lt;blabla&gt; WORKDIR /src/&lt;blabla&gt; RUN cd /src/&lt;blabla&gt; RUN git pull --all --tags RUN git branch RUN git tag RUN git checkout v1.1.2 RUN pip install . </code></pre> <p>where I can see that the last created branch and the last tag are now cloned indeed. The workaround I found is to make a double pull </p> <pre><code>RUN git clone git@deploy:&lt;blabla&gt;.git /src/&lt;blabla&gt; WORKDIR /src/&lt;blabla&gt; RUN cd /src/&lt;blabla&gt; RUN git pull --all --tags RUN git pull --all --tags RUN git checkout v1.1.2 RUN pip install . </code></pre> <p>and now everything works great.</p>
<p>Try this:</p> <pre><code>RUN git clone -b 'v1.1.2' --single-branch --depth 1 git@deploy:&lt;blabla&gt;.git /src/&lt;blabla&gt; \ &amp;&amp; cd /src/&lt;blabla&gt; \ &amp;&amp; pip install . WORKDIR /src/&lt;blabla&gt; </code></pre> <p>Git clone can directly fetch the tag, and adding <code>--single-branch</code> and <code>--depth</code> avoid to clone the whole repository history to the container.</p> <p>It's a bit more compact and avoids extra layers. You can still break it into multiple lines of you want.</p>
Using Identity in SQL Server without race condition <p>So let's say you have a table of Patients with an IDENTITY(1,1) for the primary key. By using @@Identity, how do we avoid a race condition where two people may save a new patient at the same time? Obviously, duplicate ID's in the Patients table would not be created, but what if the application needed the ID for one of the inserted patients to update a record in another table elsewhere? How do we know that @@Identity won't get the ID of the other record if both are inserted at the same time?</p> <p>Or is there a best practice for avoiding this?</p> <p>JamesNT</p>
<p>@@IDENTITY will not cause a race condition but it is NOT best practice either. You should instead be using SCOPE_IDENTITY.</p> <p><a href="http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/" rel="nofollow">http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/</a></p>