title
stringlengths
15
150
body
stringlengths
38
32.9k
label
int64
0
3
TypeError: Cannot read property 'split' of undefined in Nodejs
<p>i get the following error, using the jwt-simple lib:</p> <pre><code>TypeError: Cannot read property 'split' of undefined at module.exports (C:\my_application\services\mylist.js:5:40) at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5) at next (C:\my_application\node_modules\express\lib\router\route.js:131:13) at Route.dispatch (C:\my_application\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5) at C:\my_application\node_modules\express\lib\router\index.js:277:22 at Function.process_params (C:\my_application\node_modules\express\lib\router\index.js:330:12) at next (C:\my_application\node_modules\express\lib\router\index.js:271:10) at C:\my_application\api.js:39:3 at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5) at trim_prefix (C:\my_application\node_modules\express\lib\router\index.js:312:13) at C:\my_application\node_modules\express\lib\router\index.js:280:7 at Function.process_params (C:\my_application\node_modules\express\lib\router\index.js:330:12) at next (C:\my_application\node_modules\express\lib\router\index.js:271:10) at logger (C:\my_application\node_modules\morgan\index.js:144:5) at Layer.handle [as handle_request] (C:\my_application\node_modules\express\lib\router\layer.js:95:5) </code></pre> <p>and here is mylist.js file:</p> <pre><code>var jwt = require('jwt-simple'); module.exports = function (req, res) { var token = req.headers.authorization.split(' ')[1]; var payload = jwt.decode(token, "shhh.."); if(!payload.sub) { res.status(401).send({ message: 'Authentication failed' }); } if(!req.headers.authorization){ return res.status(401).send({ message: 'You are not authorized' }); } res.json(mylist); }; var mylist = [ 'Proj 1', 'Proj 2', 'Proj 3', 'Proj 4' ]; </code></pre> <p>i am trying to see if the user is authorized to access the mylist resource on frontend. <br> does anyone have any idea?</p>
0
selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with
<p>Currently working to use Python to login with Twitter.</p> <p>Twitter's login page is <a href="https://twitter.com/login" rel="nofollow">here</a>. The source code where the Username and Password input fields are:</p> <pre><code>&lt;div class="LoginForm-input LoginForm-username"&gt; &lt;input type="text" class="text-input email-input js-signin-email" name="session[username_or_email]" autocomplete="username" placeholder="Phone, email or username" /&gt; &lt;/div&gt; &lt;div class="LoginForm-input LoginForm-password"&gt; &lt;input type="password" class="text-input" name="session[password]" placeholder="Password" autocomplete="current-password"&gt; &lt;/div&gt; </code></pre> <p>So when I write my code in Python utilizing the Selenium module:</p> <pre><code># -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("https://twitter.com/login") elem = driver.find_element_by_name("session[username_or_email]") elem.clear() elem.send_keys(username) elem = driver.find_element_by_name("session[password]") elem.clear() elem.send_keys(password) elem.send_keys(Keys.RETURN) sleep(delay) </code></pre> <p>The error that is returned:</p> <blockquote> <p>selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with</p> </blockquote> <p>Any help? Thanks! I have read of the responses of other similar questions, but have not helped much.</p> <p><strong>Edit:</strong></p> <p>Full error message:</p> <pre><code>Traceback (most recent call last): File "main.py", line 154, in &lt;module&gt; main() File "main.py", line 143, in main twitterBruteforce(username, wordlist, delay) File "src/twitterLib.py", line 27, in twitterBruteforce elem.clear() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 88, in clear self._execute(Command.CLEAR_ELEMENT) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webelement.py", line 457, in _execute return self._parent.execute(command, params) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 233, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Stacktrace: at fxdriver.preconditions.visible (file:///tmp/tmpurkUhr/extensions/[email protected]/components/command-processor.js:10092) at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpurkUhr/extensions/[email protected]/components/command-processor.js:12644) at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpurkUhr/extensions/[email protected]/components/command-processor.js:12661) at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpurkUhr/extensions/[email protected]/components/command-processor.js:12666) at DelayedCommand.prototype.execute/&lt; (file:///tmp/tmpurkUhr/extensions/[email protected]/components/command-processor.js:12608) </code></pre>
0
android 6.0 javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
<p>this code works well before android 6.0, <strong>but get an error on 6.0 if encrypted file size less than about 1k bytes.</strong></p> <pre><code>public static byte[] decode(byte[] decrypteSrcBuffer) throws Exception { Key deskey = null; DESedeKeySpec spec = new DESedeKeySpec(mKeyBytes); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede"); deskey = keyfactory.generateSecret(spec); Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding"); IvParameterSpec ips = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, deskey, ips); byte[] decryptData = cipher.doFinal(decrypteSrcBuffer); return decryptData; } </code></pre> <p>Error info:</p> <pre><code>javax.crypto.BadPaddingException: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT at com.android.org.conscrypt.NativeCrypto.EVP_CipherFinal_ex(Native Method) at com.android.org.conscrypt.OpenSSLCipher$EVP_CIPHER.doFinalInternal(OpenSSLCipher.java:568) at com.android.org.conscrypt.OpenSSLCipher.engineDoFinal(OpenSSLCipher.java:350) at javax.crypto.Cipher.doFinal(Cipher.java:2056) </code></pre>
0
C++ boolean array initialization
<p>I want to initilize all elements from my 2-dimensional boolean array to false. </p> <pre><code>size_t n, m; cin &gt;&gt; n &gt;&gt; m; bool arr[n][m] = {false}; for(size_t i = 0; i &lt; n; i++){ for(size_t j = 0; j &lt; m; j++){ cout &lt;&lt; arr[i][j] &lt;&lt; " "; } cout &lt;&lt; endl; } </code></pre> <p>But i'm getting very confused with the output. For example, if n = 5 and m = 5, i have the following :</p> <pre><code>0 27 64 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>So, what's wrong with the code?</p>
0
Unable to install dplyr in R 3.3.1
<p>I can't seem to install dplyr or perhaps I really can't install it? Here's what I have</p> <pre><code>install.packages("dplyr") package ‘dplyr’ successfully unpacked and MD5 sums checked Warning in install.packages : package ‘C:/Users/808797/AppData/Local/Temp/Rtmpkl7AKB/downloaded_packages’ is not available (for R version 3.3.1) </code></pre> <p>also tried</p> <pre><code>&gt;install.packages("https://cran.r-project.org/bin/windows/contrib/3.3/dplyr_0.5.0.zip",repos=null,type=source) </code></pre> <p>also tried</p> <pre><code>&gt; library("downloader") &gt; download("https://cran.r-project.org/bin/windows/contrib/3.3/dplyr_0.5.0.zip","dplyr") &gt; install.packages("dplyr") Warning in install.packages : package ‘dplyr’ is not available (for R version 3.3.1) </code></pre> <p>always the same <code>is not available (for R version 3.3.1)</code></p> <p>am i out of luck?</p>
0
How to universally enable scrolling on website that disabled scrolling?
<p>How to quickly and universally re-enable scrolling on a website that has disabled scrolling with JavaScript? (Given that there is actually content to scroll through.)</p> <p>The scrolling works when JavaScript is disabled and, with JavaScript enabled, <code>window.scrollBy(0, 100)</code> works fine but not when ordinarily bound to keys or mouse scroll.</p>
0
Prevent user from refreshing the page
<p>I want to prevent the user from refreshing the page, How to do this? I have been using <code>e.preventDefault</code> method but it`s not running properly.</p>
0
Split a string by a newline in C#
<p>I have a string like this : </p> <blockquote> <p>SITE IÇINDE OLMASI\nLÜKS INSAA EDILMIS OLMASI\nSITE IÇINDE YÜZME HAVUZU, VB. SOSYAL YASAM ALANLARININ OLMASI.\nPROJESİNE UYGUN YAPILMIŞ OLMASI</p> </blockquote> <p>I'm trying to split and save this string like this : </p> <pre><code>array2 = mystring.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var str in sarray2) { if (str != null &amp;&amp; str != "") { _is.RelatedLook.InternalPositive += str; } } </code></pre> <p>I also tried </p> <pre><code>Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); </code></pre> <p>This obviously doesn't split my string. How can I split my string in a correct way? Thanks</p>
0
Locked object found on oracle.jdbc.driver.T4CConnection
<p>I am using JMC to perform application profiling and I did not see any locked/thread contention as shown in the screenshot below.</p> <p><a href="https://i.stack.imgur.com/kMIka.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kMIka.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/i8L93.png" rel="noreferrer"><img src="https://i.stack.imgur.com/i8L93.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/PWNEo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PWNEo.png" alt="enter image description here"></a> I ran the SQL below (every few secs) also did not return any result.</p> <pre><code>select (select username from v$session where sid=a.sid) blocker, a.sid, ' is blocking ', (select username from v$session where sid=b.sid) blockee, b.sid from v$lock a, v$lock b where a.block = 1 and b.request &gt; 0 and a.id1 = b.id1 and a.id2 = b.id2; </code></pre> <p>What could be the caused of a lock database connection? Could it be database record/table locks?</p> <p>Below is the thread dump which I have extracted during the execution of my program when it seems to be running forever.</p> <pre><code> java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) at java.net.SocketInputStream.read(SocketInputStream.java:170) at java.net.SocketInputStream.read(SocketInputStream.java:141) at oracle.net.ns.Packet.receive(Packet.java:283) at oracle.net.ns.DataPacket.receive(DataPacket.java:103) at oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:230) at oracle.net.ns.NetInputStream.read(NetInputStream.java:175) at oracle.net.ns.NetInputStream.read(NetInputStream.java:100) at oracle.net.ns.NetInputStream.read(NetInputStream.java:85) at oracle.jdbc.driver.T4CSocketInputStreamWrapper.readNextPacket(T4CSocketInputStreamWrapper.java:123) at oracle.jdbc.driver.T4CSocketInputStreamWrapper.read(T4CSocketInputStreamWrapper.java:79) at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1122) at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1099) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:288) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207) at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:863) at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1153) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1275) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576) at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3620) - locked &lt;0x00000007af3423c0&gt; (a oracle.jdbc.driver.T4CConnection) </code></pre>
0
Create an object from an array of keys and an array of values
<p>I have two arrays: <code>newParamArr</code> and <code>paramVal</code>.</p> <p>Example values in the <code>newParamArr</code> array: <code>[ &quot;Name&quot;, &quot;Age&quot;, &quot;Email&quot; ]</code>.</p> <p>Example values in the <code>paramVal</code> array: <code>[ &quot;Jon&quot;, 15, &quot;[email protected]&quot; ]</code>.</p> <p>I need to create a JavaScript object that places all of the items in the array in the same object. For example <code>{ [newParamArr[0]]: paramVal[0], [newParamArr[1]]: paramVal[1], ... }</code>.</p> <p>In this case, the result should be <code>{ Name: &quot;Jon&quot;, &quot;Age&quot;: 15, &quot;Email&quot;: &quot;[email protected]&quot; }</code>.</p> <p>The lengths of the two arrays are always the same, but the length of arrays can increase or decrease. That means <code>newParamArr.length === paramVal.length</code> will always hold.</p> <p>None of the below posts could help to answer my question:</p> <p><a href="https://stackoverflow.com/questions/11827456/javascript-recursion-for-creating-a-json-object">Javascript Recursion for creating a JSON object</a></p> <p><a href="https://stackoverflow.com/questions/15690706/recursively-looping-through-an-object-to-build-a-property-list">Recursively looping through an object to build a property list</a></p>
0
Disable/Enable powershell with reg key
<p>I want to disable/enable powershell with reg key (if it is possible) to execute in cmd</p> <p>For example. If I want to disable/enable WSH, simply i run in cmd with privileged:</p> <pre><code>:: Disable WSH reg add "HKLM\Software\Microsoft\Windows Script Host\Settings" /v Enabled /t REG_DWORD /d 0 /f reg add "HKCU\Software\Microsoft\Windows Script Host\Settings" /v Enabled /t REG_DWORD /d 0 /f :: Restore WSH reg add "HKLM\Software\Microsoft\Windows Script Host\Settings" /v Enabled /t REG_DWORD /d 1 /f reg add "HKCU\Software\Microsoft\Windows Script Host\Settings" /v Enabled /t REG_DWORD /d 1 /f </code></pre> <p>How do I do this to disable/enable Powershell? (in Windows XP/7/8/8.1/10 x86 x64)</p> <p>Thanks</p>
0
Swift 3, URLSession dataTask completionHandler not called
<p>I am writing a library, So not using UIKit, Even in my iOS app same code works, but when i execute in command line in doesn't . In PlayGround also it seems working.</p> <p>For some reason callback is not getting triggered, so print statements are not executing.</p> <pre><code>internal class func post(request: URLRequest, responseCallback: @escaping (Bool, AnyObject?) -&gt; ()) { execTask(request: request, taskCallback: { (status, resp) -&gt; Void in responseCallback(status, resp) }) } internal class func clientURLRequest(url: URL, path: String, method: RequestMethod.RawValue, params: Dictionary&lt;String, Any&gt;? = nil) -&gt; URLRequest { var request = URLRequest(url: url) request.httpMethod = method do { let jsonData = try JSONSerialization.data(withJSONObject: (params! as [String : Any]), options: .prettyPrinted) request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.httpBody = jsonData } catch let error as NSError { print(error) } return request } private class func execTask(request: URLRequest, taskCallback: @escaping (Bool, AnyObject?) -&gt; ()) { let session = URLSession(configuration: URLSessionConfiguration.default) print("THIS LINE IS PRINTED") let task = session.dataTask(with: request, completionHandler: {(data, response, error) -&gt; Void in if let data = data { print("THIS ONE IS NOT PRINTED") let json = try? JSONSerialization.jsonObject(with: data, options: []) if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode { taskCallback(true, json as AnyObject?) } else { taskCallback(false, json as AnyObject?) } } }) task.resume() } </code></pre> <p>Edits -: I am writing a library, So not using UIKit, Even in my iOS app same code works, but when i execute in command line in doesn't . In PlayGround also it seems working.</p>
0
How to properly remove a character from a char array (with or without converting to a string)?
<p><em>Sorry in advance for any possible duplicate question. I have been Googling a solution for my compiler error, for a week now, tried different workarounds from various answers around here, yet I keep getting some errors.</em></p> <p>I am currently learning C++, trying to build a program that does basic stuff like vowel/consonant count, letter removal etc. Everything works fine until I get to the <em>custom letter</em> removal part. Basically, it's near impossible to do that using character functions (according to my knowledge), while converting to a string seems to spawn other kinds of errors.</p> <p>Here is the code fragment where I keep getting errors:</p> <pre><code>if (strcmp (service, key4) ==0) { string str(s); cout&lt;&lt;endl&lt;&lt;"Please insert the letter you would like removed from your "&lt;&lt;phrasal&lt;&lt;":"&lt;&lt;endl; cin&gt;&gt;letterToRemove; s.erase(remove(s.begin(), s.end(),letterToRemove), s.end()); cout&lt;&lt;endl&lt;&lt;s&lt;&lt; "\n"&lt;&lt;endl; } </code></pre> <p>and here are initialized variable I used:</p> <pre><code>int main() { char s[1000], phrasal[10], service[50], key1[] = "1", key2[] = "2", key3[] = "3", key4[] = "4", key5[] = "5", key6[] = "6", key0[] = "0", *p, letterToRemove; int vowel=0, vowel2=0, consonant=0, consonant2=0, b, i, j, k, phrase=0, minusOne, letter, idxToDel; void pop_back(); char *s_bin; </code></pre> <p>As you can see, the original <strong>'s'</strong> is a char array. In the first code sample I have tried converting it into a string array (<em>string str(s)</em>), but that results in the following compiling errors:</p> <ul> <li>error: request for member 'erase' in 's', which is of non-class type 'char[1000]'</li> <li>error: request for member 'begin' in 's', which is of non-class type 'char[1000]'</li> <li>error: request for member 'end' in 's', which is of non-class type 'char[1000]'</li> <li>error: request for member 'end' in 's', which is of non-class type 'char[1000]'</li> </ul> <p>The other workaround I've tried was this:</p> <pre><code>if(strcmp(service, key4)==0) {std::string s(s); cout&lt;&lt;endl&lt;&lt;"Please insert the letter you would like removed from your "&lt;&lt;phrasal&lt;&lt;":"&lt;&lt;endl; cin&gt;&gt;letterToRemove; s.erase(remove(s.begin(), s.end(),letterToRemove), s.end()); cout&lt;&lt;endl&lt;&lt;s&lt;&lt; "\n"&lt;&lt;endl; } </code></pre> <p>Now here's the funny part, I get no errors whatsoever for this one, but the debug crashes as soon as I select the <em>custom letter removal</em> feature. Here's what it says:</p> <p><a href="http://i.stack.imgur.com/QzILv.png" rel="nofollow">"terminate called after throwing an instance of 'std::length_error' what(): basic_string::_S_create          This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information."</a></p> <p>Any help would be much appreciated, stuck at this one for a week now!</p> <p><em>P.S. Is it okay if I or a moderator deletes this question after it's been answered? I'm quite sure I'm not the first one who asks this, but, as before-hand mentioned, I keep getting these errors, even after following answers from similar questions.</em></p>
0
how to validate radio button without javascript?
<p>I have used radio button for gender as follow:-</p> <pre><code>&lt;td&gt;&lt;input type="radio" name="gender" value="male" checked required="required"&gt; Male&lt;br&gt; &lt;input type="radio" name="gender" value="female"&gt; Female&lt;br&gt; &lt;input type="radio" name="gender" value="other"&gt; Other&lt;/td&gt; </code></pre> <p>but this "required" validation is not working how to put validation on it without using JavaScript. </p>
0
Need only 2 digits after decimal point
<p>I want my function to return value with <em>only 2 decimal places</em>. I have tried following code :</p> <pre><code>private static double CalculateSlabTax(int nSlabStartTaxable, int nSlabEndTaxable, float fSlabRate) { double dblSlabResult = 0; try { dblSlabResult = (nSlabStartTaxable - nSlabEndTaxable) * fSlabRate; dblSlabResult = Math.Round(dblSlabResult , 2); return dblSlabResult; } catch (Exception) { return -1; } } </code></pre> <p>Expected output is : <code>dblSlabResult = ####.##</code> - <em>two digits</em> (eg. <code>1002.05</code>)</p> <p>Getting output as : eg. <code>dblSlabResult = 1002.1</code></p>
0
Microsoft SQL Server , Error : 87
<p>I am really tired, it's been 3 days that I can't open my SQL Server Management Studio. I got connection string error with number 87. Below screenshot show my problem:</p> <p><img src="https://i.stack.imgur.com/nGSzV.png" alt="Picture number 1"></p> <p><img src="https://i.stack.imgur.com/Mo4MJ.png" alt="Picture number 2"></p> <p>And I use <code>localhost\MSSQLSERVER</code> with error 87 and <code>Arash-PC</code> (my machine name) with error number 2.</p> <p>And I tried <code>sqlcmd -U sa -S Arash-PC</code> too</p>
0
Javascript Set vs. Array performance
<p>It may be because Sets are relatively new to Javascript but I haven't been able to find an article, on StackO or anywhere else, that talks about the performance difference between the two in Javascript. So, what is the difference, in terms of performance, between the two? Specifically, when it comes to removing, adding and iterating.</p>
0
Python: delete all variables except one for loops without contaminations
<pre><code>%reset %reset -f </code></pre> <p>and </p> <pre><code>%reset_selective a %reset_selective -f a </code></pre> <p>are usefull Python alternative to the Matlab command "clear all", in which "-f" means "force without asking for confirmation" and "_selective" could be used in conjunction with </p> <pre><code>who_ls </code></pre> <p>to selectively delete variables in workspace as clearly shown here <a href="https://ipython.org/ipython-doc/3/interactive/magics.html" rel="nofollow">https://ipython.org/ipython-doc/3/interactive/magics.html</a> .</p> <p>Now I am managing loops in which I am going to define a large number of variables, for example</p> <pre><code>for j in range(1000): a = crazy_function1() b = crazy_function2() ... m = crazy_function18() n = crazy_function19() ... z = crazy_functionN() </code></pre> <p>and at the end of each cycle I want to delete ALL variables EXCEPT the standard variables of the Python workspace and some of the variables I introduced (in this example only m and n). This would avoid contaminations and memory burdening hence it will make the code more efficient and safe.</p> <p>I saw that "who_ls" result looks like a list, hence I thought at a loop that delete all variables that are not equal to m or n</p> <pre><code>for j in range(1000): a = crazy_function1() b = crazy_function2() ... m = crazy_function18() n = crazy_function19() ... z = crazy_functionN() if who_ls[j] != m or who_ls[j] != n: %reset_selective -f who_ls[j] </code></pre> <p>but it doesn't work as who_ls looks as a list but it doesn't work as a list. How would you modify the last lines of code? Is there anything like</p> <pre><code> %reset_selective -f, except variables(m, n) </code></pre> <p>?</p>
0
ImportError: No module named impyla
<p>I have installed impyla and it's dependencies following <a href="https://github.com/cloudera/impyla" rel="nofollow noreferrer">this</a> guide. The installation seems to be successful as now I can see the folder <strong>&quot;impyla-0.13.8-py2.7.egg&quot;</strong> in the Anaconda folder (64-bit Anaconda 4.1.1 version).</p> <p>But when I import impyla in python, I get the following error:</p> <pre><code>&gt;&gt;&gt; import impyla Traceback (most recent call last): File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt; ImportError: No module named impyla </code></pre> <p><strong>I have installed 64-bit Python 2.7.12</strong></p> <p><strong>Can any body please explain me why I am facing this error?</strong> I am new on Python and have been spending allot of time on different blogs, but I don't see much information present there yet. Thanks in advance for your time.</p>
0
How to detect the change on input when it changed dynamically
<p>How to detect the changes in input values when it is dynamically changed. as the change on txt2 clear the value in txt1 . I need to detect that it has cleared or changed.</p> <p>Onchange does not do that. </p> <pre><code>&lt;input id="txt1" type="text" onchange="SetDefault();" onpaste="this.onchange();" oninput="this.onchange();"&gt; &lt;br&gt; &lt;input id="txt2" type="text" onchange="SetDefaultSecond();" onkeyup="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"&gt; &lt;script&gt; function SetDefault(){ alert("Change1"); } function SetDefaultSecond(){ $("#txt1").val(''); alert("Change2"); } &lt;/script&gt; </code></pre>
0
ASCII text executable, with CRLF line terminators
<p>Good evening,</p> <p>I'm currently enrolled in an introduction-course to python and have come across an issue that I haven't been able to solve. I'm sure it's a simple error somewhere in my code, but I haven't been able to find any questions on SO that solved my issue.</p> <p><em>Strangely enough it compiles and runs fine when executing it from cygwin...</em></p> <p><strong>I'm getting this error while validating through 3rd party tests (that I don't have access to):</strong></p> <blockquote> <p>Python script, ASCII text executable, with CRLF line terminators</p> </blockquote> <p>This is my code: </p> <pre><code> height = float(input("What is the plane's elevation in metres? \r\n")) height = format(height * 3.28084, '.2f') speed = float(input("What is the plane's speed in km/h? \r\n")) speed = format(speed * 0.62137, '.2f') temperature = float(input("Finally, what is the temperature (in celsius) outside? \r\n")) temperature = format(temperature * (9/5) + 32, '.2f') print("""\n########### OUTPUT ###########\n\nThe elevation is {feet} above the sea level, \n you are going {miles} miles/h, \n finally the temperature outside is {temp} degrees fahrenheit \n ########### OUTPUT ###########""".format(feet=height, miles=speed, temp=temperature)) </code></pre> <p>And this is a cgi based on it (both are throwing the same error):</p> <pre><code> #!/usr/bin/env python3 # -*- coding: utf-8 -*- # To write pagecontent to sys.stdout as bytes instead of string import sys import codecs #Enable debugging of cgi-.scripts import cgitb cgitb.enable() # Send the HTTP header #print("Content-Type: text/plain;charset=utf-8") print("Content-Type: text/html;charset=utf-8") print("") height = format(1100 * 3.28084, '.2f') speed = format(1000 * 0.62137, '.2f') temperature = format(-50 * (9/5) + 32, '.2f') toPrint = """\n########### OUTPUT ###########\n\nThe elevation is {feet} above the sea level, \n you are going {miles} miles/h, \n finally the temperature outside is {temp} degrees fahrenheit \n ########### OUTPUT ###########""" toPrint.format(feet=height, miles=speed, temp=temperature) # Here comes the content of the webpage content = """&lt;!doctype html&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Min redovisnings-sida&lt;/title&gt; &lt;pre&gt; &lt;h1&gt;Min Redovisnings-sida &lt;/h1&gt; &lt;/pre&gt; &lt;body&gt; {printer} &lt;/body&gt; """ # Write page content sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) sys.stdout.write(content.format(printer=toPrint)) </code></pre>
0
dplyr object not found error
<p>I am not quite sure why this piece of code isn't working. </p> <p>Here's how my data looks like:</p> <pre><code>head(test) Fiscal.Year Fiscal.Quarter Seller Product.Revenue Product.Quantity Product.Family Sales.Level.1 Group Fiscal.Week 1 2015 2015Q3 ABCD1234 4000 4 Paper cup Americas Paper Division 32 2 2014 2014Q1 DDH1234 300 5 Paper tissue Asia Pacific Paper Division 33 3 2015 2015Q1 PNS1234 298 6 Spoons EMEA Cutlery 34 4 2016 2016Q4 CCC1234 289 7 Knives Africa Cutlery 33 </code></pre> <p>Now, my objective is to summarize revenue by year.</p> <p>Here's the dplyr code I wrote:</p> <pre><code>test %&gt;% group_by(Fiscal.Year) %&gt;% select(Seller,Product.Family,Fiscal.Year) %&gt;% summarise(Rev1 = sum(Product.Revenue)) %&gt;% arrange(Fiscal.Year) </code></pre> <p>This doesnt work. I get the error:</p> <pre><code>Error: object 'Product.Revenue' not found </code></pre> <p>However, when I get rid of select statement, it works but then I don't get to see the output with Sellers, and Product family.</p> <pre><code>test %&gt;% group_by(Fiscal.Year) %&gt;% # select(Seller,Product.Family,Fiscal.Year) %&gt;% summarise(Rev1 = sum(Product.Revenue)) %&gt;% arrange(Fiscal.Year) </code></pre> <p>The output is : </p> <pre><code># A tibble: 3 x 2 Fiscal.Year Rev1 &lt;dbl&gt; &lt;dbl&gt; 1 2014 300 2 2015 4298 3 2016 289 </code></pre> <p>This works well. </p> <p>Any idea what's going on? It's been about 3 weeks since I started programming in R. So, I'd appreciate your thoughts. I am following this guide: <a href="https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html" rel="nofollow noreferrer">https://cran.rstudio.com/web/packages/dplyr/vignettes/introduction.html</a> </p> <p>Also, I looked at similar threads on SO, but I believe they were relating to issues because of "+" sign:<a href="https://stackoverflow.com/questions/38524956/error-in-dplyr-group-by-function-object-not-found">Error in dplyr group_by function, object not found</a></p> <p>I am looking for the following output:</p> <pre><code> Fiscal.Year Rev1 Product Family Seller &lt;dbl&gt; &lt;dbl&gt; ... ... 1 2014 ... 2 2015 ... 3 2016 ... </code></pre> <p>Many thanks</p>
0
How to get text of next td in jQuery?
<p>I need Test 2 text when I clicked on "Click". I have tried like this ...</p> <pre><code>$("#clicked").click(function(){ alert( $('this').closest('td').next('td').next('td').text()); }) </code></pre> <p>But In alert there is empty. How I can get Test 2 ?</p> <pre><code>&lt;tr&gt; &lt;td&gt; &lt;/td&gt; &lt;td&gt;&lt;a id = 'clicked'&gt;Click&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Test 1&lt;/td&gt; &lt;td&gt;&lt;a id = 'clicked2' /&gt; Test 2&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <hr> <p><em>From comment below:</em></p> <p><code>this</code> means <code>$('#clicked')</code>. That means when I clicked on the <code>Click</code> link. </p>
0
When should I use IntStream.range in Java?
<p>I would like to know when I can use <code>IntStream.range</code> effectively. I have three reasons why I am not sure how useful <code>IntStream.range</code> is.</p> <p>(Please think of start and end as integers.)</p> <ol> <li><p>If I want an array, <code>[start, start+1, ..., end-2, end-1]</code>, the code below is much faster.</p> <pre><code>int[] arr = new int[end - start]; int index = 0; for(int i = start; i &lt; end; i++) arr[index++] = i; </code></pre> <p>This is probably because <code>toArray()</code> in <code>IntStream.range(start, end).toArray()</code> is very slow.</p></li> <li><p>I use MersenneTwister to shuffle arrays. (I downloaded MersenneTwister class online.) I do not think there is a way to shuffle <code>IntStream</code> using MersenneTwister.</p></li> <li><p>I do not think just getting <code>int</code> numbers from <code>start</code> to <code>end-1</code> is useful. I can use <code>for(int i = start; i &lt; end; i++)</code>, which seems easier and not slow.</p></li> </ol> <p>Could you tell me when I should choose <code>IntStream.range</code>?</p>
0
overridePendingTransition in a fragment
<p>My main activity uses tablayout with a viewpager and FragmentStatePagerAdapter. I want to open a new activity with a custom animation from one of my fragments and close it again with animation. When I open it, the only thing I see is a black screen. This is how I do it:</p> <pre><code>public class SearchActivity extends Fragment{ ... Intent myIntent = new Intent(getContext(), DetailsActivity.class); startActivityForResult(myIntent, ACTIVITY_RESULT); getActivity().overridePendingTransition(R.anim.animation_enter, R.anim.animation_leave); ... } public class DetailsActivity extends AppCompatActivity{ ... Intent returnIntent = new Intent(); returnIntent.putExtra("result", updatesPerformed); setResult(Activity.RESULT_OK, returnIntent); finish(); overridePendingTransition(R.anim.animation_leave, R.anim.animation_enter); ... } </code></pre> <p>I tried to move the method in different places but the animation still doesn't work and I see only black screen. If I pause and resume to the same activity I see it.</p>
0
How to stop writing a blank line at the end of csv file - pandas
<p>When saving the data to csv, <code>data.to_csv('csv_data', sep=',', encoding='utf-8', header= False, index = False)</code>, it creates a blank line at the end of csv file. </p> <p>How do you avoid that? </p> <p>It's got to do with the <code>line_terminator</code> and it's default value is <code>n</code>, for new line.</p> <p>Is there a way to specify the <code>line_terminator</code> to avoid creating a blank line at the end, or do i need to read the csv file, remove the blank line and save it?</p> <p>Not familiar with pandas. Your help will be appreciated, thanks in advance!</p>
0
Gettings javax.mail.MessagingException: [EOF] on our live server, but everything works as expected on our dev server
<p>Running this Java service on my laptop (Windows 10) or on our development server (CentOS) everything works as expected. But when I run it on our live server (CentOS) I get the following error:</p> <pre><code>09/Sep/2016 08:31:07,005 [ERROR] [pool-2-thread-2] - EmailSender: A Messaging exception occurred in EmailSender javax.mail.MessagingException: [EOF] at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1363) ~[jar:rsrc:mail-1.4.jar!/:?] at com.sun.mail.smtp.SMTPTransport.helo(SMTPTransport.java:838) ~[jar:rsrc:mail-1.4.jar!/:?] at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:375) ~[jar:rsrc:mail-1.4.jar!/:?] at javax.mail.Service.connect(Service.java:275) ~[jar:rsrc:mail-1.4.jar!/:?] at javax.mail.Service.connect(Service.java:156) ~[jar:rsrc:mail-1.4.jar!/:?] at com.awesomecompany.messaging.server.EmailSender.sendEmail(EmailSender.java:99) [rsrc:./:?] at com.awesomecompany.messaging.server.MonitorDevicesRunnable.run(MonitorDevicesRunnable.java:82) [rsrc:./:?] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [?:1.7.0_75] at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304) [?:1.7.0_75] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) [?:1.7.0_75] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.7.0_75] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [?:1.7.0_75] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [?:1.7.0_75] at java.lang.Thread.run(Thread.java:745) [?:1.7.0_75] </code></pre> <p>My email code: </p> <pre><code>public void sendEmail(User user) { to[0] = user.getEmail(); Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", password); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.debug", "true"); props.put("mail.store.protocol", "imap"); subject = user.getEmailBuilder().getEmailSubject(); try { Session session = Session.getDefaultInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); MimeMessage message = new MimeMessage(session) { protected void updateMessageID() throws MessagingException { if (getHeader("Message-ID") == null) super.updateMessageID(); } }; message.setFrom(new InternetAddress(from)); InternetAddress[] to_addresses = new InternetAddress[to.length]; for (int i = 0; i &lt; to.length; i++) { to_addresses[i] = new InternetAddress(to[i]); } message.addRecipients(javax.mail.Message.RecipientType.TO, to_addresses); String messageHtml = user.getEmailMessage(); message.setSubject(subject); message.setContent(messageHtml, "text/html;charset=UTF-8;"); message.saveChanges(); user.setEmailMessageId(message.getMessageID()); log.info("Email message ID: " + message.getMessageID()); Transport transport = session.getTransport("smtp"); transport.connect(host, from, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); user.setEmailStatus(DistinctNotification.STATUS_SENT); } catch (AddressException e) { log.error("An AddressException occurred in EmailSender", e); user.setEmailStatus(DistinctNotification.STATUS_READY); } catch (MessagingException e) { log.error("A Messaging exception occurred in EmailSender", e); user.setEmailStatus(DistinctNotification.STATUS_READY); } } </code></pre> <p>The error occurs at this line:</p> <pre><code>transport.connect(host, from, password); </code></pre> <p><strong>EDIT:</strong> </p> <p>I reverted to an earlier build that I know for a fact worked, maybe a few months ago. It no longer works, I get the same error.<br> My other colleagues who have access to the server say they haven't made any changes to it. </p> <p>I have absolutely no idea where to go with this. I have no problem contacting googles servers using telnet. I'm going to do more checking on various ports just to be sure, but I don't thing that's the issue. <strong>EDIT 2:</strong> </p> <p>Here's the issue: <code>501-5.5.4 Empty HELO/EHLO argument not allowed, closing connection.</code><br> But why would this be happening only on the one server?</p> <p>Additional logs from the console: </p> <pre><code>DEBUG SMTP: connected to host "smtp.gmail.com", port: 587 EHLO 501-5.5.4 Empty HELO/EHLO argument not allowed, closing connection. 501 5.5.4 https://support.google.com/mail/?p=helo l10sm686448lfd.19 - gsmtp HELO DEBUG SMTP: EOF: [EOF] 09:07:00.277 [pool-2-thread-1] - A Messaging exception occurred in EmailSender javax.mail.MessagingException: [EOF] at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1363) ~[jar:rsrc:mail-1.4.jar!/:?] at com.sun.mail.smtp.SMTPTransport.helo(SMTPTransport.java:838) ~[jar:rsrc:mail-1.4.jar!/:?] at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:375) ~[jar:rsrc:mail-1.4.jar!/:?] at javax.mail.Service.connect(Service.java:275) ~[jar:rsrc:mail-1.4.jar!/:?] at javax.mail.Service.connect(Service.java:156) ~[jar:rsrc:mail-1.4.jar!/:?] at com.watersprint.messaging.server.EmailSender.sendEmail(EmailSender.java:99) [rsrc:./:?] at com.watersprint.messaging.server.MonitorDevicesRunnable.run(MonitorDevicesRunnable.java:82) [rsrc:./:?] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [?:1.7.0_75] at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304) [?:1.7.0_75] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) [?:1.7.0_75] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.7.0_75] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [?:1.7.0_75] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [?:1.7.0_75] at java.lang.Thread.run(Thread.java:745) [?:1.7.0_75] 2016-09-15 09:07:00,760 ERROR Error occurred while sending e-mail notification. javax.mail.MessagingException: [EOF] at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1363) at com.sun.mail.smtp.SMTPTransport.helo(SMTPTransport.java:838) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:375) at javax.mail.Service.connect(Service.java:297) at javax.mail.Service.connect(Service.java:156) at javax.mail.Service.connect(Service.java:105) at javax.mail.Transport.send0(Transport.java:168) at javax.mail.Transport.send(Transport.java:98) at org.apache.logging.log4j.core.net.SmtpManager.sendMultipartMessage(SmtpManager.java:241) at org.apache.logging.log4j.core.net.SmtpManager.sendEvents(SmtpManager.java:150) at org.apache.logging.log4j.core.appender.SmtpAppender.append(SmtpAppender.java:173) at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:99) at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:430) at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:409) at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:367) at org.apache.logging.log4j.core.Logger.logMessage(Logger.java:112) at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:727) at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:716) at org.apache.logging.log4j.spi.AbstractLogger.error(AbstractLogger.java:354) at com.watersprint.messaging.server.EmailSender.sendEmail(EmailSender.java:110) at com.watersprint.messaging.server.MonitorDevicesRunnable.run(MonitorDevicesRunnable.java:82) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 2016-09-15 09:07:00,762 ERROR An exception occurred processing Appender SMTPAppender org.apache.logging.log4j.LoggingException: Error occurred while sending email at org.apache.logging.log4j.core.net.SmtpManager.sendEvents(SmtpManager.java:153) at org.apache.logging.log4j.core.appender.SmtpAppender.append(SmtpAppender.java:173) at org.apache.logging.log4j.core.config.AppenderControl.callAppender(AppenderControl.java:99) at org.apache.logging.log4j.core.config.LoggerConfig.callAppenders(LoggerConfig.java:430) at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:409) at org.apache.logging.log4j.core.config.LoggerConfig.log(LoggerConfig.java:367) at org.apache.logging.log4j.core.Logger.logMessage(Logger.java:112) at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:727) at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:716) at org.apache.logging.log4j.spi.AbstractLogger.error(AbstractLogger.java:354) at com.watersprint.messaging.server.EmailSender.sendEmail(EmailSender.java:110) at com.watersprint.messaging.server.MonitorDevicesRunnable.run(MonitorDevicesRunnable.java:82) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:304) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Caused by: javax.mail.MessagingException: [EOF] at com.sun.mail.smtp.SMTPTransport.issueCommand(SMTPTransport.java:1363) at com.sun.mail.smtp.SMTPTransport.helo(SMTPTransport.java:838) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:375) at javax.mail.Service.connect(Service.java:297) at javax.mail.Service.connect(Service.java:156) at javax.mail.Service.connect(Service.java:105) at javax.mail.Transport.send0(Transport.java:168) at javax.mail.Transport.send(Transport.java:98) at org.apache.logging.log4j.core.net.SmtpManager.sendMultipartMessage(SmtpManager.java:241) at org.apache.logging.log4j.core.net.SmtpManager.sendEvents(SmtpManager.java:150) ... 18 more </code></pre>
0
#1044 - Access denied for user 'someusr'@'localhost' to database 'somedb'
<p>I'm trying to give admin rights to MySQL user using this SQL statement ran on cpanel>phpmyadmin>SQL</p> <pre><code>GRANT ALL PRIVILEGES ON somedb.* TO 'someusr'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION; </code></pre> <p>but it's giving user denied error:</p> <pre><code>#1044 - Access denied for user 'someusr'@'localhost' to database 'somedb' </code></pre> <p>We are trying to Integrate our website "www.somewebsite.com" MySQL database with Peachtree accounting software using Dell Boomi AtomSphere. </p> <p>As per Dell Boomi forums. They replied in the link.</p> <p><a href="https://community.boomi.com/message/8983" rel="nofollow noreferrer">https://community.boomi.com/message/8983</a></p> <p>There is no global privileges option on the phpMyAdmin page. There is only data and structure privileges in Cpanel>MySQL Database but no Administration privileges as shown in this video @ 8:27 sec; <a href="https://youtu.be/64nYbTkcRZ4?t=507" rel="nofollow noreferrer">https://youtu.be/64nYbTkcRZ4?t=507</a></p> <p>I tried using SHOW GRANTS FOR 'someusr'@'localhost';</p> <p>It's showing:</p> <p>Grants for someusr@localhost </p> <p>GRANT USAGE ON <em>.</em> TO 'someusr'@'localhost' IS GRANTABLE = NO</p> <p>What should I do?</p>
0
geckodriver.exe not in current directory or path variable, Selenium 2.53.1 + Firefox 48 + Selenium 3 Beta
<p>Seen a lot of questions regarding Selenium 2.53.1 and Firefox 47.0.1, but none in regards to the Selenium 3 Beta release. I am attempting to use the new gecko/marionette Firefox webdrivers, but even though I have the driver location in; my environment path, Firefox install folder in programs, and give the drive location in the system environment, it will still not work correctly.</p> <p><strong>Error:</strong></p> <p><em>The geckodriver.exe does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at <a href="https://github.com/mozilla/geckodriver/releases">https://github.com/mozilla/geckodriver/releases</a>.</em></p> <p><strong>Using:</strong></p> <ul> <li>Selenium 2.53.1 server</li> <li>Firefox 48</li> <li>Selenium 3 Beta DLLs</li> <li>Window 10</li> </ul> <p><strong>Example Code 1</strong></p> <pre><code> using OpenQA.Selenium.Firefox; public static class FirefoxInitialise { public static IWebDriver Driver {get; set;} Driver = new FirefoxDriver(); } </code></pre> <p>Also attempted the below:</p> <pre><code> using OpenQA.Selenium.Firefox; public static class FirefoxInitialise { public static IWebDriver Driver {get; set;} FirefoxDriverServices service = FirefoxDriverService.CreateDefaultService(); service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe"; FirefoxOptions options = new FirefoxOptions(); TimeSpan time = TimeSpan.FromSeconds(10); Driver = new FirefoxDriver(service, options, time); } </code></pre> <p>Any help or insight as to why the code still won't detect this driver would be greatly appreciated it.</p>
0
How to install MySQL 5.7 on Amazon ec2
<p>How am I able to install MySQL 5.7 in the cloud on Amazon EC2? </p> <p>Most of the Amazon Machine Instances (AMIs) that I see either lack any MySQL server or possess an older version such as MySQL Server 5.5</p> <p>I want to use the latest and greatest.</p>
0
Using calc() on repsonsive width to center element
<p>Is it possible to use calc() to center an element, which has a width defined with % ?</p> <p>e.g.</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>.wrapper { width: 100%; background-color: black; height: 300px; position: absolute; top: 0; } .inside { width: 100%; margin-left: 30px; background-color: yellow; height: 250px; margin: 20px; } .inside h1 { width: 30%; background-color: white; text-align: center; } .inside h1 { position: absolute; left: calc(50% - 15%); left: -webkit-calc(50% - 15%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="wrapper"&gt; &lt;div class="inside"&gt; &lt;h1&gt;CENTERED to viewport&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="https://i.stack.imgur.com/3SpCN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3SpCN.jpg" alt="slider"></a></p> <p>This is the slider. It has a "string", which guides through the steps of the slider and the header is always in the middle of the screen. But for design purpose, the line starts a bit to the right and ends a bit to the left, which is given with a width of 80%. The top is slider no.1 with the string, the second slider, which is synced is the area with the big white square.</p> <p>Maybe now it is a bit more clear, why I tried what I tried.</p>
0
The Operation could not be completed. The system cannot find the path specified
<p>I created a C# Website using Visual studio 2015 in my laptop, i copied the same folder to my desktop system and open in Visual studio 2015, when i try to run the application its suddenly gives following error.</p> <blockquote> <p><strong>The operation could not be completed. The system cannot find the path specified</strong></p> </blockquote> <p>Anybody feel same error in your latest Visual Studio 2015? I updated all the latest patches. </p> <p>following trial are done</p> <ul> <li>Re created the soluition file(.sln)</li> <li>Deleted Web.config and added new one</li> </ul> <p><a href="https://i.stack.imgur.com/dbtYf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dbtYf.png" alt="Visual studio 2015 Error The operation could not be completed. The system cannot find the path specified"></a></p> <p>Still the error exists, so i cant able to debug or run the application.</p>
0
method or data member not found in vb6?
<p>This is my code </p> <pre><code>Sub filllistview() Dim itmX As ListItem Main rs.Open " select * from hatw order by id desc ", dbconn, 3, 2 If Not rs.EOF Then ListView1.ListItems.Clear rs.MoveFirst Do While Not rs.EOF Set itmX = ListView1.ListItems.Add(1, , rs!id) itmX.ListSubItems.Add , , rs!no_of_text itmX.ListSubItems.Add , , rs!date_of_text itmX.ListSubItems.Add , , rs!Title rs.MoveNext Loop Else ListView1.ListItems.Clear End If rs.Close Set rs = Nothing End Sub </code></pre> <p>When I hit <kbd>F5</kbd> this error occurs:</p> <blockquote> <p>method or data member not found</p> </blockquote> <p>The error highlights this statement:</p> <blockquote> <pre><code>ListView1.ListItems.Clear </code></pre> </blockquote>
0
How to call an ajax function in a for loop
<p>I'm new to ajax and JavaScript. What am trying to do is to call an ajax function several times to fetch certain data from a resource and then "push" all of the data into an array so that I can use it later on in the code. Here is my code.</p> <pre><code>var arr = []; var users = ["brunofin", "comster404", "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; for (i = 0; i &lt; users.length; i++) { $.ajax({ url: "https://api.twitch.tv/kraken/streams/" + users[i], success: function(data) { arr.push(data); }, error: function(data) { arr.push("blank"); }, complete: function() { if (i == users.length) { console.log(arr); //This seem to print even when the condition isn't true } } }); } </code></pre> <p>The problem with the code is that, it prints to the console even when <code>i</code> isn't equal to <code>users.length</code></p> <p>My question is; how do I make certain that it waits until <code>i == users.length</code> is true before it prints to the console? Please keep in mind that I still desire the process to be asynchronous.</p>
0
Can num++ be atomic for 'int num'?
<p>In general, for <code>int num</code>, <code>num++</code> (or <code>++num</code>), as a read-modify-write operation, is <strong>not atomic</strong>. But I often see compilers, for example <a href="https://en.wikipedia.org/wiki/GNU_Compiler_Collection" rel="noreferrer">GCC</a>, generate the following code for it (<a href="https://godbolt.org/g/UFKEvp" rel="noreferrer">try here</a>):</p> <pre class="lang-c prettyprint-override"><code>void f() { int num = 0; num++; } </code></pre> <pre><code>f(): push rbp mov rbp, rsp mov DWORD PTR [rbp-4], 0 add DWORD PTR [rbp-4], 1 nop pop rbp ret </code></pre> <p>Since line 5, which corresponds to <code>num++</code> is one instruction, can we conclude that <code>num++</code> <strong>is atomic</strong> in this case?</p> <p>And if so, <strong>does it mean that so-generated <code>num++</code> can be used in concurrent (multi-threaded) scenarios without any danger of data races</strong> (i.e. we don't need to make it, for example, <code>std::atomic&lt;int&gt;</code> and impose the associated costs, since it's atomic anyway)?</p> <p><strong>UPDATE</strong></p> <p>Notice that this question is <em>not</em> whether increment <em>is</em> atomic (it's not and that was and is the opening line of the question). It's whether it <em>can</em> be in particular scenarios, i.e. whether one-instruction nature can in certain cases be exploited to avoid the overhead of the <code>lock</code> prefix. And, as the accepted answer mentions in the section about uniprocessor machines, as well as <a href="https://stackoverflow.com/a/39414316/4973224">this answer</a>, the conversation in its comments and others explain, <strong>it can</strong> (although not with C or C++).</p>
0
Error 'String or binary data would be truncated' in Microsoft SQL
<p>I got this error when inserting data to Microsoft SQL.</p> <blockquote> <p>error: ('22001', '[22001] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]String or binary data would be truncated. (8152) (SQLParamData); [01000] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The statement has been terminated. (3621)')</p> </blockquote> <p>FYI, I use Python 2.7 and <code>pyodbc</code> library.</p> <p>What is that error about? What should I do to solve it?</p>
0
Send POST data via raw JSON with Postman
<p>I've got Postman (the one that doesn't open in Chrome) and I'm trying to do a POST request using raw JSON.</p> <p>In the Body tab I have &quot;raw&quot; selected and &quot;JSON (application/json)&quot; with this body:</p> <pre><code>{ &quot;foo&quot;: &quot;bar&quot; } </code></pre> <p>For the header I have 1, <code>Content-Type: application/json</code></p> <p>On the PHP side I'm just doing <code>print_r($_POST);</code> for now, and I'm getting an empty array.</p> <hr /> <p>If I use jQuery and do:</p> <pre><code>$.ajax({ &quot;type&quot;: &quot;POST&quot;, &quot;url&quot;: &quot;/rest/index.php&quot;, &quot;data&quot;: { &quot;foo&quot;: &quot;bar&quot; } }).done(function (d) { console.log(d); }); </code></pre> <p>I'm getting as expected:</p> <pre><code>Array ( [foo] =&gt; bar ) </code></pre> <p>So why isn't it working with Postman?</p> <hr /> <p>Postman screenshots:</p> <p><a href="https://i.stack.imgur.com/Zkviw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Zkviw.png" alt="enter image description here" /></a></p> <p>and header:</p> <p><a href="https://i.stack.imgur.com/KxBsi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KxBsi.png" alt="enter image description here" /></a></p>
0
Small Example for pyserial using Threading
<p>Can anyone please give me a small and simple example on how to use threading with pyserial communication. I am googling for over three days and I am still illeterate and I dont even have a working piece of code which integrate both of them</p> <p>Basically I am aiming to use threading in this scenario:</p> <p>Have a serial communication continuously go on in the back ground to attain certain value (say A) from an MCU.</p> <p>Stop attaining value A - then attain value B...and start continuously attaining value A again. </p> <p>You can find some basic code here. </p> <pre><code>import threading import time import sys import serial import os import time def Task1(ser): while 1: print "Inside Thread 1" ser.write('\x5A\x03\x02\x02\x02\x09') # Byte ArrayTo Control a MicroProcessing Unit b = ser.read(7) print b.encode('hex') print "Thread 1 still going on" time.sleep(1) def Task2(ser): print "Inside Thread 2" print "I stopped Task 1 to start and execute Thread 2" ser.write('x5A\x03\x02\x08\x02\x0F') c = ser.read(7) print c.encode('hex') print "Thread 2 complete" def Main(): ser = serial.Serial(3, 11520) t1 = threading.Thread(target = Task1, args=[ser]) t2 = threading.Thread(target = Task2, args=[ser]) print "Starting Thread 1" t1.start() print "Starting Thread 2" t2.start() print "=== exiting ===" ser.close() if __name__ == '__main__': Main() </code></pre>
0
"Creating an image format with an unknown type is an error" with UIImagePickerController
<p>While choosing an image from the image picker in iOS 10 Swift 3 I am getting an error - <code>Creating an image format with an unknown type is an error</code></p> <pre><code> func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { imagePost.image = image self.dismiss(animated: true, completion: nil) } </code></pre> <p>The image is not getting selected and updated. I need help or suggestion to know if the syntax or anything regarding this method has been changed in iOS10 or Swift 3 or is there any other way to do this.</p>
0
Why Time complexity of permutation function is O(n!)
<p>Consider following code.</p> <pre class="lang-java prettyprint-override"><code>public class Permutations { static int count=0; static void permutations(String str, String prefix){ if(str.length()==0){ System.out.println(prefix); } else{ for(int i=0;i&lt;str.length();i++){ count++; String rem = str.substring(0,i) + str.substring(i+1); permutations(rem, prefix+str.charAt(i)); } } } public static void main(String[] args) { permutations("abc", ""); System.out.println(count); } } </code></pre> <p>here the logic, that i think is followed is- it considers each character of the string as a possible prefix and permutes the remaining n-1 characters. <br> so by this logic recurrence relation comes out to be <br></p> <pre><code>T(n) = n( c1 + T(n-1) ) // ignoring the print time </code></pre> <p>which is obviously O(n!). but when i used a count variable to see wheather algo really grows in order of n!, i found different results.<br> for 2-length string for count++(inside for loop) runs 4 times, for 3-length string value of count comes 15 and for 4 and 5-length string its 64 and 325.<br> It means it grows worse than n!. then why its said that this(and similar algos which generate permuatations) are O(n!) in terms of run time.</p>
0
How can I read tar.gz file using pandas read_csv with gzip compression option?
<p>I have a very simple csv, with the following data, compressed inside the tar.gz file. I need to read that in dataframe using pandas.read_csv. </p> <pre><code> A B 0 1 4 1 2 5 2 3 6 import pandas as pd pd.read_csv("sample.tar.gz",compression='gzip') </code></pre> <p>However, I am getting error:</p> <pre><code>CParserError: Error tokenizing data. C error: Expected 1 fields in line 440, saw 2 </code></pre> <p>Following are the set of read_csv commands and the different errors I get with them:</p> <pre><code>pd.read_csv("sample.tar.gz",compression='gzip', engine='python') Error: line contains NULL byte pd.read_csv("sample.tar.gz",compression='gzip', header=0) CParserError: Error tokenizing data. C error: Expected 1 fields in line 440, saw 2 pd.read_csv("sample.tar.gz",compression='gzip', header=0, sep=" ") CParserError: Error tokenizing data. C error: Expected 2 fields in line 94, saw 14 pd.read_csv("sample.tar.gz",compression='gzip', header=0, sep=" ", engine='python') Error: line contains NULL byte </code></pre> <p>What's going wrong here? How can I fix this?</p>
0
How to tell spring to only load the needed beans for the JUnit test?
<p>A simple question that might have an advanced answer.</p> <p>The Question: My question is, is there a way to instantiate only the classes, in your application context, needed for that specific JUnit test ?</p> <p>The Reason: My application context is getting quite big. I also do a lot of integration tests so you I guess you would understand when I say that every time I run a test all the classes in my application context get instantiated and this takes time. </p> <p>The Example:</p> <p>Say class Foo inject only bar </p> <pre><code>public class Foo { @Inject Bar bar; @Test public void testrunSomeMethod() throws RegisterFault { bar.runSomeMethod(); } </code></pre> <p>but the application context has beans foobar and bar. I know this is not a vaild application context but rest assure all my code works.</p> <pre><code>&lt;beans&gt; &lt;bean id="foobar" class="some.package.FooBar"/&gt; &lt;bean id="bar" class="some.package.Bar"/&gt; &lt;beans&gt; </code></pre> <p>So how do I tell spring to only instantiate Bar and ignore FooBar for the test class foo.</p> <p>Thank you.</p>
0
Django get_object_or_404 is not defined
<p>I am developing a standalone application which uses ORM of django. In my main application, I am using django's module of get_object_or_404.</p> <p>I have imported it with all its dependencies when I run the script, it gives me the error: </p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 240, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/celery/app/trace.py", line 438, in __protected_call__ return self.run(*args, **kwargs) File "/root/standAlone/tasks.py", line 48, in task1 NameError: global name 'get_object_or_404' is not defined </code></pre> <p>Here is my full script code:</p> <pre><code>import django from celery import Celery from django.conf import settings settings.configure( DATABASE_ENGINE = "django.db.backends.mysql", DATABASE_NAME = "database name", DATABASE_USER = "username", DATABASE_PASSWORD = "password", DATABASE_HOST = "host", DATABASE_PORT = "3306", INSTALLED_APPS = ("myApp",) ) django.setup() from django.db import models from myApp.models import * from django.contrib import messages from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.shortcuts import render,redirect from django.shortcuts import get_list_or_404, get_object_or_404 from celery.decorators import task from celery.utils.log import get_task_logger app = Celery('tasks', broker='redis://broker_url') @app.task(name="task1") def task1(recipe_pk): recipe = get_object_or_404(Recipe, pk=recipe_pk) #error occurs here recipe.status = 'Completed' recipe.save() </code></pre> <p>Does anyone know how to solve this problem?</p>
0
Change the color of the title bar (caption) of a win32 application
<p>I want to change the color of the title bar in my application as I have seen done in programs such as Skype Preview. I have found only one solution offered on the internet for this (WM_NCPAINT) which seems to require me to draw a completely custom title bar which is of course not ideal when all I want to do is change the background color. Is anyone aware of a better solution? Someone suggested hooking GetSysColor, but it is never called with an index of 2 (COLOR_ACTIVECAPTION) so the color is being retrieved from elsewhere.</p> <p>Current title bar:</p> <p><a href="https://i.stack.imgur.com/WVGDv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WVGDv.png" alt="" /></a><br /> <sub>(source: <a href="https://cdn.pbrd.co/images/fuI0GBSuK.png" rel="noreferrer">pbrd.co</a>)</sub></p> <p>End goal:</p> <p><a href="https://i.stack.imgur.com/6rA5X.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6rA5X.png" alt="" /></a></p>
0
Incorrect date shown in new Date() in JavaScript
<p><a href="https://i.stack.imgur.com/GaNm1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GaNm1.png" alt="enter image description here"></a></p> <p>This is what I get in chrome console. I pass "2016-09-05"(YYYY-MM-DD) as the date and it shows me Sept 4,2016 as the date. </p> <p>Another constructor shows the right date</p> <p><a href="https://i.stack.imgur.com/CB1eN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CB1eN.png" alt="enter image description here"></a></p> <p>Passing it comma separated needs some tokenizing + parsing + making month zero indexed which I want to avoid</p>
0
Android postDelayed Handler Inside a For Loop?
<p>Is there any way of running a handler inside a loop? I have this code but is not working as it does not wait for the loop but executes the code right way:</p> <pre><code>final Handler handler = new Handler(); final Runnable runnable = new Runnable() { public void run() { // need to do tasks on the UI thread Log.d(TAG, "runn test"); // for (int i = 1; i &lt; 6; i++) { handler.postDelayed(this, 5000); } } }; // trigger first time handler.postDelayed(runnable, 0); </code></pre> <p>Of course when I move the post delayed outside the loop works but it does not iterate nor execute the times I need:</p> <pre><code>final Handler handler = new Handler(); final Runnable runnable = new Runnable() { public void run() { // need to do tasks on the UI thread Log.d(TAG, "runn test"); // for (int i = 1; i &lt; 6; i++) { } // works great! but it does not do what we need handler.postDelayed(this, 5000); } }; // trigger first time handler.postDelayed(runnable, 0); </code></pre> <p><strong>SOLUTION FOUND:</strong></p> <p>I need to use asyntask along with Thread.sleep(5000) in the doInBackground method:</p> <pre><code>class ExecuteAsyncTask extends AsyncTask&lt;Object, Void, String&gt; { // protected String doInBackground(Object... task_idx) { // String param = (String) task_idx[0]; // Log.d(TAG, "xxx - iter value started task idx: " + param); // stop try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } // Log.d(TAG, "xxx - iter value done " + param); return " done for task idx: " + param; } // protected void onPostExecute(String result) { Log.d(TAG, "xxx - task executed update ui controls: " + result); } } for(int i = 0; i &lt; 6; i ++){ // new ExecuteAsyncTask().execute( String.valueOf(i) ); } </code></pre>
0
converting RegExp to String then back to RegExp
<p>So I have a RegExp <code>regex = /asd/</code></p> <p>I am storing it as a as a key in my key-val store system.</p> <p>So I say <code>str = String(regex)</code> which returns <code>"/asd/"</code>.</p> <p>Now I need to convert that string back to a RegExp.</p> <p>So I try: <code>RegExp(str)</code> and I see <code>/\/asd\//</code></p> <p>this is not what I want. It is not the same as <code>/asd/</code></p> <p>Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like <code>/i</code> or <code>/g</code></p> <p>Is there a better way to do this?</p>
0
How do I keep my input fields on one line while centering the DIV that contains them?
<p>I gave this CSS class to some input fields </p> <pre><code>.searchField { display: inline-block; } </code></pre> <p>This is their underlying HTML ...</p> <pre><code>&lt;div id="searchForm"&gt; Search For Results&lt;br&gt; &lt;form id="search-form" action="/races/search" accept-charset="UTF-8" method="get"&gt;&lt;input name="utf8" type="hidden" value="✓"&gt; &lt;input type="text" name="first_name" id="first_name" placeholder="First Name" class="searchField"&gt; &lt;input type="text" name="last_name" id="last_name" placeholder="Last Name" class="searchField"&gt; &lt;input type="text" name="my_object" id="my_object" placeholder="Event" size="50" class="searchField"&gt; &lt;input alt="Search" type="image" src="/assets/magnifying-glass-0220f37269f90a370c3bb60229240f2a4e15b335cd42e64563ba65e4f22e4.png" class="search_button"&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>However, despite the fact that there is enough horizontal screen real estate, one of them keeps wrapping to teh next line, as this Fiddle illustrates -- <a href="https://jsfiddle.net/3mwn14fk/" rel="noreferrer">https://jsfiddle.net/3mwn14fk/</a> . How do I keep these items on one line (assuming there is enough browser width)? Note I also want to keep the DIV they are within vertically and horizontally centered.</p> <p><b>Edit:</b> This is what I see in the Fiddle. This is on Firefox. Note the text fields are not on one line.</p> <p><a href="https://i.stack.imgur.com/FYWGn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FYWGn.png" alt="What I see in my Fiddle"></a></p> <p><b>Edit 2</b></p> <p>Per Monica's Fiddle, this is what I see. Note that the first naem and last name are on one line, but the event text box is on the next line. I would like all three to be on the same line, even if the black box containing them has to expand</p> <p><a href="https://i.stack.imgur.com/l4ZbL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/l4ZbL.png" alt="What I see from Monica&#39;s Fiddle"></a></p>
0
How to check if property exists on potentially undefined object?
<p>So there are questions on S.O. that answer how to check if a property on an object exists. <a href="https://stackoverflow.com/questions/11040472/check-if-object-property-exists-using-a-variable">Example</a> Answer is to use <code>Object.prototype.hasOwnProperty()</code>.</p> <p>However, how would you check the property of a potentially undefined object?</p> <p>If one were to attempt to just directly check if a property exists on an undefined object then it would be a reference error.</p> <p>Semantically, it seems better to check code directly <code>if (obj.prop) //dosomething</code> -- it shows clearer intent. Is there any way to achieve this? Preferably, is there a built-in Javascript method to do such a thing or by convention?</p> <p><strong>Motive:</strong> A package adds property user.session.email -- but I'm checking to see if email exists, not the session, though the session could be nonexistent.</p> <p><strong>Update:</strong> Many of the answers say to use the &amp;&amp; operator to short-circuit. I'm aware that this is a possible solution, but it is not exactly what is desired as it seems like we're working AROUND the JS object syntax -- that is, though you want to really check for a property on an object, you are being forced to check if the object exists in order to do so.</p> <p><strong>Note to being marked as closed</strong> Why was this marked as closed? The link that presumes this is a duplicate may not yield the same answers. We're looking for a better, more semantic solution and marking this closed makes the assumption that "nested" === "potentially undefined".</p> <p><strong>This question is disputably closed:</strong> Since I can't answer my own question now. As of recently, a proposal was put in Stage 1 <a href="https://github.com/tc39/proposal-optional-chaining" rel="noreferrer">here</a> that would solve this very issue. Again, the question wants a more semantic solution as is shown in the proposal. </p>
0
angular 2 Observable complete not called
<p>I am playing around with hero app fro angular 2 tutorial and right now i have this Component</p> <pre><code>import { Component, OnInit } from '@angular/core' import { Subject } from 'rxjs/Subject'; import { Hero } from "./hero"; import { Router } from "@angular/router"; import { HeroService } from "./hero.service"; import { BehaviorSubject } from "rxjs/BehaviorSubject"; @Component({ selector: 'hero-search', templateUrl: 'app/hero-search.component.html', styleUrls: ['app/hero-search.component.css'], }) export class HeroSearchComponent implements OnInit{ heroes: Hero[]; isLoading: BehaviorSubject&lt;boolean&gt; = new BehaviorSubject(false); error: any; private searchNameStream = new Subject&lt;string&gt;(); constructor( private heroService: HeroService, private router: Router ) {} ngOnInit() { this.searchNameStream .debounceTime(400) .distinctUntilChanged() .switchMap(name =&gt; { this.isLoading.next(true); return this.heroService.getHeroesByName(name) }) .subscribe( heroes =&gt; this.heroes = heroes, error =&gt; this.error = error, () =&gt; { console.log('completed'); this.isLoading.next(false); }) } // Push a search term into the observable stream. search(Name: string): void { this.searchNameStream.next(Name) } gotoDetail(hero: Hero): void { let link = ['/detail', hero.id]; this.router.navigate(link); } } </code></pre> <p>The problem is that, if i understand it correctly, subscribe takes three callback parameters <code>.subscribe(success, failure, complete);</code>. But in my case the complete part is never executed. I guess it has something to do with how switchMap works. Am i right?</p>
0
How to add space between table cells `td`?
<p>I want to make modal window like window explorer when you see there is file column and Date with sort function, I got that working. I removed all borders from table, Now i want to add space between columns <code>td</code> cell. how can I do that with CSS ?</p> <p>main.css</p> <pre><code>table { border:none !important; border-spacing: 10px !important; } </code></pre> <p>main.html</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;th&gt;File&lt;/th&gt; &lt;th&gt; &lt;p ng-click="sortType = 'fileDate'; sortReverse = !sortReverse"&gt; Date &lt;span ng-show="sortType == 'fileDate' &amp;&amp; !sortReverse" class="glyphicon glyphicon-chevron-down"&gt;&lt;/span&gt; &lt;span ng-show="sortType == 'fileDate' &amp;&amp; sortReverse" class="glyphicon glyphicon-chevron-up"&gt;&lt;/span&gt; &lt;/p&gt; &lt;/th&gt; &lt;/tr&gt; &lt;tr ng-repeat="file in data | orderBy:sortType:sortReverse"&gt; &lt;td ng-click="downloadServerFile(file.filename)" class="noBorder"&gt;{{file.filename}} &lt;p class=" text-danger current-file-text" ng-if="file.mostRecent"&gt;&lt;small&gt;current file recording in progress&lt;/small&gt;&lt;br&gt;&lt;/p&gt; &lt;/td&gt; &lt;td class="noBorder"&gt;{{file.fileDate |date : 'medium'}}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
0
'C:\wmic' is not recognized as an internal or external command, operable program or batch file
<p>I want to display in a browser the load percentage of a cpu trough php. This is the code I am using:</p> <pre><code>$command ="C:\\wmic cpu get loadpercentage"; echo shell_exec("$command 2&gt;&amp;1 ; echo $?" ); </code></pre> <p>This is the output:</p> <pre><code>'C:\wmic' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>What am I missing?</p> <p>Update - 1</p> <p>Change the code to allow spaces between words: <code>$command ="C:\\wmic^ cpu^ get^ loadpercentage";</code></p> <pre><code>'C:\wmic cpu get loadpercentage' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>Now the entire line of code is being read, not only <strong>'C:\wmic'</strong></p>
0
Print all data in multiple page pagination
<p>I have problem to print all data in data table that have pagination. I have already do research and found this same question in this link</p> <p><a href="https://stackoverflow.com/questions/468881/print-div-id-printarea-div-only">Print &lt;div id=&quot;printarea&quot;&gt;&lt;/div&gt; only?</a></p> <p><a href="https://stackoverflow.com/questions/8823575/printing-multiple-pages-with-javascript">Printing multiple pages with Javascript</a></p> <p>but some of the coding wont work in my project or maybe i dont understand the coding.</p> <p>this is the example coding that i already tried..so basically i have 19 data in the database ..but in this page i limit it to 15</p> <p><a href="https://i.stack.imgur.com/gVdBp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gVdBp.jpg" alt="example"></a></p> <p>so when i click button print i dont have to go to every page to print all the data in data table.</p> <p>this is the code that i use for button print</p> <pre><code>&lt;div id="printableArea"&gt; &lt;h1&gt;Print me&lt;/h1&gt; </code></pre> <p></p> <p></p> <p><strong>Javascript</strong> </p> <pre><code>function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </code></pre>
0
TypeError: argument of type 'float' is not iterable
<p>I am new to python and TensorFlow. I recently started understanding and executing TensorFlow examples, and came across this one: <a href="https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html" rel="nofollow noreferrer">https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html</a></p> <p>I got the error, <strong>TypeError: argument of type 'float' is not iterable</strong>, and I believe that the problem is with the following line of code:</p> <pre><code>df_train[LABEL_COLUMN] = (df_train['income_bracket'].apply(lambda x: '&gt;50K' in x)).astype(int) </code></pre> <p>(income_bracket is the label column of the census dataset, with '&gt;50K' being one of the possible label values, and the other label is '=&lt;50K'. The dataset is read into df_train. The explanation provided in the documentation for the reason to do the above is, &quot;Since the task is a binary classification problem, we'll construct a label column named &quot;label&quot; whose value is 1 if the income is over 50K, and 0 otherwise.&quot;)</p> <p>If anyone could explain me what is exactly happening and how should I fix it, that'll be great. I tried using Python2.7 and Python3.4, and I don't think that the problem is with the version of the language. Also, if anyone is aware of great tutorials for someone who is new to TensorFlow and pandas, please share the links.</p> <p>Complete program:</p> <pre><code>import pandas as pd import urllib import tempfile import tensorflow as tf gender = tf.contrib.layers.sparse_column_with_keys(column_name=&quot;gender&quot;, keys=[&quot;female&quot;, &quot;male&quot;]) race = tf.contrib.layers.sparse_column_with_keys(column_name=&quot;race&quot;, keys=[&quot;Amer-Indian-Eskimo&quot;, &quot;Asian-Pac-Islander&quot;, &quot;Black&quot;, &quot;Other&quot;, &quot;White&quot;]) education = tf.contrib.layers.sparse_column_with_hash_bucket(&quot;education&quot;, hash_bucket_size=1000) marital_status = tf.contrib.layers.sparse_column_with_hash_bucket(&quot;marital_status&quot;, hash_bucket_size=100) relationship = tf.contrib.layers.sparse_column_with_hash_bucket(&quot;relationship&quot;, hash_bucket_size=100) workclass = tf.contrib.layers.sparse_column_with_hash_bucket(&quot;workclass&quot;, hash_bucket_size=100) occupation = tf.contrib.layers.sparse_column_with_hash_bucket(&quot;occupation&quot;, hash_bucket_size=1000) native_country = tf.contrib.layers.sparse_column_with_hash_bucket(&quot;native_country&quot;, hash_bucket_size=1000) age = tf.contrib.layers.real_valued_column(&quot;age&quot;) age_buckets = tf.contrib.layers.bucketized_column(age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65]) education_num = tf.contrib.layers.real_valued_column(&quot;education_num&quot;) capital_gain = tf.contrib.layers.real_valued_column(&quot;capital_gain&quot;) capital_loss = tf.contrib.layers.real_valued_column(&quot;capital_loss&quot;) hours_per_week = tf.contrib.layers.real_valued_column(&quot;hours_per_week&quot;) wide_columns = [gender, native_country, education, occupation, workclass, marital_status, relationship, age_buckets, tf.contrib.layers.crossed_column([education, occupation], hash_bucket_size=int(1e4)), tf.contrib.layers.crossed_column([native_country, occupation], hash_bucket_size=int(1e4)), tf.contrib.layers.crossed_column([age_buckets, race, occupation], hash_bucket_size=int(1e6))] deep_columns = [ tf.contrib.layers.embedding_column(workclass, dimension=8), tf.contrib.layers.embedding_column(education, dimension=8), tf.contrib.layers.embedding_column(marital_status, dimension=8), tf.contrib.layers.embedding_column(gender, dimension=8), tf.contrib.layers.embedding_column(relationship, dimension=8), tf.contrib.layers.embedding_column(race, dimension=8), tf.contrib.layers.embedding_column(native_country, dimension=8), tf.contrib.layers.embedding_column(occupation, dimension=8), age, education_num, capital_gain, capital_loss, hours_per_week] model_dir = tempfile.mkdtemp() m = tf.contrib.learn.DNNLinearCombinedClassifier( model_dir=model_dir, linear_feature_columns=wide_columns, dnn_feature_columns=deep_columns, dnn_hidden_units=[100, 50]) COLUMNS = [&quot;age&quot;, &quot;workclass&quot;, &quot;fnlwgt&quot;, &quot;education&quot;, &quot;education_num&quot;, &quot;marital_status&quot;, &quot;occupation&quot;, &quot;relationship&quot;, &quot;race&quot;, &quot;gender&quot;, &quot;capital_gain&quot;, &quot;capital_loss&quot;, &quot;hours_per_week&quot;, &quot;native_country&quot;, &quot;income_bracket&quot;] LABEL_COLUMN = 'label' CATEGORICAL_COLUMNS = [&quot;workclass&quot;, &quot;education&quot;, &quot;marital_status&quot;, &quot;occupation&quot;, &quot;relationship&quot;, &quot;race&quot;, &quot;gender&quot;, &quot;native_country&quot;] CONTINUOUS_COLUMNS = [&quot;age&quot;, &quot;education_num&quot;, &quot;capital_gain&quot;, &quot;capital_loss&quot;, &quot;hours_per_week&quot;] train_file = tempfile.NamedTemporaryFile() test_file = tempfile.NamedTemporaryFile() urllib.urlretrieve(&quot;https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data&quot;, train_file.name) urllib.urlretrieve(&quot;https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test&quot;, test_file.name) df_train = pd.read_csv(train_file, names=COLUMNS, skipinitialspace=True) df_test = pd.read_csv(test_file, names=COLUMNS, skipinitialspace=True, skiprows=1) df_train[LABEL_COLUMN] = (df_train['income_bracket'].apply(lambda x: '&gt;50K' in x)).astype(int) df_test[LABEL_COLUMN] = (df_test['income_bracket'].apply(lambda x: '&gt;50K' in x)).astype(int) def input_fn(df): continuous_cols = {k: tf.constant(df[k].values) for k in CONTINUOUS_COLUMNS} categorical_cols = {k: tf.SparseTensor( indices=[[i, 0] for i in range(df[k].size)], values=df[k].values, shape=[df[k].size, 1]) for k in CATEGORICAL_COLUMNS} feature_cols = dict(continuous_cols.items() + categorical_cols.items()) label = tf.constant(df[LABEL_COLUMN].values) return feature_cols, label def train_input_fn(): return input_fn(df_train) def eval_input_fn(): return input_fn(df_test) m.fit(input_fn=train_input_fn, steps=200) results = m.evaluate(input_fn=eval_input_fn, steps=1) for key in sorted(results): print(&quot;%s: %s&quot; % (key, results[key])) </code></pre> <p>Thank you</p> <p>PS: Full stack trace for the error</p> <pre><code>Traceback (most recent call last): File &quot;/home/jaspreet/PycharmProjects/TicTacTensorFlow/census.py&quot;, line 73, in &lt;module&gt; df_train[LABEL_COLUMN] = (df_train['income_bracket'].apply(lambda x: '&gt;50K' in x)).astype(int) File &quot;/usr/lib/python2.7/dist-packages/pandas/core/series.py&quot;, line 2023, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File &quot;inference.pyx&quot;, line 920, in pandas.lib.map_infer (pandas/lib.c:44780) File &quot;/home/jaspreet/PycharmProjects/TicTacTensorFlow/census.py&quot;, line 73, in &lt;lambda&gt; df_train[LABEL_COLUMN] = (df_train['income_bracket'].apply(lambda x: '&gt;50K' in x)).astype(int) TypeError: argument of type 'float' is not iterable </code></pre>
0
What do you mean by 'make' command in linux?
<p>First, i know that <code>make</code> is used for building the code. But which code?</p> <p>But what does it mean by building a code, and after executing the <code>make</code> command, what is presented to the user?</p> <p>Second, how is it different from <code>make build_for_e2e</code>?</p>
0
How to troubleshoot iOS background app fetch not working?
<p>I am trying to get iOS background app fetch to work in my app. While testing in Xcode it works, when running on the device it doesn't!</p> <ul> <li>My test device is running iOS 9.3.5 (my deployment target is 7.1)</li> <li>I have enabled "Background fetch" under "Background modes" under "Capabilities" on the target in Xcode</li> </ul> <p><a href="https://i.stack.imgur.com/9NxuP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9NxuP.png" alt="enter image description here"></a></p> <p>In application:didFinishLaunchingWithOptions I have tried various intervals with setMinimumBackgroundFetchInterval, including UIApplicationBackgroundFetchIntervalMinimum</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // tell the system we want background fetch //[application setMinimumBackgroundFetchInterval:3600]; // 60 minutes [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]; //[application setMinimumBackgroundFetchInterval:1800]; // 30 minutes return YES; } </code></pre> <p>I have implemented application:performFetchWithCompletionHandler</p> <pre><code>void (^fetchCompletionHandler)(UIBackgroundFetchResult); NSDate *fetchStart; -(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { fetchCompletionHandler = completionHandler; fetchStart = [NSDate date]; [[NSUserDefaults standardUserDefaults] setObject:fetchStart forKey:kLastCheckedContentDate]; [[NSUserDefaults standardUserDefaults] synchronize]; [FeedParser parseFeedAtUrl:url withDelegate:self]; } -(void)onParserFinished { DDLogVerbose(@"AppDelegate/onParserFinished"); UIBackgroundFetchResult result = UIBackgroundFetchResultNoData; NSDate *fetchEnd = [NSDate date]; NSTimeInterval timeElapsed = [fetchEnd timeIntervalSinceDate:fetchStart]; DDLogVerbose(@"Background Fetch Duration: %f seconds", timeElapsed); if ([self.mostRecentContentDate compare:item.date] &lt; 0) { DDLogVerbose(@"got new content: %@", item.date); self.mostRecentContentDate = item.date; [self scheduleNotificationWithItem:item]; result = UIBackgroundFetchResultNewData; } else { DDLogVerbose(@"no new content."); UILocalNotification* localNotification = [[UILocalNotification alloc] init]; localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:60]; localNotification.alertBody = [NSString stringWithFormat:@"Checked for new posts in %f seconds", timeElapsed]; localNotification.timeZone = [NSTimeZone defaultTimeZone]; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; } fetchCompletionHandler(result); } </code></pre> <ul> <li><p>I have (successfully!) tested with the simulator and device using Xcode's Debug/SimulateBackgroundFetch</p></li> <li><p>I have successfully tested with a new scheme as shown in another SO answer (<a href="https://stackoverflow.com/a/29923802/519030">https://stackoverflow.com/a/29923802/519030</a>)</p></li> <li>My tests show code executing in the performFetch method in about 0.3 seconds (so it's not taking a long time)</li> <li>I have verified that the device has background refresh enabled within settings.</li> <li>Of course, I've looked at the other SO questions hoping someone else experienced the same thing. :)</li> </ul> <p>When running on the device and not connected to Xcode, my code is not executing. I've opened the app, closed the app (not killed the app!), waited hours and days. I have tried logging in the fetch handers, and also written code to send local notifications.</p> <p>I once successfully saw my local notifications test on the device, and in fact iOS seemed to trigger the fetch three times, each about about fifteen minutes apart, but then it never occurred again.</p> <p>I know the algorithm used to determine how frequently to allow the background fetch to occur is a mystery, but I would expect it to run at least occasionally within a span of days.</p> <p>I am at a loss for what else to test, or how to troubleshoot why it seems to work in the simulator but not on the device.</p> <p>Appreciate any advice!</p>
0
Linq performance: should I first use `where` or `select`
<p>I have a large <code>List</code> in memory, from a class that has about 20 <code>properties</code>. </p> <p>I'd like to filter this list based on just one <code>property</code>, for a particular task I only need a list of that <code>property</code>. So my query is something like:</p> <pre><code>data.Select(x =&gt; x.field).Where(x =&gt; x == "desired value").ToList() </code></pre> <p>Which one gives me a better performance, using <code>Select</code> first, or using <code>Where</code>?</p> <pre><code>data.Where(x =&gt; x.field == "desired value").Select(x =&gt; x.field).ToList() </code></pre> <p>Please let me know if this is related to the <code>data type</code> I'm keeping the data in memory, or field's type. Please note that I need these objects for other tasks too, so I can't filter them in the first place and before loading them into memory.</p>
0
Change database schema during runtime based on logged in user
<p>I've read many questions and answers about dynamic datasource routing and have implemented a solution using <code>AbstractRoutingDataSource</code> and another(see below). That's fine, but requires hardcoded properties for all datasources. As the number of users using the application increases, this isn't a suitable way of routing any more. Also it would require to add an entry to the properties every time a new user registers. The situation is as follows</p> <ul> <li>1 database server</li> <li>many schemas on that server, every user has their own schema.</li> <li>I only need to change the schema name during runtime</li> <li>schema name is retainable by logged in user</li> </ul> <p>I'm using <code>spring boot 1.4.0</code> together with <code>hibernate 5.1</code> and <code>spring data jpa</code></p> <p>I can't find a way to change the schema completely dynamically. Does someone know how to do it in spring?</p> <p><strong>EDIT:</strong></p> <p>Thanks to @Johannes Leimer's answer, I got a working implemantation. </p> <p>Here's the code:</p> <p><em>User Provider</em>:</p> <pre><code>@Component public class UserDetailsProvider { @Bean @Scope("prototype") public CustomUserDetails customUserDetails() { return (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); } } </code></pre> <p><em>UserSchemaAwareRoutingDatasource</em>:</p> <pre><code>public class UserSchemaAwareRoutingDataSource extends AbstractDataSource { @Inject Provider&lt;CustomUserDetails&gt; customUserDetails; @Inject Environment env; private LoadingCache&lt;String, DataSource&gt; dataSources = createCache(); @Override public Connection getConnection() throws SQLException { try { return determineTargetDataSource().getConnection(); } catch (ExecutionException e){ e.printStackTrace(); return null; } } @Override public Connection getConnection(String username, String password) throws SQLException { System.out.println("getConnection" + username); System.out.println("getConnection2" + password); try { return determineTargetDataSource().getConnection(username, password); } catch (ExecutionException e) { e.printStackTrace(); return null; } } private DataSource determineTargetDataSource() throws SQLException, ExecutionException { try { String schema = customUserDetails.get().getUserDatabase(); return dataSources.get(schema); } catch (NullPointerException e) { e.printStackTrace(); return dataSources.get("fooooo"); } } </code></pre>
0
Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in php with mongoDB :
<p>I am working on <code>php</code> with <code>MongoDB</code>. On running the below script in <code>wamp server</code> by going to <code>localhost/test.php</code>, it gives the error:</p> <blockquote> <p>Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in C:\wamp64\www\test.php on line 3</p> </blockquote> <p>The second error is </p> <blockquote> <p>Fatal error: require(): Failed opening required 'vendor/autoload.php' (include_path='.;C:\php\pear') in C:\wamp64\www\test.php on line 3</p> </blockquote> <p>I also installed <code>composer</code> by <code>composerSetup.exe</code>. Why it is giving the error?</p> <pre><code>&lt;?php require 'vendor/autolod.php'; $client = new Mongo\Client; $companydb = $client-&gt;companydb; $result1 = $companydb-&gt;createCollection('collection1'); var_dump(result1); ?&gt; </code></pre> <p>while <code>phpinfo()</code> is working fine after running this code. </p> <pre><code>&lt;?php echo phpinfo(); ?&gt; </code></pre> <p>Actually I followed <a href="https://www.youtube.com/watch?v=9gEPiIoAHo8" rel="nofollow">this you tube video</a> . He uses XAMP server and run command composer require <code>"mongodb/mongodb=^1.0.0"</code> in <code>xamp/htdocs/projectname/</code> but I used <code>wampserver</code> and in <code>wamp directory</code> there is no <code>htdocs directory</code>. I think I am making mistake at this point. Is'nt it?</p>
0
Blocking pop up while using window.open in javascript
<p><strong>Actually my real scenario is</strong></p> <p>When user opens the modal pop up (say bootstrap modal pop up <a href="http://getbootstrap.com/javascript/#modals" rel="nofollow">http://getbootstrap.com/javascript/#modals</a>), we need to open a url which is already saved by the user. </p> <p>So for that I have tried to open with window.open. But this is always blocking me. Is there any way to overcome this?</p> <p><strong>The following scenarios I have tried.</strong></p> <p>When I try to open using <code>window.open(link, '_blank');</code> and if browser has the blocked the pop up, then I restricted by browser to open the url in new tab.</p> <p>To over come this I have tried like (following) creating anchor link and triggering click event. But this is also not also working.</p> <pre><code>var link = document.createElement('a'); link.setAttribute('href', url); link.target="_blank"; var event = document.createEvent('MouseEvents'); event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null); link.dispatchEvent(event); </code></pre> <p>Some websites by passing this feature.</p> <p>For example, <a href="https://www.online.citibank.co.in/" rel="nofollow">https://www.online.citibank.co.in/</a>.</p> <p>When I click log in button, a new window is opening. They also doing the same functionality as <strong>window.open</strong>. But the browser is not blocking citibank new window.</p> <blockquote> <p>I don't know what is the reason behind this. How to implement this feature?</p> </blockquote>
0
SSLHandshakeException: Handshake failed on Android N/7.0
<p>I'm working on an app for which the (power)users have to set up their own server (i.e. nginx) to run the backend application. The corresponding domain needs to be configured in the app so it can connect. I've been testing primarily on my own phone (sony z3c) and started developing for 5.1. Later I received an update for 6.0 but still maintained a working 5.1 inside the emulator. Not too long ago, I started to work on an AVD with an image for 7.0 and to my suprise it won't connect to my server, telling me the ssl handshake failed. My nginx configuration is pretty strict, but it works for both 5.1 and 6.0, so .... ?!</p> <p>Here is what I know:</p> <ul> <li>I use v24 for support libs, i.e. my compileSdkVersion is 24.</li> <li>I use Volley <a href="https://bintray.com/android/android-utils/com.android.volley.volley" rel="noreferrer">v1.0.0</a>.</li> <li>I've tried the <a href="https://stackoverflow.com/a/33874126">TLSSocketFactory</a>, but it doesn't change anything. This seems to be used most of the times to prevent SSL3 use for older SDK versions anyway.</li> <li>I've tried increasing the <a href="https://stackoverflow.com/questions/32184787/com-android-volley-noconnectionerror-javax-net-ssl-sslhandshakeexception-javax">timeout</a>, but it doesn't change anything.</li> <li>I've tried using HttpURLConnection directly, but it doesn't change anything apart from the stack trace (it's without the volley references, but identical otherwise).</li> </ul> <p>Without the TLSSocketFactory the request are made through a bare request queue, instantiated with <code>Volley.newRequestQueue(context)</code>.</p> <p>This is what I see in android studio:</p> <pre><code>W/System.err: com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: Connection closed by peer W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:151) W/System.err: at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112) W/System.err: Caused by: javax.net.ssl.SSLHandshakeException: Connection closed by peer W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method) W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:357) W/System.err: at com.android.okhttp.Connection.connectTls(Connection.java:235) W/System.err: at com.android.okhttp.Connection.connectSocket(Connection.java:199) W/System.err: at com.android.okhttp.Connection.connect(Connection.java:172) W/System.err: at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367) W/System.err: at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130) W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329) W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246) W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457) W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126) W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:257) W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218) W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java) W/System.err: at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:264) W/System.err: at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234) W/System.err: at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107) W/System.err: at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96) W/System.err: ... 1 more W/System.err: Suppressed: javax.net.ssl.SSLHandshakeException: Handshake failed W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:429) W/System.err: ... 17 more W/System.err: Caused by: javax.net.ssl.SSLProtocolException: SSL handshake terminated: ssl=0x7ffef3748040: Failure in SSL library, usually a protocol error W/System.err: error:10000410:SSL routines:OPENSSL_internal:SSLV3_ALERT_HANDSHAKE_FAILURE (external/boringssl/src/ssl/s3_pkt.c:610 0x7ffeda1d2240:0x00000001) W/System.err: error:1000009a:SSL routines:OPENSSL_internal:HANDSHAKE_FAILURE_ON_CLIENT_HELLO (external/boringssl/src/ssl/s3_clnt.c:764 0x7ffee9d2b70a:0x00000000) W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method) W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:357) W/System.err: ... 17 more </code></pre> <p>Since it says <code>SSLV3_ALERT_HANDSHAKE_FAILURE</code> I can only assume it for some reason tries to connect using SSLv3 and fails, but this doesn't make any sense to me whatsoever. It might be a cipher-issue, but how can I tell what it is trying to use ? I would rather not enable a ciphers on the server, make a connection attempt and repeat.</p> <p>My nginx site uses a let's encrypt certificate and has the following configuration:</p> <pre><code>ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /etc/ssl/certs/lets-encrypt-x1-cross-signed.pem; ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:!aNULL; ssl_dhparam /etc/ssl/certs/dhparam.pem; ssl_ecdh_curve secp384r1; ssl_prefer_server_ciphers on; ssl_protocols TLSv1.2; </code></pre> <p>To test these ciphers I've a <a href="https://superuser.com/a/224263">script</a> and it confirms these ciphers (run on a wheezy vps outside the server's network):</p> <pre> Testing ECDHE-RSA-AES256-GCM-SHA384...YES Testing ECDHE-ECDSA-AES256-GCM-SHA384...NO (sslv3 alert handshake failure) Testing ECDHE-RSA-AES256-SHA384...NO (sslv3 alert handshake failure) Testing ECDHE-ECDSA-AES256-SHA384...NO (sslv3 alert handshake failure) Testing ECDHE-RSA-AES256-SHA...NO (sslv3 alert handshake failure) Testing ECDHE-ECDSA-AES256-SHA...NO (sslv3 alert handshake failure) Testing SRP-DSS-AES-256-CBC-SHA...NO (sslv3 alert handshake failure) Testing SRP-RSA-AES-256-CBC-SHA...NO (sslv3 alert handshake failure) Testing DHE-DSS-AES256-GCM-SHA384...NO (sslv3 alert handshake failure) Testing DHE-RSA-AES256-GCM-SHA384...NO (sslv3 alert handshake failure) Testing DHE-RSA-AES256-SHA256...NO (sslv3 alert handshake failure) Testing DHE-DSS-AES256-SHA256...NO (sslv3 alert handshake failure) Testing DHE-RSA-AES256-SHA...NO (sslv3 alert handshake failure) Testing DHE-DSS-AES256-SHA...NO (sslv3 alert handshake failure) Testing DHE-RSA-CAMELLIA256-SHA...NO (sslv3 alert handshake failure) Testing DHE-DSS-CAMELLIA256-SHA...NO (sslv3 alert handshake failure) Testing AECDH-AES256-SHA...NO (sslv3 alert handshake failure) Testing SRP-AES-256-CBC-SHA...NO (sslv3 alert handshake failure) Testing ADH-AES256-GCM-SHA384...NO (sslv3 alert handshake failure) Testing ADH-AES256-SHA256...NO (sslv3 alert handshake failure) Testing ADH-AES256-SHA...NO (sslv3 alert handshake failure) Testing ADH-CAMELLIA256-SHA...NO (sslv3 alert handshake failure) Testing ECDH-RSA-AES256-GCM-SHA384...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-AES256-GCM-SHA384...NO (sslv3 alert handshake failure) Testing ECDH-RSA-AES256-SHA384...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-AES256-SHA384...NO (sslv3 alert handshake failure) Testing ECDH-RSA-AES256-SHA...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-AES256-SHA...NO (sslv3 alert handshake failure) Testing AES256-GCM-SHA384...NO (sslv3 alert handshake failure) Testing AES256-SHA256...NO (sslv3 alert handshake failure) Testing AES256-SHA...NO (sslv3 alert handshake failure) Testing CAMELLIA256-SHA...NO (sslv3 alert handshake failure) Testing PSK-AES256-CBC-SHA...NO (no ciphers available) Testing ECDHE-RSA-DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing ECDHE-ECDSA-DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing SRP-DSS-3DES-EDE-CBC-SHA...NO (sslv3 alert handshake failure) Testing SRP-RSA-3DES-EDE-CBC-SHA...NO (sslv3 alert handshake failure) Testing EDH-RSA-DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing EDH-DSS-DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing AECDH-DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing SRP-3DES-EDE-CBC-SHA...NO (sslv3 alert handshake failure) Testing ADH-DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing ECDH-RSA-DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing DES-CBC3-SHA...NO (sslv3 alert handshake failure) Testing PSK-3DES-EDE-CBC-SHA...NO (no ciphers available) Testing ECDHE-RSA-AES128-GCM-SHA256...YES Testing ECDHE-ECDSA-AES128-GCM-SHA256...NO (sslv3 alert handshake failure) Testing ECDHE-RSA-AES128-SHA256...NO (sslv3 alert handshake failure) Testing ECDHE-ECDSA-AES128-SHA256...NO (sslv3 alert handshake failure) Testing ECDHE-RSA-AES128-SHA...NO (sslv3 alert handshake failure) Testing ECDHE-ECDSA-AES128-SHA...NO (sslv3 alert handshake failure) Testing SRP-DSS-AES-128-CBC-SHA...NO (sslv3 alert handshake failure) Testing SRP-RSA-AES-128-CBC-SHA...NO (sslv3 alert handshake failure) Testing DHE-DSS-AES128-GCM-SHA256...NO (sslv3 alert handshake failure) Testing DHE-RSA-AES128-GCM-SHA256...NO (sslv3 alert handshake failure) Testing DHE-RSA-AES128-SHA256...NO (sslv3 alert handshake failure) Testing DHE-DSS-AES128-SHA256...NO (sslv3 alert handshake failure) Testing DHE-RSA-AES128-SHA...NO (sslv3 alert handshake failure) Testing DHE-DSS-AES128-SHA...NO (sslv3 alert handshake failure) Testing DHE-RSA-SEED-SHA...NO (sslv3 alert handshake failure) Testing DHE-DSS-SEED-SHA...NO (sslv3 alert handshake failure) Testing DHE-RSA-CAMELLIA128-SHA...NO (sslv3 alert handshake failure) Testing DHE-DSS-CAMELLIA128-SHA...NO (sslv3 alert handshake failure) Testing AECDH-AES128-SHA...NO (sslv3 alert handshake failure) Testing SRP-AES-128-CBC-SHA...NO (sslv3 alert handshake failure) Testing ADH-AES128-GCM-SHA256...NO (sslv3 alert handshake failure) Testing ADH-AES128-SHA256...NO (sslv3 alert handshake failure) Testing ADH-AES128-SHA...NO (sslv3 alert handshake failure) Testing ADH-SEED-SHA...NO (sslv3 alert handshake failure) Testing ADH-CAMELLIA128-SHA...NO (sslv3 alert handshake failure) Testing ECDH-RSA-AES128-GCM-SHA256...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-AES128-GCM-SHA256...NO (sslv3 alert handshake failure) Testing ECDH-RSA-AES128-SHA256...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-AES128-SHA256...NO (sslv3 alert handshake failure) Testing ECDH-RSA-AES128-SHA...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-AES128-SHA...NO (sslv3 alert handshake failure) Testing AES128-GCM-SHA256...NO (sslv3 alert handshake failure) Testing AES128-SHA256...NO (sslv3 alert handshake failure) Testing AES128-SHA...NO (sslv3 alert handshake failure) Testing SEED-SHA...NO (sslv3 alert handshake failure) Testing CAMELLIA128-SHA...NO (sslv3 alert handshake failure) Testing PSK-AES128-CBC-SHA...NO (no ciphers available) Testing ECDHE-RSA-RC4-SHA...NO (sslv3 alert handshake failure) Testing ECDHE-ECDSA-RC4-SHA...NO (sslv3 alert handshake failure) Testing AECDH-RC4-SHA...NO (sslv3 alert handshake failure) Testing ADH-RC4-MD5...NO (sslv3 alert handshake failure) Testing ECDH-RSA-RC4-SHA...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-RC4-SHA...NO (sslv3 alert handshake failure) Testing RC4-SHA...NO (sslv3 alert handshake failure) Testing RC4-MD5...NO (sslv3 alert handshake failure) Testing PSK-RC4-SHA...NO (no ciphers available) Testing EDH-RSA-DES-CBC-SHA...NO (sslv3 alert handshake failure) Testing EDH-DSS-DES-CBC-SHA...NO (sslv3 alert handshake failure) Testing ADH-DES-CBC-SHA...NO (sslv3 alert handshake failure) Testing DES-CBC-SHA...NO (sslv3 alert handshake failure) Testing EXP-EDH-RSA-DES-CBC-SHA...NO (sslv3 alert handshake failure) Testing EXP-EDH-DSS-DES-CBC-SHA...NO (sslv3 alert handshake failure) Testing EXP-ADH-DES-CBC-SHA...NO (sslv3 alert handshake failure) Testing EXP-DES-CBC-SHA...NO (sslv3 alert handshake failure) Testing EXP-RC2-CBC-MD5...NO (sslv3 alert handshake failure) Testing EXP-ADH-RC4-MD5...NO (sslv3 alert handshake failure) Testing EXP-RC4-MD5...NO (sslv3 alert handshake failure) Testing ECDHE-RSA-NULL-SHA...NO (sslv3 alert handshake failure) Testing ECDHE-ECDSA-NULL-SHA...NO (sslv3 alert handshake failure) Testing AECDH-NULL-SHA...NO (sslv3 alert handshake failure) Testing ECDH-RSA-NULL-SHA...NO (sslv3 alert handshake failure) Testing ECDH-ECDSA-NULL-SHA...NO (sslv3 alert handshake failure) Testing NULL-SHA256...NO (sslv3 alert handshake failure) Testing NULL-SHA...NO (sslv3 alert handshake failure) Testing NULL-MD5...NO (sslv3 alert handshake failure </pre> <p>I <em>can</em> open the server-url in the emulator's browser and get a perfect json response so I know the system itself is capable.</p> <p>So the question is, why can't I connect on Android 7 ?</p> <p><strong>Update</strong>:</p> <p>I've looked at a captured packet using tcpdump and wireshark and the enabled ciphers are in the ClientHello, so that should not be a problem.</p> <pre> Cipher Suites (18 suites) Cipher Suite: Unknown (0xcca9) Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (0xc02b) Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 (0xc02c) Cipher Suite: Unknown (0xcca8) Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f) Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030) Cipher Suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (0x009e) Cipher Suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (0x009f) Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA (0xc009) Cipher Suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA (0xc00a) Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (0xc013) Cipher Suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (0xc014) Cipher Suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA (0x0033) Cipher Suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA (0x0039) Cipher Suite: TLS_RSA_WITH_AES_128_GCM_SHA256 (0x009c) Cipher Suite: TLS_RSA_WITH_AES_256_GCM_SHA384 (0x009d) Cipher Suite: TLS_RSA_WITH_AES_128_CBC_SHA (0x002f) Cipher Suite: TLS_RSA_WITH_AES_256_CBC_SHA (0x0035) </pre> <p>As you can see <code>0xc02f</code> and <code>0xc030</code> match, but the next TLSv1.2 packet says: <code>Alert (21), Handshake Failure (40)</code>.</p> <p><strong>Update 2</strong>:</p> <p>These are the curves from Android 5.1 in the ClientHello:</p> <pre> Elliptic curves (25 curves) Elliptic curve: sect571r1 (0x000e) Elliptic curve: sect571k1 (0x000d) Elliptic curve: secp521r1 (0x0019) Elliptic curve: sect409k1 (0x000b) Elliptic curve: sect409r1 (0x000c) Elliptic curve: secp384r1 (0x0018) Elliptic curve: sect283k1 (0x0009) Elliptic curve: sect283r1 (0x000a) Elliptic curve: secp256k1 (0x0016) Elliptic curve: secp256r1 (0x0017) Elliptic curve: sect239k1 (0x0008) Elliptic curve: sect233k1 (0x0006) Elliptic curve: sect233r1 (0x0007) Elliptic curve: secp224k1 (0x0014) Elliptic curve: secp224r1 (0x0015) Elliptic curve: sect193r1 (0x0004) Elliptic curve: sect193r2 (0x0005) Elliptic curve: secp192k1 (0x0012) Elliptic curve: secp192r1 (0x0013) Elliptic curve: sect163k1 (0x0001) Elliptic curve: sect163r1 (0x0002) Elliptic curve: sect163r2 (0x0003) Elliptic curve: secp160k1 (0x000f) Elliptic curve: secp160r1 (0x0010) Elliptic curve: secp160r2 (0x0011) </pre> <p>In the ServerHello <code>secp384r1 (0x0018)</code> is returned.</p> <p>And this is from Android 7:</p> <pre> Elliptic curves (1 curve) Elliptic curve: secp256r1 (0x0017) </pre> <p>Resulting in the Handshake Failure.</p> <p>Changing the nginx configuration by removing secp384r1 or replacing it with the default (prime256v1) does get it to work. So I guess the question remains: am I able to add elliptic curves ?</p> <p>The captured data is the same when using the emulator as when using an Android 7.0 device (General Mobile 4G).</p> <p><strong>Update 3</strong>:</p> <p>Small update, but worth mentioning: I got it to work in the emulator using Android 7.1.1 (!). It shows the following data (again, grabbed using tcpdump and viewed using wireshark):</p> <pre> Elliptic curves (3 curves) Elliptic curve: secp256r1 (0x0017) Elliptic curve: secp384r1 (0x0018) Elliptic curve: secp512r1 (0x0019) </pre> <p>It shows the same 18 Cipher Suites.</p>
0
Beta testing: App not appearing in Play Store Beta tab
<p>I have been trying for several weeks now to get the Google Alpha / Beta testing functionality on the Play Store to work with no success. As far as I can tell I have followed the process but clearly something is not working from my side. I hope someone on SO can tell me what I'm doing wrong.</p> <p>I have created both an Apha and Beta testing community.</p> <p>I have added the Beta testing community to the Beta testing section that relates to using Google+ communities to test. My Beta testing community does have members added.</p> <p>Although I have an Alpha testing community, none of the Alpha testing methods are currently enabled.</p> <p>On my test device, using a Google account that is a member of my Beta testing community, I only ever see the version of my app that is currently in Prod. I have spent days waiting just in case it takes a couple of days to show up (at least a week which I assume should be long enough).</p> <p>I need to test the release version because I am trying to test some inapp billing functionality that I had to change due to security warnings from Google relating to my current Prod version.</p> <p>BUT: if I load the release version of the app directly (instead of downloading from the Play Store) I can see that it is seeing this account as a "test account" because when I test the inapp billing I get the correct message telling me that the subscription will renew every day but I won't be charged. However the Beta version of the app never appears in the "BETA" tab in the Play Store.</p> <p>I have noticed something "strange" (possibly) in the developer console though: When I click on the "Beta Testing" tab it shows 10399 supported devices and 0 excluded devices for the Beta app. However if I click on the line of the Beta app where you can promote the app etc, the details that are then displayed indicate 0 supported Android devices. Why would this be? This seems to be conflicting information on the console.</p> <p>Note: The current Prod version of my app was developed using Eclipse. I have recently converted to Android Studio and this is my first upload using Android Studio.</p> <p>Where else should I be looking to get my app to appear in the Play Store</p> <p>Thanks</p>
0
Running PowerShell from .NET Core
<p>Is there a way to run PowerShell scripts from .net-core ? </p> <p>I'm trying to run a PowerShell script in a new .net core 'website\api'. From what I can tell in order to run PowerShell on .net we need to add the</p> <p>System.Management.Automation namespace.</p> <p>This isn't possible for .net core ( or I haven't found the appropriate way to add it). There are a couple of NuGet packages which are also aimed at adding this DLL to project but those aren't compatible with .net core either. Is there a way to do this on .net core ? Here are some links I've tried but none of them are .net core specific:</p> <p><a href="http://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/" rel="noreferrer">http://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/</a></p> <p><a href="https://stackoverflow.com/questions/1186270/referencing-system-management-automation-dll-in-visual-studio">Referencing system.management.automation.dll in Visual Studio</a></p> <p><a href="https://www.nuget.org/packages/System.Management.Automation/" rel="noreferrer">https://www.nuget.org/packages/System.Management.Automation/</a></p>
0
Pandas dataframe: ValueError: num must be 1 <= num <= 0, not 1
<p>I am getting the following error while I am trying to plot a <code>pandas dataframe</code>:</p> <blockquote> <p>ValueError: num must be 1 &lt;= num &lt;= 0, not 1</p> </blockquote> <p>Code:</p> <pre><code>import matplotlib.pyplot as plt names = ['buying', 'maint', 'doors', 'persons', 'lug_boot', 'safety'] custom = pd.DataFrame(x_train) //only a portion of the csv custom.columns = names custom.hist() plt.show() </code></pre> <p>I have tried to read the file again from the <code>csv</code> and I am getting the exact same error.</p> <p>Edit:</p> <p><code>print x_train</code> output:</p> <blockquote> <p>[[0.0 0.0 0.0 0.0 0.0 0.0]</p> <p>[1.0 1.0 0.0 0.0 0.0 0.0]</p> <p>[0.0 0.0 0.0 0.0 0.0 0.0]</p> <p>..., </p> <p>[0.0 0.0 0.0 0.0 0.0 0.0]</p> <p>[0.3333333333333333 0.3333333333333333 2.0 2.0 2.0 2.0]</p> <p>[0.0 0.0 3.0 3.0 3.0 3.0]]</p> </blockquote> <p>Edit2:</p> <p>Complete list of errors(Traceback): </p> <blockquote> <p>Traceback (most recent call last):</p> <p>File "temp.py", line 104, in custom.dropna().hist()</p> <p>File "/home/kostas/anaconda2/lib/python2.7/site-packages/pandas/tools/plotting.py", line 2893, in hist_frame layout=layout)</p> <p>File "/home/kostas/anaconda2/lib/python2.7/site-packages/pandas/tools/plotting.py", line 3380, in _subplots ax0 = fig.add_subplot(nrows, ncols, 1, **subplot_kw)</p> <p>File "/home/kostas/anaconda2/lib/python2.7/site-packages/matplotlib/figure.py", line 1005, in add_subplot a = subplot_class_factory(projection_class)(self, *args, **kwargs)</p> <p>File "/home/kostas/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_subplots.py", line 64, in <strong>init</strong> maxn=rows*cols, num=num))</p> </blockquote>
0
C# conditional operator - Call method if condition is true else do nothing
<p>C# provides <a href="https://msdn.microsoft.com/en-us/library/ty67wk28.aspx" rel="nofollow">conditional operator (?:)</a> that returns one of two values depending on the value of a Boolean expression. eg</p> <p><code>condition ? first_expression : second_expression;</code></p> <p>My question is can we use the same syntax to call a method when condition is true? and when condition is false then do nothing</p> <pre><code> public void Work(int? val) { var list = new List&lt;int&gt;(); //ofcourse line below doesn't work //but is it possible to call method when condition is true and else do nothing val.HasValue? list.Add(val.value) : else do nothing } </code></pre>
0
Convert RGB array to image in C#
<p>I know the rgb value of every pixel, and how can I create the picture by these values in C#? I've seen some examples like this:</p> <pre><code>public Bitmap GetDataPicture(int w, int h, byte[] data) { Bitmap pic = new Bitmap(this.width, this.height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); Color c; for (int i = 0; i &lt; data.length; i++) { c = Color.FromArgb(data[i]); pic.SetPixel(i%w, i/w, c); } return pic; } </code></pre> <p>But it does not works. I have a two-dimensional array like this:</p> <blockquote> <p>1 3 1 2 4 1 3 ...<br/>2 3 4 2 4 1 3 ...<br/>4 3 1 2 4 1 3 ...<br/>...</p> </blockquote> <p>Each number correspond to a rgb value, for example, 1 => {244,166,89} 2=>{54,68,125}.</p>
0
Fastest way to sync two Amazon S3 buckets
<p>I have a S3 bucket with around 4 million files taking some 500GB in total. I need to sync the files to a new bucket (actually changing the name of the bucket would suffice, but as that is not possible I need to create a new bucket, move the files there, and remove the old one).</p> <p>I'm using AWS CLI's <code>s3 sync</code> command and it does the job, but takes a lot of time. I would like to reduce the time so that <strong>the dependent system downtime is minimal</strong>.</p> <p>I was trying to run the sync both from my local machine and from <code>EC2 c4.xlarge</code> instance and there isn't much difference in time taken. </p> <p>I have noticed that the time taken can be somewhat reduced when I split the job in multiple batches using <code>--exclude</code> and <code>--include</code> options and run them in parallel from separate terminal windows, i.e.</p> <pre><code>aws s3 sync s3://source-bucket s3://destination-bucket --exclude "*" --include "1?/*" aws s3 sync s3://source-bucket s3://destination-bucket --exclude "*" --include "2?/*" aws s3 sync s3://source-bucket s3://destination-bucket --exclude "*" --include "3?/*" aws s3 sync s3://source-bucket s3://destination-bucket --exclude "*" --include "4?/*" aws s3 sync s3://source-bucket s3://destination-bucket --exclude "1?/*" --exclude "2?/*" --exclude "3?/*" --exclude "4?/*" </code></pre> <p>Is there anything else I can do speed up the sync even more? Is another type of <code>EC2</code> instance more suitable for the job? Is splitting the job into multiple batches a good idea and is there something like 'optimal' number of <code>sync</code> processes that can run in parallel on the same bucket?</p> <p><strong>Update</strong></p> <p>I'm leaning towards the strategy of syncing the buckets before taking the system down, do the migration, and then sync the buckets again to copy only the small number of files that changed in the meantime. However running the same <code>sync</code> command even on buckets with no differences takes a lot of time.</p>
0
Eclipse - Empty Logcat with Android 7
<p>I recently updated my Nexus 9 Tablet to Android 7 Nougat.<br> Since then the Logcat view in Eclipse stoped displaying Logcat messages, the view just stays empty.<br> Also the devices target is shown as "Unknown". If I instead start Logcat outside Eclipse (AndroidSDK->tools->ddms) it displays all messages. However, then the "Application" Column stays empty.<br> There are allready some (older) questions on this topic here on SO, but none of the solutions here worked for me.<br> What i tryed: </p> <ul> <li>Use another USB Port</li> <li>Focus the device in the DDMS perspective</li> <li>Restart Eclipse</li> <li>Reboot the device + pc</li> <li>abd kill-server</li> <li>disable and re-enabled USB Debuging on the device</li> <li>Reset the USB-Debuging authorization and confirm the RSA fingerprint again</li> <li>Switch USB-Mode to "MTP" </li> </ul> <p>Every installed package from the Android SDK is up to date and i use latest Eclipse+ADT Plugin.<br> Also everything works fine with my Galaxy S5 Mini (Android 5.1.1).<br> I know, that the ADT-Plugin is deprecated and we should use Android Studio.<br> However I still preffer to use Eclipse as long as possible, so I am looking for a solution for this problem.<br> So does anyone know how to solve this issue?</p>
0
Unexpected value 'MyCustomModule' imported by the module 'AppModule'
<p>I am trying to migrate one of my angular2 custom library to RC.6 + Webpack. My directory structure is:</p> <pre><code>- src - source TS files - lib - transpiled JS files + definition files - dev - development app to test if it works / looks ok. - myCustomLib.js - barrel - myCustomLib.d.ts </code></pre> <p>Within <code>dev</code> folder try to run an app. I bootstrap my module:</p> <p><strong>app.module.ts</strong></p> <pre><code>import { BrowserModule } from "@angular/platform-browser"; import { NgModule } from "@angular/core"; import { AppComponent } from "./app.component"; import { MyCustomModule } from "../../myCustomLib"; @NgModule({ imports: [ BrowserModule, MyCustomModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } </code></pre> <p>Now using the webpack I bundle my dev app. </p> <p><strong>webpack.config.js</strong></p> <pre><code>module.exports = { entry: "./app/boot", output: { path: __dirname, filename: "./bundle.js", }, resolve: { extensions: ['', '.js', '.ts'], modules: [ 'node_modules' ] }, devtool: 'source-map', module: { loaders: [{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.ts$/, loader: 'awesome-typescript-loader', exclude: /node_modules/ }] }, watch: true }; </code></pre> <p>But when I try to load the app I get a message:</p> <pre><code>metadata_resolver.js:230 Uncaught Error: Unexpected value 'MyCustomModule' imported by the module 'AppModule' </code></pre> <p>My barrel file I import looks like:</p> <p><strong>myCustomLib.js</strong></p> <pre><code>export * from './lib/myCustomLib.module'; </code></pre> <p>I found also <a href="https://github.com/angular/angular-cli/issues/1831#issuecomment-242401992">hint on similar topic on github</a>, but changing it to:</p> <pre><code>export { MyCustomModule } from './lib/myCustomLib.module'; </code></pre> <p>did not help. I have also tried to import the module from <code>src</code> directory - same error. MyCustomModule should be ok as It was working fine with systemJS before.</p> <p><strong>myCustomLib.module.ts:</strong></p> <pre><code>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; @NgModule({ imports: [ BrowserModule ] }) export class MyCustomModule {} </code></pre> <p>Any idea what can be the reason of this error? I have seen similar topics here but no answer or hint helped.</p> <p><strong>Edit</strong>: To make the example even simpler I have removed all from MyCustomModule - same problem... </p>
0
Fixing a multiple warning "unknown column"
<p>I have a persistent multiple warning of "unknown column" for all types of commands (e.g., str(x) to installing updates on packages), and not sure how to debug this or fix it. </p> <p>The warning "unknown column" is clearly related to a variable in a tbl_df that I renamed, but the warning comes up in all kinds of commands seemingly unrelated to the tbl_df (e.g., installing updates on a package, str(x) where x is simply a character vector). </p>
0
How to get console inside jsfiddle
<p>How can I get the console to show in a fiddle on JSfiddle.com?</p> <p>I recently saw a fiddle that had the console embedded in the fiddle, anyone know how this can be done?</p>
0
Easy, best way to check if WebAPI is available in C# Code Behind
<p>What is the best way to check if the WebAPI is available or not? I want to check it in a simple <code>if()</code> statement, is it even possible to keep it relatively simple? if there is a better way to check. like a try/catch. just tell me. Thanks</p> <p>I want to include the if-statement in my code-behind <code>Page_Load</code> Method. So I can block the site when the API is not available. </p> <p>I tried this:</p> <pre><code>try { WebClient client = new WebClient(); client.UseDefaultCredentials = true; string response = client.DownloadString(baseuri + Constants.API_LEHRLING + lehrlingID); } catch (Exception ex) { string url = "AccessDenied.aspx"; Server.Transfer(url, true); } </code></pre> <p>I am trying to Download a string from my webapi. my uri is built automatically. if a exception happens, i refer to my Error site. </p> <p>Any other ideas? this method works, but its not very clean</p>
0
Fuzzy string matching in Python
<p>I have 2 lists of over a million names with slightly different naming conventions. The goal here it to match those records that are similar, with the logic of 95% confidence.</p> <p>I am made aware there are libraries which I can leverage on, such as the FuzzyWuzzy module in Python.</p> <p>However in terms of processing it seems it will take up too much resources having every string in 1 list to be compared to the other, which in this case seems to require 1 million multiplied by another million number of iterations.</p> <p>Are there any other more efficient methods for this problem?</p> <p>UPDATE:</p> <p>So I created a bucketing function and applied a simple normalization of removing whitespace, symbols and converting the values to lowercase etc...</p> <pre><code>for n in list(dftest['YM'].unique()): n = str(n) frame = dftest['Name'][dftest['YM'] == n] print len(frame) print n for names in tqdm(frame): closest = process.extractOne(names,frame) </code></pre> <p>By using pythons pandas, the data is loaded to smaller buckets grouped by years and then using the FuzzyWuzzy module, <code>process.extractOne</code> is used to get the best match.</p> <p>Results are still somewhat disappointing. During test the code above is used on a test data frame containing only 5 thousand names and takes up almost a whole hour.</p> <p>The test data is split up by.</p> <ul> <li>Name</li> <li>Year Month of Date of Birth</li> </ul> <p>And I am comparing them by buckets where their YMs are in the same bucket.</p> <p>Could the problem be because of the FuzzyWuzzy module I am using? Appreciate any help.</p>
0
Can't std::ostream output a const char array?
<p>For the fun and experience of it, I'm <del>modifying and</del> exploring the source code for <a href="https://sourceforge.net/projects/blobby/files/Blobby%20Volley%202%20%28Linux%29/1.0/blobby2-linux-1.0.tar.gz/download" rel="noreferrer">Blobby Volley 2 1.0</a> (Linux).</p> <p>Well... I <strong>would</strong> be modifying the source code, but I can't even get the program to compile. (Sad, isn't it?)</p> <p>Here's the code that causes the error:</p> <pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const ServerInfo&amp; val) { return stream &lt;&lt; val.name &lt;&lt; " (" &lt;&lt; val.hostname &lt;&lt; ":" &lt;&lt; val.port &lt;&lt; ")"; } </code></pre> <p>Trying to compile this with <em>g++ 5.4.0</em> gives the following (simplified output--the original output is ~443 lines) error message:</p> <blockquote> <p>error: no match for ‘operator&lt;&lt;’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘const char [32]’)</p> <p>return stream &lt;&lt; val.name &lt;&lt; " (" &lt;&lt; val.hostname &lt;&lt; ":" &lt;&lt; val.port &lt;&lt; ")";</p> </blockquote> <p>I simplified the code to this:</p> <pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const ServerInfo&amp; val) { stream &lt;&lt; "hello"; //can't get simpler than this, right? return stream; } </code></pre> <p>and got</p> <blockquote> <p>error: no match for ‘operator&lt;&lt;’ (operand types are ‘std::ostream {aka std::basic_ostream}’ and ‘const char [6]’)</p> <p>stream &lt;&lt; "hello";</p> </blockquote> <p>The code that calls it looks like this:</p> <pre><code>std::cout &lt;&lt; "duplicate server entry\n"; std::cout &lt;&lt; info &lt;&lt; "\n"; //it's called here </code></pre> <hr> <p>The thing I find most surprising is that we all know that <code>std::cout</code> and its ilk can handle <code>char</code> arrays.</p> <p>For instance,</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; int main () { const char a[6] = "hello"; std::cout &lt;&lt; a &lt;&lt; std::endl; //No problem here! return 0; } </code></pre> <p>works without a hitch.</p> <hr> <p>Oh, one more thing.</p> <p>If I include <code>&lt;string&gt;</code>, this works:</p> <pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, const ServerInfo&amp; val) { stream &lt;&lt; std::string("hello"); return stream; } </code></pre> <hr> <p>Does anyone know what I'm missing?</p> <hr> <p><strong>PS:</strong> Here's a <a href="http://pastebin.com/UYPHqspD" rel="noreferrer">pastebin of the errors.</a></p> <p><strong>PPS:</strong> Here's the headers that were requested:</p> <pre><code>/* header include */ #include "NetworkMessage.h" /* includes */ #include &lt;cstring&gt; #include "UserConfig.h" #include "SpeedController.h" </code></pre> <p><strong><em>PPS:</em></strong> If you are wondering why I didn't get an error about <code>std::ostream</code> not being defined, check the 3rd paragraph of Sam's answer.</p>
0
Python os.environ throws key error?
<p>I'm accessing an environment variable in a script with <code>os.environ.get</code> and it's throwing a <code>KeyError</code>. It doesn't throw the error from the Python prompt. This is running on OS X 10.11.6, and is Python 2.7.10.</p> <p>What is going on?</p> <pre><code>$ python score.py Traceback (most recent call last): File "score.py", line 4, in &lt;module&gt; setup_logging() File "/score/log.py", line 29, in setup_logging config = get_config() File "/score/log.py", line 11, in get_config environment = os.environ.get('NODE_ENV') File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/UserDict.py", line 23, in __getitem__ raise KeyError(key) KeyError: 'NODE_ENV' $ python -c "import os; os.environ.get('NODE_ENV')" $ </code></pre> <p><strong>As requested, here's the source code for <code>score.py</code></strong></p> <pre><code>from __future__ import print_function from log import get_logger, setup_logging setup_logging() log = get_logger('score') </code></pre> <p><strong>And here's <code>log.py</code></strong></p> <pre><code>import json import os import sys from iron_worker import IronWorker from logbook import Logger, Processor, NestedSetup, StderrHandler, SyslogHandler IRON_IO_TASK_ID = IronWorker.task_id() def get_config(): environment = os.environ.get('NODE_ENV') if environment == 'production': filename = '../config/config-production.json' elif environment == 'integration': filename = '../config/config-integration.json' else: filename = '../config/config-dev.json' with open(filename) as f: return json.load(f) def setup_logging(): # This defines a remote Syslog handler # This will include the TASK ID, if defined app_name = 'scoreworker' if IRON_IO_TASK_ID: app_name += '-' + IRON_IO_TASK_ID config = get_config() default_log_handler = NestedSetup([ StderrHandler(), SyslogHandler( app_name, address = (config['host'], config['port']), level = 'ERROR', bubble = True ) ]) default_log_handler.push_application() def get_logger(name): return Logger(name) </code></pre>
0
Can a line of Python code know its indentation nesting level?
<p>From something like this:</p> <pre><code>print(get_indentation_level()) print(get_indentation_level()) print(get_indentation_level()) </code></pre> <p>I would like to get something like this:</p> <pre><code>1 2 3 </code></pre> <p>Can the code read itself in this way?</p> <p>All I want is the output from the more nested parts of the code to be more nested. In the same way that this makes code easier to read, it would make the output easier to read. </p> <p>Of course I could implement this manually, using e.g. <code>.format()</code>, but what I had in mind was a custom print function which would <code>print(i*' ' + string)</code> where <code>i</code> is the indentation level. This would be a quick way to make readable output on my terminal. </p> <p>Is there a better way to do this which avoids painstaking manual formatting?</p>
0
Enable SSL in Visual Studio
<p>I have enabled SSL in Visual Studio as shown below:</p> <p><a href="https://i.stack.imgur.com/x6Qx3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/x6Qx3.png" alt="enter image description here"></a></p> <p>I have also set the below:</p> <p><a href="https://i.stack.imgur.com/3w6VH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3w6VH.png" alt="enter image description here"></a></p> <p>When I access the website via IE (via Visual Studio debugging) I see this:</p> <p><a href="https://i.stack.imgur.com/gmipq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gmipq.png" alt="enter image description here"></a></p> <p>When I access the website via Firefox (via Visual Studio debugging) I see this:</p> <p><a href="https://i.stack.imgur.com/BMZIP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BMZIP.png" alt="enter image description here"></a></p> <p>There is no option to progress to the website in either Firefox or IE. I have spent all day trying to understand what is wrong. What am I doing wrong?</p>
0
Java thread executing remainder operation in a loop blocks all other threads
<p>The following code snippet executes two threads, one is a simple timer logging every second, the second is an infinite loop that executes a remainder operation:</p> <pre><code>public class TestBlockingThread { private static final Logger LOGGER = LoggerFactory.getLogger(TestBlockingThread.class); public static final void main(String[] args) throws InterruptedException { Runnable task = () -&gt; { int i = 0; while (true) { i++; if (i != 0) { boolean b = 1 % i == 0; } } }; new Thread(new LogTimer()).start(); Thread.sleep(2000); new Thread(task).start(); } public static class LogTimer implements Runnable { @Override public void run() { while (true) { long start = System.currentTimeMillis(); try { Thread.sleep(1000); } catch (InterruptedException e) { // do nothing } LOGGER.info("timeElapsed={}", System.currentTimeMillis() - start); } } } } </code></pre> <p>This gives the following result:</p> <pre><code>[Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1004 [Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1003 [Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=13331 [Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1006 [Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1003 [Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1004 [Thread-0] INFO c.m.c.concurrent.TestBlockingThread - timeElapsed=1004 </code></pre> <p>I don't understand why the infinite task blocks all other threads for 13.3 seconds. I tried to change thread priorities and other settings, nothing worked.</p> <p>If you have any suggestions to fix this (including tweaking OS context switching settings) please let me know. </p>
0