Id
int64
34.6M
60.5M
Title
stringlengths
15
150
Body
stringlengths
33
36.7k
Tags
stringlengths
3
112
CreationDate
stringdate
2016-01-01 00:21:59
2020-02-29 17:55:56
Y
stringclasses
3 values
39,174,178
Restart Python Program within and If statement - not complex
<pre><code>Question1 = input("We will start off simple, what is your name?") if len(Question1) &gt; 0 and Question1.isalpha(): #checks if the user input contains characters and is in the alphabet, not numbers. Question2 = input("Ah! Lovely name, %s. Not surprised you get all the women, or is it men?" % Question1) if Question2.lower() in m: #checks if the user input is in the variable m print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2)) elif Question2.lower() in w: # checks if the user input is in the variable w print ("So, your name is %s and you enjoy the pleasure of %s! I bet you didnt see that coming." % (Question1, Question2)) else: #if neither of the statements are true (incorrect answer) print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!") else: print ("Come on, enter your accurate information before proceeding! Restart me!") #if the first question is entered wrong (not a name) Question3 = input("Now I know your name and what gender attracts you. One more question and I will know everything about you... Shall we continue?") </code></pre> <p>In order to get the right answer, I will first tell you what happens when I run it: There are several scenarios but I will walk you through 2. When I run the program I am first asked what my name is, I can enter anything here that is alphabetic, then it asks me if I like men or woman, weird I know but it's a project I am working on, if I were to say 'men' or 'women' the program runs perfectly, but if I were to enter say... 'dogs' it would follow the else statement <code>print ("Come on! You're helpless. I asked you a simple question with 2 very destinctive answers. Restart!")</code> but then it continues the code and goes to the last line shown above "Now I know your name and what gender attract you...... blah blah". <strong>What I am trying to do is have it restart the script if you were to enter anything other than 'men' or 'women'.</strong> I was told that a while statement would work, but I would need an explanation as to why and how... I'm new to Python in a sense.</p>
<python>
2016-08-26 20:26:28
LQ_CLOSE
39,174,188
Is it possible to store the value from a populated dropdown list in HTML/php and store it again into another table?
I have 7 populated dropdown lists and I want it's values to be stored again into another table is even possible. How do I do it?
<php><html>
2016-08-26 20:27:35
LQ_EDIT
39,174,382
Windows x86 assembly language syntax
<p>(1) What does the following code mean? I cannot find any reference about the ds:[ ] syntax anywhere online. How is it different from without the ds:?</p> <pre><code>cmp eax,dword ptr ds:[12B656Ch] </code></pre> <p>(2) In the following instruction,</p> <pre><code>movsx eax,word ptr [esi+24h] </code></pre> <p>What is the esi register used for? Is it possible to guess what the original C code is doing from using such a rare register?</p>
<windows><assembly><x86>
2016-08-26 20:44:06
LQ_CLOSE
39,174,399
Why is it not detecting a capital letter in php
<p>this is someone else's code and seems to work for everyone online but me. It doesn't seem to detect the capital letters even though i have dedicated code for it. </p> <p>Could someone spot the error in my code:</p> <pre><code>&lt;?php if($_POST['submit']){ if(!$_POST['email']) $error.="&lt;br /&gt;Please enter your email"; else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) $error.="&lt;br /&gt;Please enter a valid mail"; if(!$_POST['password']) $error.="&lt;br /&gt;Please enter your password"; else { if(strlen($_POST['password'])&lt;8) $error.="&lt;br /&gt;Please enter a password with atleast 8 characters"; if(!preg_match('/[A-Z]/', $_post['password'])) $error.="&lt;br /&gt;Please enter atleast one capital letter"; } if($error) echo "There were error(s) in your details:".$error; } ?&gt; &lt;form method="post"&gt; &lt;input type="email" name="email" id="email" /&gt; &lt;input type="password" name="password" /&gt; &lt;input type="submit" name="submit" value="signup" /&gt; &lt;/form&gt; </code></pre> <p>Here is the link to it: </p> <p><a href="http://hassannasir.co.uk/mysql/" rel="nofollow">http://hassannasir.co.uk/mysql/</a></p>
<php><html><mysql><css>
2016-08-26 20:45:36
LQ_CLOSE
39,174,932
How do I code a program that will create drop down lists from input and populate columns in another sheet with drop downs
<p>I am new to VBA and currently know how to create Macros using the "Record Macro" option. I need to code something that does multiple steps in VBA.</p> <p>I will have an unknown number of columns that I need the program to go through and check if the second row has a value in it.(These columns and rows will be input from a user so the number of columns or entries per row is unknown). </p> <p>The values under each column are the possible categories a user will later choose from for that specific variable. So in Sheet 1 there is a variable "Sex" there will be one row under it saying "female" and another row under that saying "male". These have to be made into a drop down list and pasted under another sheet (Sheet2) in which the same column names (Sex) will now have drop downs under them.</p> <p>Steps to take: </p> <p>1) IF Column(i)'s Row 2 is not empty</p> <p>2) Then define all rows below it as a list and make a drop down of this list</p> <p>3) Then paste this drop down under a column that matches the name of the Column(i) in another sheet</p> <h1>SHEET 1 (what i have)</h1> <pre><code>Age | Sex | Race | Height ------------------------------------ [EMPTY] |Female |Asian |[EMPTY] [EMPTY] |Male |Black |[EMPTY] [EMPTY] |[EMPTY] |Hispanic|[EMPTY] [EMPTY] |[EMPTY] |Native A|[EMPTY] [EMPTY] |[EMPTY] |White |[EMPTY] [EMPTY] |[EMPTY] |Other |[EMPTY] </code></pre> <hr> <h1>SHEET 2 (what I want)</h1> <pre><code>AGE | Sex | Race | Height ------------------------------------------------------------ [EMPTY] | [dropdown of sex] | [dropdown of race] |[EMPTY] </code></pre>
<vba><excel>
2016-08-26 21:35:53
LQ_CLOSE
39,175,016
How to turn off SonarLint automatic triggering on IntelliJ IDEA
<p>Is there some way of turning-off automatic SonarLint analysis in Intellij IDEA?</p> <p>I have some 10,000 to 20,000 lines-of-code classes (don't ask, not my fault, trying to refactor). Every time I edit even a single character in the class, the SonarLint plugin makes IDEA unusable for a few minutes.</p> <p>It is not possible to save the "Automatically trigger analysis" checkbox in the unchecked state in Other Settings > SonarLint General Settings. Is there some other solution to my problem? I really want to use the plugin. I just can't use it in automatic mode.</p>
<intellij-idea><sonarlint><sonarlint-intellij>
2016-08-26 21:44:40
HQ
39,175,252
Can't call Auth::user() on controller's constructor
<p>I'm trying to check if the user has permission to a certain model. Up until now (with Laravel 5.2), I added this code at the constructor:</p> <pre><code>public function __construct() { if (!Auth::user()-&gt;hasPermission('usergroups')) { abort(404); } } </code></pre> <p>Now, after upgrading to Laravel 5.3, <code>Auth::user()</code> returns <code>null</code> when being called from the controller's constructor. If I call it within any other method of the class, it returns the currently logged in user.</p> <p>Any Ideas why?</p>
<laravel><laravel-5.3>
2016-08-26 22:06:31
HQ
39,176,018
cannot update identity column in Entity Framework Core
<p>I've added a separate Identification to the AspNetUsers table called NumericId that will serve along with the GUID like ID that ASP has for default.</p> <p>I've added the property as an additional property of the ApplicationUser class:</p> <pre><code>public class ApplicationUser : IdentityUser { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public virtual int NumericId { get; set; } } </code></pre> <p>However, when I try to register, or update the user's details (that aren't even relevant to the numericId) I keep getting the error </p> <pre><code>SqlException: Cannot update identity column 'NumericId'. </code></pre> <p>which prevents any changes and in the end does not update the user (but it does register one, and Numeric Id is properly assigned on that part. But this is irrelevant)</p>
<asp.net-core-mvc><entity-framework-core>
2016-08-26 23:42:17
HQ
39,176,121
Random forest for important predictor variables
<p>In my data set I've 19 predictor variables which include both categorical and continuous variables. I want to fit a random forest model using only <strong>important predictor variables</strong> (not all the predictor variables) and also I've to repeat the process 100 times.How can I do this by using R? Any suggestions please?</p>
<r><random-forest>
2016-08-26 23:54:33
LQ_CLOSE
39,176,237
How do I store JWT and send them with every request using react
<p>So happy right know because I got my basic registration/authentication system going on.</p> <p>so basically I got this :</p> <pre><code>app.post('/login', function(req,res) { Users.findOne({ email: req.body.email }, function(err, user) { if(err) throw err; if(!user) { res.send({success: false, message: 'Authentication Failed, User not found.'}); } else { //Check passwords checkingPassword(req.body.password, user.password, function(err, isMatch) { if(isMatch &amp;&amp; !err) { //Create token var token = jwt.sign(user,db.secret, { expiresIn: 1008000 }); res.json({success: true, jwtToken: "JWT "+token}); } else { res.json({success: false, message: 'Authentication failed, wrong password buddy'}); } }); } }); }); </code></pre> <p>Then I secure my /admin routes and with POSTMAN whenever I send a get request with the jwt in the header everything works perfectly.</p> <p>Now here is the tricky part, basically When i'm going to login if this a sucess then redirect me to the admin page, and everytime I try to access admin/* routes I want to send to the server my jwToken but the problem is, how do I achieve that ? I'm not using redux/flux, just using react/react-router.</p> <p>I don't know how the mechanic works.</p> <p>Thanks guys</p>
<express><reactjs><passport.js><react-router><jwt>
2016-08-27 00:12:15
HQ
39,176,248
React.js - Can't read property of undefined
<p>I'm making very simple react app. Yet as I try to invoke method of parent (actually grandparent) component via onChange event, I keep getting <code>Uncaught TypeError: Cannot read property 'props' of undefined</code>.</p> <p>Here is the component/form that is triggering the event (thus invoking method on binded parent component... Yes I used .bound(this) on the method as I passed it down from parent component via props.).</p> <pre><code>class MonthsTable extends Component { handleChangeOnMonth(e){ this.props.setMonth(e.target.id, e.target.value); // here the method is not found, causing error. } render(){ console.log(this.props.setMonth) // here the method is present alright return (&lt;form&gt; {this.props.months.map((e, i) =&gt; &lt;input type='number' id={i} key={i} // yes I know, bad habit, but in this case it doesn't matter value={this.props.months[i]} onChange={this.handleChangeOnMonth} /&gt;)} &lt;/form&gt;) } } </code></pre> <p>Here is how I pass the method as props from most parent (grandparent) component.</p> <pre><code>&lt;Months setMonth={this.setMonth.bind(this)} /&gt; </code></pre> <p>Here is how I pass the method as props in the parent (the component that is between method owner and method invoker)</p> <pre><code>&lt;MonthsTable setMonth={this.props.setMonth} /&gt; </code></pre> <p>And finally passed to component (MonthsTable) that you saw first. Wheter it is relevant or not, final (most child) components is displayed depending of if statement which works just fine (Might somehow be relevant, I don't know).</p> <p>Question is... Why is the (setMonth) method 'invisible' inside of (handleChangeOnMonth) method.</p> <p>Thanks for any advice. </p>
<javascript><reactjs>
2016-08-27 00:14:01
HQ
39,176,623
How to delete Github's wiki homepage?
<p>Today I put my password to Github's wiki <code>Home</code> page. Then, I know it's a mistake. </p> <p>How to remove this page? (I can remove child page, but I don't know how to delete wiki <code>Home</code> page)</p>
<github>
2016-08-27 01:27:42
HQ
39,176,692
The wait operation timed out. ASP
<p>I created an internal website for our company. It run smoothly for several months and then I made a major update due to user suggestion. When I run in live, it run normally. Then suddenly one of my user from japan sending me an "The Wait operation timed out." error. When I check access that certain link, It run normally for me and some other who I ask to check if they access that page. I already update the httpRuntime executionTimeout but still no luck. Is it the error come from database connection? If I increase the timeout in the database connection it will be fix the problem? </p>
<sql><asp.net><connection>
2016-08-27 01:44:38
HQ
39,177,136
Deploy path doesn't work for Git Deploy Method in middleman-deploy
<p>I am using <a href="https://github.com/middleman/middleman-blog" rel="noreferrer">middleman-blog</a> and <a href="https://github.com/middleman-contrib/middleman-deploy" rel="noreferrer">middleman-deploy</a>.</p> <p>What I would like to do, is within the branch I am deploying to, I want the static files to be deployed to a subfolder within the repo (i.e. not the root folder).</p> <p>I tried doing this in my <code>config.rb</code>:</p> <pre><code>activate :deploy do |deploy| deploy.build_before = true deploy.deploy_method = :git deploy.branch = 'gh-pages-2' deploy.remote = 'github' deploy.path = 'blog' end </code></pre> <p>But that doesn't work, it still deploys to the root directory. In fact, it doesn't even create the <code>/blog</code> folder I am looking for.</p> <p>When I visit the config settings locally, these are the settings I see under <code>:deploy</code>:</p> <pre><code>:deploy :branch = "gh-pages" :build_before = true :clean = false :commit_message = nil :deploy_method = :git :flags = nil :host = nil :password = nil :path = "blog" :port = 22 :remote = "github" :strategy = :force_push :user = nil </code></pre> <p>This indicates to me that the path attribute is being set correctly.</p> <p>I also tried doing <code>deploy.path = '/blog'</code> and that still doesn't work.</p> <p>So how can I get this to deploy to <code>\blog\</code> subfolder within my repo rather than the root directory?</p> <p>The versions of the different gems are as follows:</p> <pre><code>middleman (4.1.10) middleman-blog (4.0.1) middleman-cli (4.1.10) middleman-deploy (2.0.0.pre.alpha) </code></pre> <p><strong>Note:</strong> I am purposely using <code>gh-pages-2</code> because I don't want to overwrite my current <code>gh-pages</code> without being certain that it will deploy to the correct subfolder.</p>
<ruby><git><deployment><middleman>
2016-08-27 03:22:51
HQ
39,177,353
LDAP Authentication with a service account in Java
<p>I am trying to authenticate users from LDAP with a service account created. Im getting below error on <strong>ctx = new InitialDirContext(env);</strong></p> <blockquote> <p>[LDAP: error code 49 - 8009030C: LdapErr: DSID-0C0903A8, comment: AcceptSecurityContext error, data 2030, v1db1</p> </blockquote> <p><strong><em>Can someone help me to understand where am I going wrong ?</em></strong></p> <p>This is my java file</p> <pre><code>/** * */ package com.dei; import java.util.Hashtable; import javax.naming.AuthenticationException; import javax.naming.Context; import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.SizeLimitExceededException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; public class LdapConnector { private static final String LDAP_SERVER_PORT = "389"; private static final String LDAP_SERVER = "server"; private static final String LDAP_BASE_DN = "OU=role,OU=roles,OU=de,OU=apps,DC=meta,DC=company,DC=com"; private static final String LDAP_BIND_DN = "cn=service_account";//service account userid provided by LDAP team private static final String LDAP_BIND_PASSWORD = "password";///service account pwd provided by LDAP team public Boolean validateLogin(String userName, String userPassword) { Hashtable&lt;String, String&gt; env = new Hashtable&lt;String, String&gt;(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://" + LDAP_SERVER + ":" + LDAP_SERVER_PORT + "/" + LDAP_BASE_DN); // To get rid of the PartialResultException when using Active Directory env.put(Context.REFERRAL, "follow"); // Needed for the Bind (User Authorized to Query the LDAP server) env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, LDAP_BIND_DN); env.put(Context.SECURITY_CREDENTIALS, LDAP_BIND_PASSWORD); DirContext ctx; try { ctx = new InitialDirContext(env); } catch (NamingException e) { throw new RuntimeException(e); } NamingEnumeration&lt;SearchResult&gt; results = null; try { SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search Entire Subtree controls.setCountLimit(1); //Sets the maximum number of entries to be returned as a result of the search controls.setTimeLimit(5000); // Sets the time limit of these SearchControls in milliseconds String searchString = "(&amp;(objectCategory=user)(sAMAccountName=" + userName + "))"; results = ctx.search("", searchString, controls); if (results.hasMore()) { SearchResult result = (SearchResult) results.next(); Attributes attrs = result.getAttributes(); Attribute dnAttr = attrs.get("distinguishedName"); String dn = (String) dnAttr.get(); // User Exists, Validate the Password env.put(Context.SECURITY_PRINCIPAL, dn); env.put(Context.SECURITY_CREDENTIALS, userPassword); new InitialDirContext(env); // Exception will be thrown on Invalid case System.out.println("Login successful"); return true; } else return false; } catch (AuthenticationException e) { // Invalid Login System.out.println("Login failed" +e.getMessage()); return false; } catch (NameNotFoundException e) { // The base context was not found. System.out.println("Login failed" +e.getMessage()); return false; } catch (SizeLimitExceededException e) { throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e); } catch (NamingException e) { throw new RuntimeException(e); } finally { if (results != null) { try { results.close(); } catch (Exception e) { /* Do Nothing */ } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { /* Do Nothing */ } } } } } </code></pre>
<java><authentication><ldap>
2016-08-27 04:07:13
HQ
39,177,715
How does one make programs with string equality in Python?
<p>Obviously, I've just started trying to make some random programs, and do not know much. A program I have tried to write is the following:</p> <pre><code>print('Please print your name') myName = input() if myName == 'No' print('Fine, be that way') </code></pre> <p>There is an error in the third line, and am not really sure why. How would I correct this?</p>
<python>
2016-08-27 05:16:09
LQ_CLOSE
39,178,169
When using JavaScript's reduce, how do I skip an iteration?
<p>I am trying to figure out a way to conditionally break out of an iteration when using JavaScript's <code>reduce</code> function. </p> <p>Given the following code sums an array of integers and will return the number <code>10</code>: </p> <pre><code>[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { return previousValue + currentValue; }); </code></pre> <p>How can I do something like this: </p> <pre><code>[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, currentIndex, array) { if(currentValue === "WHATEVER") { // SKIP or NEXT -- don't include it in the sum } return previousValue + currentValue; }); </code></pre>
<javascript>
2016-08-27 06:27:26
HQ
39,178,288
Why don't complex-number literals work in clang?
<p>When I run this code <a href="https://ideone.com/HdviA2">on ideone.com</a>, it prints <code>(2,3)</code>:</p> <pre><code>#include &lt;iostream&gt; #include &lt;complex&gt; int main() { std::complex&lt;double&gt; val = 2 + 3i; std::cout &lt;&lt; val &lt;&lt; std::endl; return 0; } </code></pre> <p>But when I use clang on macOS 10.11.6, I get no errors or warnings, but the output is <code>(2,0)</code>:</p> <pre class="lang-none prettyprint-override"><code>$ clang --version Apple LLVM version 7.3.0 (clang-703.0.31) Target: x86_64-apple-darwin15.6.0 $ clang -lc++ test.cpp &amp;&amp; ./a.out (2,0) </code></pre> <p>What happened to the imaginary part? Am I doing something wrong?</p>
<c++><c++11><clang><complex-numbers><user-defined-literals>
2016-08-27 06:45:20
HQ
39,178,294
Phyton 3.5 "for loop" "enumerate()” Select Word from List
Hi I'm new here I've just started learning python Individual words in wordList will be referred to as “word” as a variable. who would I set this up this for a python english grammar gen program by the way. also I wanna try to Enter a loop that repeats once for each word in wordList. Trying to use a for loop with “enumerate()” function but I keep getting stuck. Any help would be great. print('Welcome to my English Test App') # Import the random module to allow us to select the word list and questions at random. import random candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', 'DUCK', 'PIGEON', 'POSTER', 'TELEVISION', 'SPY', 'RHYTHM', 'SUBSTANTIAL', 'SNOW', 'MAGNET', 'TOWEL', 'WALKING', 'SPEAKER', 'UNCHARACTERISTICALLY'] print (random.sample (candidateWords, 5)) # This function receives a word as a parameter and should return the number of vowels in the word. def countVowels(word): pass #
<python><python-3.x><for-loop><enumerate>
2016-08-27 06:45:53
LQ_EDIT
39,178,631
I'm usingto use google maps and need to get natural feature like ocean, sea etc from location in android
I am trying to get name of oceans from location using this- https://maps.googleapis.com/maps/api/geocode/json?latlng=0,0&result_type=natural_feature&key=AIzaSyBZ1dxaR_eFtP4LYS8Ky9x4hHdVYf6456Y But not found. Please help me to find out this. Thanks in advance
<android><google-maps>
2016-08-27 07:31:11
LQ_EDIT
39,178,785
How can I use java Integer.Intparse()?
I was trying to change like String A00001 to int 1 in this code.but Eclipse told me that --- Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "00001 " at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at LibraryManager.BookAdd.getInsertOrderedList(BookAdd.java:105) while(rs1.next()){ allid[i]=rs1.getString("id"); String mystr=allid[i].substring(1); try{ System.out.println(mystr);//this print 00001 intofid[i]=Integer.parseInt(mystr); }catch(Exception e){ e.printStackTrace(); } i++; } <!-- end snippet --> how could I resolved this??
<java>
2016-08-27 07:50:42
LQ_EDIT
39,179,068
How can I control my website's inputs when they are entered by users?
<p>I have a question and answer website like SO. I have some limitations on some of facilities. For example an user cannot vote who has less than 20 reputation. Or an user cannot close a question until earning at least 200 reputation.</p> <p>Ok well, there is also somethings which don't have any limitation, like writing an answer for questions. In this case, <strong>a bad user</strong> can write multiple irrelevant answers for multiple questions and makes my database huge with useless information.</p> <p>So I guess I need to check something before inserting a new answer, Am I right? Or anyway, how can I manage my website's inputs? As I mentioned, in my current algorithm, a bad user <em>(like a spammer or hacker)</em> can simply enter lots of useless data in my database, and then maybe I understand it after 1 day <em>(which is too late)</em> which in this case, it takes some times to block him and remove all his data.</p> <p>In conclusion, I like to know, <em>(for example)</em>, how a website like SO handle that? Do I need a separated query before inserting a new answer for checking? Or what? </p> <p><strong>Note:</strong> I use PHP <em>(for server-side codes)</em> and MySQL <em>(for database codes)</em>.</p>
<php><mysql><database><algorithm><security>
2016-08-27 08:27:39
LQ_CLOSE
39,179,592
Luigi LocalTarget binary file
<p>I am having troubles to write a binary <code>LocalTarget</code> in a Luigi pipeline in my project. I isolated the problem here:</p> <pre><code>class LuigiTest(luigi.Task): def output(self): return luigi.LocalTarget('test.npz') def run(self): with self.output().open('wb') as fout: np.savez_compressed(fout, array=np.asarray([1, 2, 3])) </code></pre> <p>I tried opening as <code>'w'</code> and <code>'wb'</code> but I keep getting the following error:</p> <pre><code>TypeError: write() argument must be str, not bytes </code></pre> <p>I am using python 3.5.1 and my version of luigi is 2.1.1</p>
<python-3.x><luigi>
2016-08-27 09:33:48
HQ
39,179,863
Is this Quicksort correct?
<p>I changed the pivot to be the first element in the array, will this Quicksort algorithm still be ok? and will the variable "l" in the data array be the first element in all the partitioning steps?</p> <p>x = data[l] // pivot</p> <p>thanks</p> <pre><code> public void QuickSort(int[] data) { QuickSort(data, 0, data.Length - 1); } private void QuickSort(int[] data, int l, int r) { int i, j; int x; i = l; j = r; x = data[l]; while (true) { while (data[i] &lt; x) { i++; } while (data[j] &gt; x) { j--; } if (l &lt;= j) { int temporary = data[i]; data[i] = data[j]; data[j] = temporary; i++; j--; } if (i &gt; j) { break; } } if (l &lt; j) { QuickSort(data, l, j); } if (i &lt; r) { QuickSort(data, i, r); } } </code></pre>
<c#><quicksort>
2016-08-27 10:05:48
LQ_CLOSE
39,180,032
int[] from String or int[] from char[]
<p>what i want to do is take a String of numbers like "8675309" and then do some math based on different digits from the String. i'd be happy to get 8, 6, 7, 5, 3, 0, 9 and then using the indexes, but they seem to give weird numbers (like 51) so far. i simply want to wind up doing myArray[0] + myArray[3] = output (this example would be 8+5=13)</p> <p>i own 6 books on Java and none of them cover this. 6+ hours on the web (google, stackoverflow, youtube, others) and nowhere can i find this. - no matter how i search i get results of everything but.</p> <p>from arrays which are already populated, to strings already delimited, to discarding everything but numbers from a string, etc...</p> <p>i tried using/modifying what i've found and the best i can come up with has eclipse yelling at me that it's not possible to convert a char to an int.</p> <pre><code> String str = cn; char[] charArray = str.toCharArray(); String number = String.valueOf(cn); int[] digits1 = number.toCharArray(); int newInt = charArray[0]; System.out.println(newInt); </code></pre> <p><em>"Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from char[] to int[]"</em></p>
<java><arrays><string><char><int>
2016-08-27 10:22:35
LQ_CLOSE
39,181,600
Find all n-dimensional lines and diagonals with NumPy
<p>Using NumPy, I would like to produce a list of all lines and diagonals of an n-dimensional array with lengths of k.</p> <hr> <p>Take the case of the following three-dimensional array with lengths of three.</p> <pre><code>array([[[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8]], [[ 9, 10, 11], [12, 13, 14], [15, 16, 17]], [[18, 19, 20], [21, 22, 23], [24, 25, 26]]]) </code></pre> <p>For this case, I would like to obtain all of the following types of sequences. For any given case, I would like to obtain all of the possible sequences of each type. Examples of desired sequences are given in parentheses below, for each case.</p> <ul> <li>1D lines <ul> <li>x axis (<code>0, 1, 2</code>)</li> <li>y axis (<code>0, 3, 6</code>)</li> <li>z axis (<code>0, 9, 18</code>)</li> </ul></li> <li>2D diagonals <ul> <li>x/y axes (<code>0, 4, 8</code>, <code>2, 4, 6</code>)</li> <li>x/z axes (<code>0, 10, 20</code>, <code>2, 10, 18</code>)</li> <li>y/z axes (<code>0, 12, 24</code>, <code>6, 12, 18</code>)</li> </ul></li> <li>3D diagonals <ul> <li>x/y/z axes (<code>0, 13, 26</code>, <code>2, 13, 24</code>)</li> </ul></li> </ul> <hr> <p>The solution should be generalized, so that it will generate all lines and diagonals for an array, regardless of the array's number of dimensions or length (which is constant across all dimensions).</p>
<python><arrays><numpy><diagonal><n-dimensional>
2016-08-27 13:20:07
HQ
39,182,583
Debug and Finding error in Bean Shell in Andriod
I'm using paw server and bean shell scripting in html which return the data in json form somehow i cant get any data from the script and I am not able to debug the script . Here is the code <bsh> import android.net.Uri; import android.provider.Contacts.People; import android.provider.Contacts.Phones; import java.text.DateFormat; service = server.props.get("serviceContext"); delete = parameters.get("delete"); SMS_CONTENT_URI = Uri.parse("content://sms"); // ArrayList for thread information listThreads = new ArrayList(); URI = Uri.parse("content://sms"); // --- Thread IDs cur = service.getContentResolver().query(URI, new String[] {"DISTINCT thread_id"}, null, null, "date DESC"); threadIDs = new ArrayList(); if(cur.moveToFirst()) { do { threadIDs.add(cur.getInt(0)); } while(cur.moveToNext()); } cur.close(); print("["); //--- Get infos Integer it = 0; for(id : threadIDs) { // ArrayList for this thread information listThreadInfo = new ArrayList(); /* List content 0: Thread ID (int) 1: Address (String) 2: Name (might be null) (String) 3: Contact ID (might be 0) (int) 4: Date (Date) 5: Messages in Thread (int) 6: Body (String) 7: Unread messages (int) */ // -- Messages in thread cur = service.getContentResolver().query(URI, new String[] { "COUNT(thread_id)" }, "thread_id=?", new String[] { "" + id }, null); cur.moveToFirst(); count = cur.getInt(0); cur.close(); // -- Unread messages cur = service.getContentResolver().query(URI, new String[] { "COUNT(read)" }, "thread_id=? AND read == 0", new String[] { "" + id }, null); cur.moveToFirst(); unread = cur.getInt(0); cur.close(); cur = service.getContentResolver().query(URI, null, "thread_id=?", new String[] { "" + id }, "date DESC LIMIT 1"); if(cur.moveToFirst()) { do { contactId = cur.getInt(cur.getColumnIndex("person")); address = cur.getString(cur.getColumnIndex("address")); date = new Date(cur.getLong(cur.getColumnIndex("date"))); body = cur.getString(cur.getColumnIndex("body")); // Only if address != null. Otherwise it's a DRAFT if(address != null) { name = null; phones = service.getContentResolver().query( android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] { android.provider.ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID }, android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER + "=?", new String[] { address }, null ); if(phones.moveToFirst()) { contactId = phones.getInt(0); } phones.close(); if(contactId != 0) { contact = service.getContentResolver().query( android.provider.ContactsContract.Data.CONTENT_URI, new String[]{android.provider.ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME }, android.provider.ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + android.provider.ContactsContract.CommonDataKinds.StructuredName.MIMETYPE + "=?", new String[] { "" + contactId, android.provider.ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, null ); if(contact.moveToFirst()) { name = contact.getString(0); } contact.close(); } listThreadInfo.add(0, id); listThreadInfo.add(1, address); listThreadInfo.add(2, name); listThreadInfo.add(3, contactId); listThreadInfo.add(4, date); listThreadInfo.add(5, count); listThreadInfo.add(6, body); listThreadInfo.add(7, unread); body = body.replace("\n", "<br>").replace("\t", " ").replace("\"", "\\\""); print("{"); print("\t\"id\" : " + id + ","); print("\t\"addr\" : \"" + address + "\","); print("\t\"name\" : \"" + name + "\","); print("\t\"contactId\" : " + contactId+ ","); print("\t\"date\" : " + date.getTime() + ","); print("\t\"count\" : " + count + ","); print("\t\"body\" : \"" + body + "\","); print("\t\"img\" : \"graphics/seeContactImg.xhtml?contactId=" + contactId + "\","); print("\t\"unread\" : " + unread); print("}"); it++; if(it < threadIDs.size()) { print(","); } listThreads.add(listThreadInfo); } } while(cur.moveToNext()); } cur.close(); } print("]"); </bsh> The following code return sms in json form .There is something wrong in it but Im not able to debug because it is written in .xhtml form
<android><json><beanshell><pawserver>
2016-08-27 15:08:55
LQ_EDIT
39,182,633
Spring Boot @EnableScheduling conditionally
<p>Is there a way to make @EnableScheduling conditional based on an application property? also is it possible to disable controllers based on properties too?</p> <p>What I'm trying to achieve is to have the same spring boot application used to serve web requests (but not run scheduled tasks on the same machine), and also install the same app on backend servers to run only scheduled tasks.</p> <p>My app looks like this</p> <pre><code>@SpringBootApplication @EnableScheduling @EnableTransactionManagement public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } </code></pre> <p>And a sample scheduled job looks like this</p> <pre><code>@Component public class MyTask { @Scheduled(fixedRate = 60000) public void doSomeBackendJob() { /* job implementation here */ } } </code></pre>
<java><spring-boot>
2016-08-27 15:13:21
HQ
39,182,890
What is Synchronous and asynchronous in android?
<p>I want to know the definition and meaning of word Synchronous and Asynchronous.Can any one explain me these topics I will be really appreciate.</p>
<android>
2016-08-27 15:41:03
LQ_CLOSE
39,182,907
How to show object values in html persistently.
Let suppose I am having an object like y={1,2,3}.I want to display its value using angular in html. So what I did is: for(var i=0;i<y.length;i++){ $scope.data=y[i]; //transferring } and in my html it is written: <html> {{data}} </html> Now I know that it is showing the last value(3) because the data value is updated at the end and since the last value of the loop is 3 it sets the 3 in html.So my question is how can we fix this problem?
<javascript><html><angularjs>
2016-08-27 15:43:26
LQ_EDIT
39,183,133
Evaluation of method in Watch window cannot be called in this context
<p>I'm trying to see the <code>DateTimeOffset</code> values of some objects in a collection in the Watch window. So I typed:</p> <pre><code>collection.Select(v =&gt; v.CreatedAt.ToString("O")) </code></pre> <p>Trying to evaluate this however yields an error:</p> <blockquote> <p>Evaluation of method System.Linq.SystemCore_EnumerableDebugView`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].get_Items requires calling method System.Globalization.GregorianCalendar.get_ID, which cannot be called in this context.</p> </blockquote> <p>I could have just specified <code>v.CreatedAt</code> which works but I'm interested in the milliseconds too, so I'm using the <code>O</code> format. Just calling <code>ToString()</code> yields the same error.</p> <p>So I'm wondering what is "this context" in the error message, and is there a chance to extend this context to make this possible?</p>
<c#><visual-studio-2015>
2016-08-27 16:09:03
HQ
39,184,105
Iterate with threshold stored in database
<p>I have a variable number of transactions in every month saved in the database. I have to calculate a payment according a structure like as 0-100 transaction, 1 € for every transaction, 101-200 2€ for each, 201 to 300 3€ for each, etc. The first 100 transactions I’ll pay 100 €, the next 100 transactions I’ll pay 200 € and in this way. Until here is easy for me, the problem become because the number of thresholds (in the earlier example was 3), can be variable, sometimes is 3, other times could be 2, 4, 5 or whatever. These thresholds are stored in a table in the database. Please, can someone help me. Thanks in advance.</p>
<c#>
2016-08-27 17:53:05
LQ_CLOSE
39,184,181
SSpring MVC resources not mapping
[my folder structure][1] [enter image description here][2] [1]: http://i.stack.imgur.com/YT0ZL.png [2]: http://i.stack.imgur.com/NgnE9.png And my code in the JSP page is ~ < script src='${pageContext.request.contextPath}/AppNameController.js'/> ~ I'm still getting 404 error
<spring><spring-mvc><resources>
2016-08-27 18:01:51
LQ_EDIT
39,184,389
How import object from external JS file in React JS using web pack
<p>I am building on my knowledge of React JS and I would like to import/include some external JS files that hold nothing more than an objects / object arrays. I've done this in jQuery, Vanilla JS and even in Angular JS. Sweet!!! </p> <p>How can I achieve the same thing in React JS.</p> <p>I have the following as my index.html:</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Hello React&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="hello"&gt;&lt;/div&gt; &lt;div id="world"&gt;&lt;/div&gt; &lt;div id="caseListing"&gt;&lt;/div&gt; &lt;script src="js/bundle.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and my main.js (entry file) as the following:</p> <pre><code>import Hello from './jsx/hello.jsx'; import World from './jsx/world.jsx'; var $ = require('./lib/jquery.js'); window.jQuery = $; window.$ = $; var Jobs = require('./data/jobs.js'); console.log('Jobs:', Jobs); </code></pre> <p>Here, I have Jobs.js as:</p> <pre><code>var Jobs = (function () { "use strict"; return { "jobs": [ { "jobType": "Web developer", "desc": "Creates website" }, { "jobType": "Bin Man", "desc": "Collects bins" } ] }; }()); </code></pre> <p>And just for good measure, my webpack.config.js looks like this:</p> <pre><code>var path = require('path'); var webpack = require('webpack'); module.exports = { entry: [ './js/main.js' ], output: { path: __dirname, filename: 'js/bundle.js' }, module: { loaders: [ { test: /.jsx?$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: [ 'es2015', 'react' ] } } ] } }; </code></pre> <p>All help will be appreciated. :)</p>
<javascript><reactjs><ecmascript-6><webpack><babeljs>
2016-08-27 18:25:30
HQ
39,184,738
Add one hour to PHP variable with date
<p>The title says it all. I have a PHP variable that says: <code>07/05/2016</code>.</p> <p>I've tried <code>strtodate</code>, the <code>date</code> function, but nothing seems to be working. <strong>How can I now add one hour to this date?</strong></p>
<php><date>
2016-08-27 19:07:02
LQ_CLOSE
39,184,778
Why set a React Component's state outside of the constructor?
<p>So I just downloaded source code from a React framework, and I'm getting this error in Terminal:</p> <pre><code> ERROR in ./src/components/TextEditor.js Module build failed: SyntaxError: Unexpected token (24:8) 22 | 23 | // Set the initial state when the app is first constructed. &gt; 24 | state = { | ^ 25 | state: initialState 26 | } 27 | </code></pre> <p>My question is, why do people set a React Component's state like this? What's the benefit if it'll error for some people? Also, is there a Babel preset or plugin I can get to prevent this error?</p> <p>This is how I usually set a component's state, and from what I've seen, this is conventional:</p> <pre><code>constructor() { super(); this.state = { state: initialState }; } </code></pre> <p>For the record, this is the entire document:</p> <pre><code>// Import React! import React from 'react' import {Editor, Raw} from 'slate' const initialState = Raw.deserialize({ nodes: [ { kind: 'block', type: 'paragraph', nodes: [ { kind: 'text', text: 'A line of text in a paragraph.' } ] } ] }, { terse: true }) // Define our app... export default class TextEditor extends React.Component { // Set the initial state when the app is first constructed. state = { state: initialState } // On change, update the app's React state with the new editor state. render() { return ( &lt;Editor state={this.state.state} onChange={state =&gt; this.setState({ state })} /&gt; ) } } </code></pre>
<javascript><reactjs><ecmascript-6>
2016-08-27 19:10:29
HQ
39,184,789
Difference between audit and debounce in rxjs?
<p>I am reading the offical documentaion of rxjs and then i realized they both are doing exactly same thing.</p> <p>To me they both seems to exactly similar. </p> <p>Please someone point out difference between them (if any)</p>
<angular><rxjs><rxjs5><reactivex>
2016-08-27 19:11:33
HQ
39,184,810
Why scanf() function reads two values when we put spaces after formate specifier even we are passing one reference
#include<stdio.h> main() { int a; printf("Enter a value \n"); scanf("%d ",&a); printf("a=%d \n",a); } in scanf() function i put space after formate specifier. when i compile this program scanf() function reading two values from user but the first value is assigned to 'a'. 1) why scanf() function reading two values when we use spaces after formate specifier even though we are passing one reference in above program. 2) why scanf() function reading one value when we use space before formate specifier even though we are passing one reference. 3) how the scanf() function will work.
<c>
2016-08-27 19:15:04
LQ_EDIT
39,185,449
C# read the name of the connected microphone
<p>How can I read in a winform the names of the connected recording device and of the standard recording device?</p>
<c#><microphone><recording>
2016-08-27 20:25:50
LQ_CLOSE
39,185,956
Spark on Amazon EMR: "Timeout waiting for connection from pool"
<p>I'm running a Spark job on a small three server Amazon EMR 5 (Spark 2.0) cluster. My job runs for an hour or so, fails with the error below. I can manually restart and it works, processes more data, and eventually fails again.</p> <p>My Spark code is fairly simple and is not using any Amazon or S3 APIs directly. My Spark code passes S3 text string paths to Spark and Spark uses S3 internally.</p> <p>My Spark program just does the following in a loop: Load data from S3 -> Process -> Write data to different location on S3. </p> <p>My first suspicion is that some internal Amazon or Spark code is not properly disposing of connections and the connection pool becomes exhausted.</p> <pre><code>com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.AmazonClientException: Unable to execute HTTP request: Timeout waiting for connection from pool at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:618) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.doExecute(AmazonHttpClient.java:376) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.executeWithTimer(AmazonHttpClient.java:338) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:287) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:3826) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.getObjectMetadata(AmazonS3Client.java:1015) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.getObjectMetadata(AmazonS3Client.java:991) at com.amazon.ws.emr.hadoop.fs.s3n.Jets3tNativeFileSystemStore.retrieveMetadata(Jets3tNativeFileSystemStore.java:212) at sun.reflect.GeneratedMethodAccessor45.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:191) at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102) at com.sun.proxy.$Proxy44.retrieveMetadata(Unknown Source) at com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem.getFileStatus(S3NativeFileSystem.java:780) at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:1428) at com.amazon.ws.emr.hadoop.fs.EmrFileSystem.exists(EmrFileSystem.java:313) at org.apache.spark.sql.execution.datasources.InsertIntoHadoopFsRelationCommand.run(InsertIntoHadoopFsRelationCommand.scala:85) at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult$lzycompute(commands.scala:60) at org.apache.spark.sql.execution.command.ExecutedCommandExec.sideEffectResult(commands.scala:58) at org.apache.spark.sql.execution.command.ExecutedCommandExec.doExecute(commands.scala:74) at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115) at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115) at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133) at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:114) at org.apache.spark.sql.execution.QueryExecution.toRdd$lzycompute(QueryExecution.scala:86) at org.apache.spark.sql.execution.QueryExecution.toRdd(QueryExecution.scala:86) at org.apache.spark.sql.execution.datasources.DataSource.write(DataSource.scala:487) at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:211) at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:194) at sun.reflect.GeneratedMethodAccessor85.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:237) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:280) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:128) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:211) at java.lang.Thread.run(Thread.java:745) Caused by: com.amazon.ws.emr.hadoop.fs.shaded.org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool at com.amazon.ws.emr.hadoop.fs.shaded.org.apache.http.impl.conn.PoolingClientConnectionManager.leaseConnection(PoolingClientConnectionManager.java:226) at com.amazon.ws.emr.hadoop.fs.shaded.org.apache.http.impl.conn.PoolingClientConnectionManager$1.getConnection(PoolingClientConnectionManager.java:195) at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.conn.ClientConnectionRequestFactory$Handler.invoke(ClientConnectionRequestFactory.java:70) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.conn.$Proxy45.getConnection(Unknown Source) at com.amazon.ws.emr.hadoop.fs.shaded.org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:423) at com.amazon.ws.emr.hadoop.fs.shaded.org.apache.http.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:863) at com.amazon.ws.emr.hadoop.fs.shaded.org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at com.amazon.ws.emr.hadoop.fs.shaded.org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:837) at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:607) ... 41 more </code></pre>
<apache-spark><amazon-emr>
2016-08-27 21:36:41
HQ
39,186,157
C programming book code
So I am reading the "C programming book" and I understand how this program functions, but, I don't understand one thing. I don't understand how fahr is functioning as a variable. does fahr have two values or one? Cause I thought once you write a value for a variable you can't change it unless you do the command strcpy. Maybe I am wrong, can some one help me clarify? Thanks~ Source: #include <stdio.h> #include <stdlib.h> int main() { float fahr, celsius; int lower,upper, step; lower = 0; upper = 700; step = 2; fahr = lower; printf("Fahrenheit\tCelsius\n"); while (fahr <= upper) { celsius = (5.0/9.0) * (fahr-32.0); printf("%3.0f \t %6.1f\n", fahr, celsius); fahr = fahr + step; } }
<c>
2016-08-27 22:02:16
LQ_EDIT
39,186,288
Why dollar ($) operator is so complex in GHC 8.0.1?
<pre><code>Prelude&gt; :i ($) ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). (a -&gt; b) -&gt; a -&gt; b -- Defined in ‘GHC.Base’ infixr 0 $ </code></pre> <p>How is it different from <code>(a -&gt; b) -&gt; a -&gt; b</code>? Is there any <code>b</code> that does not fit the new type signature?</p>
<haskell>
2016-08-27 22:19:09
HQ
39,187,097
Elastic Search number of object passed must be even
<p>I am learning about elastic search and I am following <a href="https://www.adictosaltrabajo.com/tutoriales/primeros-pasos-elasticsearch/" rel="noreferrer">the next tutorial</a>, but I get the next error </p> <pre><code>Exception in thread "main" java.lang.IllegalArgumentException: The number of object passed must be even but was [1] at org.elasticsearch.action.index.IndexRequest.source(IndexRequest.java:451) at elastic.elasti.App.lambda$0(App.java:55) at java.util.ArrayList.forEach(ArrayList.java:1249) at elastic.elasti.App.indexExampleData(App.java:53) at elastic.elasti.App.main(App.java:45) </code></pre> <p>Could you help me to fix it please?</p> <pre><code>public class App { public static void main( String[] args ) throws TwitterException, UnknownHostException { System.out.println( "Hello World!" ); List tweetJsonList = searchForTweets(); Client client = TransportClient.builder().build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)); String index = "tweets_juan"; client.admin().indices() .create(new CreateIndexRequest(index)) .actionGet(); indexExampleData(client, tweetJsonList, index); searchExample(client); } public static void indexExampleData(Client client, List tweetJsonList, String index) { BulkRequestBuilder bulkRequestBuilder = client.prepareBulk(); tweetJsonList.forEach((jsonTweet) -&gt; { bulkRequestBuilder.add(new IndexRequest(index, "tweets_juan") .source(jsonTweet)); }); BulkResponse bulkItemResponses = bulkRequestBuilder.get(); } public static void searchExample(Client client) { BoolQueryBuilder queryBuilder = QueryBuilders .boolQuery() .must(termsQuery("text", "españa")); SearchResponse searchResponse = client.prepareSearch("tweets_juan") .setQuery(queryBuilder) .setSize(25) .execute() .actionGet(); } public static List searchForTweets() throws TwitterException { Twitter twitter = new TwitterFactory().getInstance(); Query query = new Query("mundial baloncesto"); List tweetList = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; 10; i++) { QueryResult queryResult = twitter.search(query); tweetList.addAll(queryResult.getTweets()); if (!queryResult.hasNext()) { break; } query = queryResult.nextQuery(); } Gson gson = new Gson(); return (List) tweetList.stream().map(gson::toJson).collect(Collectors.toList()); } } </code></pre>
<elasticsearch>
2016-08-28 00:55:27
HQ
39,187,583
Xcode 8 "The application does not have a valid signature"
<p>Xcode 8 throws the following error despite provisioning seems to be fine:</p> <p><a href="https://i.stack.imgur.com/LqaRx.png"><img src="https://i.stack.imgur.com/LqaRx.png" alt="App installation failed. The application does not have a valid signature"></a></p> <p>How to fix it?</p>
<xcode><xcode8>
2016-08-28 02:47:25
HQ
39,187,722
error TS2339: Property 'for' does not exist on type 'HTMLProps<HTMLLabelElement>'
<p>Using typescript and react with TSX files with definitely typed type definitions, I am getting the error:</p> <pre><code>error TS2339: Property 'for' does not exist on type 'HTMLProps&lt;HTMLLabelElement&gt;'. </code></pre> <p>When trying to compile a component with the following TSX </p> <pre><code>&lt;label for={this.props.inputId} className="input-label"&gt;{this.props.label}&lt;/label&gt; </code></pre> <p>I have already solved but adding here for the next person since the solution didn't show up anywhere when searching (Google or StackOverflow)</p>
<reactjs><typescript>
2016-08-28 03:16:59
HQ
39,187,764
tensorflow: efficient feeding of eval/train data using queue runners
<p>I'm trying to run a tensorflow graph to train a model and periodically evaluate using a separate evaluation dataset. Both training and evaluation data is implemented using queue runners.</p> <p>My current solution is to create both inputs in the same graph and use a <code>tf.cond</code> dependent on an <code>is_training</code> placeholder. My issue is highlighted by the following code:</p> <pre><code>import tensorflow as tf from tensorflow.models.image.cifar10 import cifar10 from time import time def get_train_inputs(is_training): return cifar10.inputs(False) def get_eval_inputs(is_training): return cifar10.inputs(True) def get_mixed_inputs(is_training): train_inputs = get_train_inputs(None) eval_inputs = get_eval_inputs(None) return tf.cond(is_training, lambda: train_inputs, lambda: eval_inputs) def time_inputs(inputs_fn, n_runs=10): graph = tf.Graph() with graph.as_default(): is_training = tf.placeholder(dtype=tf.bool, shape=(), name='is_training') images, labels = inputs_fn(is_training) with tf.Session(graph=graph) as sess: coordinator = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coordinator) t = time() for i in range(n_runs): im, l = sess.run([images, labels], feed_dict={is_training: True}) dt = time() - t coordinator.request_stop() coordinator.join(threads) return dt / n_runs print('Train inputs: %.3f' % time_inputs(get_train_inputs)) print('Eval inputs: %.3f' % time_inputs(get_eval_inputs)) print('Mixed inputs: %.3f' % time_inputs(get_mixed_inputs)) </code></pre> <p>I also had to comment out the <code>image_summary</code> line <code>133</code> of <code>tensorflow/models/image/cifar10/cifar10_inputs.py</code>.</p> <p>This yielded the following results:</p> <pre><code>Train inputs: 0.055 Eval inputs: 0.050 Mixed inputs: 0.105 </code></pre> <p>It would seem in the mixed case both inputs are being read/parsed, even though only 1 is used. Is there a way of avoiding this redundant computation? Or is there a nicer way of switching between training/evaluation data that still leverages the queue-runner setup?</p>
<python><tensorflow>
2016-08-28 03:27:25
HQ
39,188,390
No javascript source from Github pages
<p>I cannot find the javascript source for a resume I'm trying to host on github pages. I'm not sure what is wrong...</p> <p>Here is a link to the site <a href="https://rowansdabomb.github.io/" rel="nofollow">https://rowansdabomb.github.io/</a></p> <p>Thanks in advance for any help!</p>
<javascript><github>
2016-08-28 05:53:11
LQ_CLOSE
39,188,469
How to read string in C
I try to run this code in c and expected runtime error but actually it did run,can you tell me the reason? char str[10]; scanf("%s",str); printf("%s",str); As i initialized the size of array as 10,how can code prints string of more than 10 letters?
<c><arrays><string>
2016-08-28 06:09:00
LQ_EDIT
39,188,847
Why do I have to set the dataSource and delegate to self?
<p>I'm learning swift, and the course I'm following teaches tableViews. It I have to set the <code>TableViewController</code> t include <code>UITableViewDataSource</code> and <code>UITableViewDelegate</code>. Then, in <code>viewDidLoad</code>, I have to set </p> <pre><code>tableView.dataSource = self tableView.delegate = self </code></pre> <p>in order for the tableView to appear and load data. </p> <p>Why do I have to do this?</p>
<ios><swift><uitableview>
2016-08-28 07:13:04
HQ
39,189,012
How to run code after a delay in Xamarin Android
<p>I'm trying to show some code after a delay in my Android app.<br> The Java code for doing this is something like this: </p> <pre><code>new Handler().postDelayed(new Runnable() { @Override public void run() { // your code that you want to delay here } }, 1000/* 1000ms = 1sec delay */); </code></pre> <p>How do I do this in Xamarin.Android with C#?</p>
<c#><android><xamarin><xamarin.android><android-runonuithread>
2016-08-28 07:36:57
HQ
39,189,483
On which way does RDD of spark finish fault-tolerance?
<p>Spark revolves around the concept of a resilient distributed dataset (RDD), which is a fault-tolerant collection of elements that can be operated on in parallel. But, I did not find the internal mechanism on which the RDD finish fault-tolerance. Could somebody describe this mechanism?Thanks.</p>
<apache-spark>
2016-08-28 08:46:54
HQ
39,190,211
How to return a tupple in haskell
type Record=([Char],[Char],[Char],[Char],[Char]) createAccount::IO()->Record createAccount=do putStrLn "Enter First Name" fname<-getLine putStrLn "Enter Last Name" lname<-getLine putStrLn "Enter State" state<-getLine putStrLn "Enter City" city<-getLine putStrLn "Enter House No." hnum<-getLine let hnumInt = read hnum :: Integer putStrLn "Enter Contact" contact<-getLine return (fname,lname,state,city,contact)
<haskell><tuples>
2016-08-28 10:12:44
LQ_EDIT
39,190,257
Please help parse Json result
Please help me get JSON result - "col1":"64.7020" to $result https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fd%2Fquotes.csv%3Fe%3D.csv%26f%3Dc4l1%26s%3DUSDRUB%3DX%22%3B&format=json&diagnostics=true&callback= {"query":{"count":1,"created":"2016-08-28T09:50:07Z","lang":"ru-RU","diagnostics":{"publiclyCallable":"true","url":{"execution-start-time":"1","execution-stop-time":"2","execution-time":"1","content":"http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USDRUB=X"},"user-time":"2","service-time":"1","build-version":"0.2.48"},"results":{"row":{"col0":"RUB","col1":"64.7020"}}}} $tick=file_get_contents('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fd%2Fquotes.csv%3Fe%3D.csv%26f%3Dc4l1%26s%3DUSDRUB%3DX%22%3B&format=json&diagnostics=true&callback='); $url = $tick; $json = file_get_contents($url); $data = json_decode($json, TRUE); $result ?? echo col1 ???????
<php><json>
2016-08-28 10:18:56
LQ_EDIT
39,190,409
I can't stop tracking files in source Tree
<p>I added to my repository files that I don't want to track now. I don't want them to appear in this pending files window but I don't wont to delete them from the project. The problem is that I don't know how to fix it. I tried everything. I even deleted them from repository(but not from the project so they were still on my disk) but after it they appeared in deleted files. It is really annoying. So how to get rid of this <code>/target/</code> files.</p> <p>Warning: Stop tracking option dosen't work! There is no reaction on it. </p> <p><a href="https://i.stack.imgur.com/MHk7q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MHk7q.png" alt="enter image description here"></a></p>
<atlassian-sourcetree><sourcetree>
2016-08-28 10:38:35
HQ
39,190,427
Angular2 Resolve before CanActivate
<p>I have an Authentication service that implements the Resolve interface to return an observable that is resolved once a user's authentication state is retrieved from the server. </p> <p>This same authentication service implements the CanActivate interface to block users from accessing a component if they are not logged in.</p> <p>Currently, the canActivate function is triggered before the resolve function is resolved, meaning it checks the user's login state before the login state has been retrieved from the server.</p> <p>My question is, how can I prevent the canActivate function being called until resolve is resolved, or otherwise is there another way I can achieve what I want?</p> <p>Thanks Max.</p>
<angular>
2016-08-28 10:40:15
HQ
39,190,451
Negative chat id in log file of telegram bot
<p>I have a telegram bot and save all user activity in a log file. When check log file, find user with negative chat id <code>-107606558</code>. Is this usual?</p>
<php-telegram-bot>
2016-08-28 10:45:08
HQ
39,190,487
if else statements formulation
<p>Maybe there was same question, but I don't know how to formulate it. Is it any difference between:</p> <pre><code>int x = 0; if( someCondition ) { x = 1; } </code></pre> <p>And</p> <pre><code>int x; if( someCondition ) { x = 1; } else { x = 0; } </code></pre>
<c#><c++>
2016-08-28 10:49:29
LQ_CLOSE
39,190,545
How do i enable javascript autoload function
is there a way i can enhance my script to autoload instad of using button. Also is there a way i can include fade-in style sort of in this script. <script> var content = [ "Headline", "Headline 1", "Headline 2", "Headline 3", ]; var msgPtr = 0; var stopAction = null; function change() { var newMsg = content[msgPtr]; document.getElementById('change').innerHTML = 'Breaking News: '+msgPtr+'<p>'+newMsg; msgPtr++; msgPtr = (msgPtr % content.length); } function startFunction() { change(); stopAction = setInterval(change, 4000); } function stopFunction() { clearInterval(stopAction); } </script>
<javascript>
2016-08-28 10:57:19
LQ_EDIT
39,190,885
Cannot find module 'eslint-config-defaults/configurations/eslint'
<p>I am new to working with the light version of Visual Studio Code and for the life of me I cannot figure out how to resolve this error.</p> <p>I've tried to pull in any type of file the even closely resembles the terms .eslint but i always get this error. I am sure it is a config error but I do not know how to work with the config just yet.</p> <p>Any suggestions?</p> <p>I am taking a Node.js course and they are using this light version and i would like to use it as well because it is somewhat faster for taking classes and so on.</p> <p><strong>Error</strong></p> <pre><code>Cannot find module 'eslint-config-defaults/configurations/eslint' </code></pre> <p><a href="https://i.stack.imgur.com/7fnxp.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/7fnxp.jpg" alt="eslint Error - Look at the very top of the enviroment"></a></p>
<c#><node.js><visual-studio-code><eslint>
2016-08-28 11:42:50
HQ
39,190,922
How to calculate with SCSS variables from function
<p>I have a function which converts px to rem. For example:</p> <pre><code>height: rem-calc(14px); // makes height: 1rem; </code></pre> <p>Now I would like to calculate with it from variables. For example:</p> <pre><code>$switch-track-width: rem-calc(50px); $switch-thumb-size: $switch-track-width / 2; // making it 25px or 1.7857rem in this case </code></pre> <p>That doesn't work so I tried something else:</p> <pre><code>$switch-thumb-size: ($switch-track-width / 2) + 0rem; $switch-thumb-size: (#{$switch-track-width} / 2) + 0rem; </code></pre> <p>Both <code>$switch-thumb-size</code> examples aren't working either. Now this is dividing but I'm also unable to get <code>times (*)</code>, <code>plus (+)</code> and <code>minus (-)</code> working.</p> <p>I'm also having a problem when calculating with 2 variables. For example:</p> <pre><code>$switch-track-height: rem-calc(14px); $switch-track-width: rem-calc(50px); $switch-thumb-right: $switch-track-height - $switch-track-width; </code></pre> <p>I prever to keep the function inside the variable instead of in the property like: <code>height: rem-calc($switch-track-height);</code>.</p> <p>If someone could tell me how to calculate with SCSS variables on both examples that would be very helpful. </p> <p>Thanks in advance</p>
<sass>
2016-08-28 11:46:31
HQ
39,191,320
this program is crashing,why?
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector<pair<int,int> > arr; arr[0].first=20,arr[0].second=1; arr[1].first=3,arr[1].second=2; arr[2].first=230,arr[2].second=3; arr[3].first=230,arr[3].second=4; arr[4].first=202,arr[4].second=5; arr[5].first=-20,arr[5].second=6; sort(arr.begin(),arr.end()); vector<pair<int,int> >::iterator it; for(it=arr.begin();it!=arr.end();it++) { cout<<it->first<<it->second<<endl; } } > This program isn't running properly,what can be possible reason behind this? also I wanna have sorted pairs vector in which sorting is done by the value.
<c++><sorting><vector><stl>
2016-08-28 12:34:03
LQ_EDIT
39,191,621
order wise match with batch and qty
I have a problem with excel sheet. i am sharing you my excel problem. Col-A Col-B Col-C Order.No Batch Qty 123451 211 5 123451 212 30 123451 213 50 123461 311 40 123471 411 50 123471 511 80 123481 611 20 123491 612 30 in col-A 123451 is repeating 3 time and 123471 2 time. i would like to max value from Col-3 and show batch No in front of it but only match 123451 order no. like Order.No Batch Qty 123451 213 50 123461 311 40 123471 411 80 123481 611 20 123491 612 30 as per this result you can see that Order.No-123451 find max value Qty and paste value batch-No as per maximum value criteria. remove duplicate Order No. the data can more then this. this is just example. Thanks. Please share this my Email: majid_mug@yahoo.com
<excel>
2016-08-28 13:11:28
LQ_EDIT
39,192,874
JQuery how to call a function when the div load completes
I have a page where i will have many buttons and links. On clicking of the buttons and links, i have a div tag called "scriptWPQ2" which will refresh. On refresh of this div completes, i need to write a function to change some data in the div dynamically. At the moment i tried document.ready or window.load it does not help please enlighten me on this $(document).ready(function () { $('#scriptWPQ2').load(function () { //dosomething }); });
<jquery>
2016-08-28 15:29:02
LQ_EDIT
39,192,945
Serialize Java 8 LocalDate as yyyy-mm-dd with Gson
<p>I am using Java 8 and the latest <code>RELEASE</code> version (via Maven) of <a href="https://github.com/google/gson" rel="noreferrer">Gson</a>. If I serialize a <a href="https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html" rel="noreferrer"><code>LocalDate</code></a> I get something like this</p> <pre><code>"birthday": { "year": 1997, "month": 11, "day": 25 } </code></pre> <p>where I would have preferred <code>"birthday": "1997-11-25"</code>. Does Gson also support the more concise format out-of-the-box, or do I have to implement a custom serializer for <code>LocalDate</code>s? </p> <p>(I've tried <code>gsonBuilder.setDateFormat(DateFormat.SHORT)</code>, but that does not seem to make a difference.)</p>
<java><gson>
2016-08-28 15:38:51
HQ
39,193,414
how to count how many users and how many comments to every post in mysql?
here is my comments table id(int) user_id(int) post_id(int) text(char) I want to calculate how many users has comments to every post and how many comments do every post have. I've already done the latter one as following: select count(*) from comments group by post_id; but how about the first one? any ideas?
<mysql><database>
2016-08-28 16:29:23
LQ_EDIT
39,193,419
Docker: in memory file system
<p>I have a docker container which does alot of read/write to disk. I would like to test out what happens when my entire docker filesystem is in memory. I have seen some answers here that say it will not be a real performance improvement, but this is for testing. </p> <p>The ideal solution I would like to test is sharing the common parts of each image and copy to your memory space when needed. </p> <p>Each container files which are created during runtime should be in memory as well and separated. it shouldn't be more than 5GB fs in idle time and up to 7GB in processing time. </p> <p>Simple solutions would duplicate all shared files (even those part of the OS you never use) for each container. </p>
<docker><filesystems><in-memory>
2016-08-28 16:29:50
HQ
39,193,985
How to colour tables in R - Conditional Fomatting
<p>I want to assign colors to tables in R.</p> <p><a href="https://i.stack.imgur.com/YjF3r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YjF3r.png" alt="enter image description here"></a></p> <p>Is it possible to create a table like this in R - where the predicted class is colored green when it is green and red when it is red.</p> <p>The above table displayed is done in excel.</p>
<r><conditional>
2016-08-28 17:30:12
LQ_CLOSE
39,194,016
Specializing templates based on methods
<p>Recently I've been programming a lot in Java, now I'm coming back to my C++ roots (I really started missing the pointers and segmentation faults). Knowing that C++ has a broad support for templates I was wondering whether it has some capabilities of Java which could be useful for writing generalized code. Lets say I'have two groups of classes. One of them has the <code>first()</code> method, the other one has the <code>second()</code> method. Is there a way of specializing the templates to be picked by the compiler depending on the methods one class possesses? I'm aiming at behavior which is similar to the one of Java:</p> <pre><code>public class Main { public static void main(String[] args) { First first = () -&gt; System.out.println("first"); Second second = () -&gt; System.out.println("second"); method(first); method(second); } static &lt;T extends First&gt; void method(T argument) { argument.first(); } static &lt;T extends Second&gt; void method(T argument) { argument.second(); } } </code></pre> <p>Where <code>First</code> and <code>Second</code> are interfaces. I know I could group both of these groups by deriving each of them from an upper class, but it's not always possible (no autoboxing in C++ and some classes don't inherit from a common ancestor).</p> <p>A good example of my needs is the STL library, where some classes have methods like <code>push()</code> and some others have <code>insert()</code> or <code>push_back()</code>. Lets say I want to create an function which has to insert multiple values into an container using an variadic function. In Java it's easy to perform because collections have a common ancestor. In C++ on the other hand it's not always the case. I tried it by duck-typing, but the compiler yields an error message:</p> <pre><code>template &lt;typename T&gt; void generic_fcn(T argument) { argument.first(); } template &lt;typename T&gt; void generic_fcn(T argument) { argument.second(); } </code></pre> <p>So my question is: Is implementing such behavior possible without creating unnecessary boileplate code by specializing every single case?</p>
<c++><templates><generics><duck-typing>
2016-08-28 17:33:22
HQ
39,194,091
how transpose column to rows spreadsheet?
Ok so I have something like this: hello hi how are you hello how are you hello hi hi hi hello hi how how are hello you I want this column to transpose into rows like this: hello hi how are you hello how are you hello hi hi hi hello hi how how are hello you How do I achieve this?
<excel><transpose>
2016-08-28 17:41:37
LQ_EDIT
39,194,331
not found: value assertThrows
<p>I have the following test class:</p> <pre><code>import org.scalatest.FunSuite @RunWith(classOf[JUnitRunner]) class NodeScalaSuite extends FunSuite { </code></pre> <p>With this test method:</p> <pre><code> test("Now doesn't terminate future that's not done") { val testFuture: Future[Int] = Future{ wait(1000) 10 } assertThrows[NoSuchElementException]{ testFuture.now } } </code></pre> <p>I am getting this error:</p> <pre><code>not found: value assertThrows </code></pre> <p>I looked over the ScalaTest documentation from here <a href="http://doc.scalatest.org/3.0.0/#org.scalatest.FunSuite" rel="noreferrer">http://doc.scalatest.org/3.0.0/#org.scalatest.FunSuite</a> and the code that's similar to mine seems to work fine.</p> <p>What's the issue?</p>
<scala><scalatest>
2016-08-28 18:10:34
HQ
39,195,232
how to setup bootstrap 4 scss with react webpack
<p>i'm starting a new project using reactjs ES6 and webpack</p> <p>using <a href="https://github.com/kriasoft/react-static-boilerplate" rel="noreferrer">react-static-boilerplate starter</a> question is how can i import bootstrap4 into the build proccess ?</p> <p>i dont want to use the bootstrap.css generated file, instead i want webpack to build it for me so i can get to change its @variables and apply my theme etc.</p> <p>i started project by cloning boilerplate</p> <pre><code>&gt; git clone -o react-static-boilerplate -b master --single-branch \ https://github.com/kriasoft/react-static-boilerplate.git MyApp &gt;cd MyApp &amp;&amp; npm install </code></pre> <ol start="2"> <li><p>installed bootstrap using npm</p> <p>npm install bootstrap@4.0.0-alpha.3</p></li> </ol> <p>now if i required the main bootstrap file into my index.js it will load fine. but how can i include the sass files of bootsrap to start customizing it ?</p>
<css><twitter-bootstrap><reactjs><webpack>
2016-08-28 19:57:11
HQ
39,195,414
Can someone help me understand != in Ruby?
<p>I'm working on learning Ruby on codecademy. I've gotten to comparators and am sure I'm not understanding !=. The directions say, exactly "You can also check to see if two values are not equal using the != comparator." What's the need to check whether something is specifically NOT equal to something else? Does this only apply to numbers? Would anyone be willing to give me 2-3 examples? </p>
<ruby>
2016-08-28 20:18:09
LQ_CLOSE
39,195,575
Is it "pythonic" to add attributes into class instance in runtime?
<p>Lets say I have a set of class instances to operate on. But I need some additional status variables per instance. The instance is not aware of them. Is it recommended to simply put such extra variable as attribute into an instance like this: <code>instances[x].extra_status_attribute = x</code>, or it is better to keep them separately?</p>
<python>
2016-08-28 20:39:51
LQ_CLOSE
39,195,699
How are files stored in memory and how can i use that knowledge in C++?
<p>How are files stored in memory? I suppose that when i write in a text file something like Hello World, the file in memory looks like this: <code>01001000 01100101 01101100 01101100 01101111</code> 1 Byte 1 Char?</p> <p>Well... I'm 90% sure I'm wrong about this and that's why I put this question.</p> <p>The actual thing is that I really want to know how Images are stored into memory because I want to use this to edit images or create ASCII art, and i feel like i could do this without a 3rd party library.</p> <p>The reason I didn't put my time into learning a library is that there are lots of them(I don't know which one to pick) and i don't know at what point I should looking into them... Well, this would be a different question</p>
<c++><c++11>
2016-08-28 20:55:35
LQ_CLOSE
39,196,129
Cannot modify example for ESP8266 provided by espressif
<p>My setup consists of the Espressif SDK using eclipse and a nodemcu, which I want to program in C.</p> <p>I have followed all he steps and I can compile and flash the board from the eclipse environment. I don't press any buttons to load the flash because the board can handle it by itself (at least that's what I read). According to <a href="http://www.cnx-software.com/2015/10/29/getting-started-with-nodemcu-board-powered-by-esp8266-wisoc/">this</a> apparently I have a nodemcu 0.9, but the board I have doesn't look quite like the one in the picture (the microstrip antenna looks weird .. and on the back of the board it says www.doit.am ESP12E devkit V2 ... the antenna on mine doesn't even look like the one on the site listed behind the board).</p> <p>I looked past everything and kept on going. I compiled the blinky example on espressif and flashed it. I saw that it created the eagle.flash.bin and eagle.irom0text.bin and loads them in 0x00000 and 0x10000 respectively (according to documents I've read this is ok). When i reset the board I can see that it really flashed and there is a program in it since the led is blinking. Then I tried the hello_world example. Everything went accordingly and after I reset the board I see that the led keeps on blinking at the same frequency and when I connect to the board via the terminal.exe provided by espressif I can only see garbage in the output, even though the baud is correct according to the code (even so I tried all different bauds possible in terminal.exe).</p> <p>Ok ... then I went to the blinky example again and increased the delay between blinks. Flashed it and the the frequency stayed the same. I know that it created new .bin files, but still, nothing changed. This led me to create a new project. I did it, following the instructions provided by Mikhail Grigorev. I just put an infinite loop, expecting to get nothing, but after flashing the newly compiled firmware I can still see the led blinking at the same frequency even though there is absolutely nothing in the code, I even wiped the flash before (yes, I verified the flash was empty).</p> <p>So this lead me to test every single example I could compile. I noticed that some didn't blink the led and others did, like nothing happened. After that i downloaded the nodemcu firmware, and after loading it I noticed that it worked properly and I could even see the ESP in the available wifi networks.</p> <p>I really don't understand what's happening. Why do some examples work and others don't? Why can't I modify the source code of a simple blinky and see the change? I really prefer to use the esp module this way, since I don't like the arduino interface or the way that it uses a static setup and loop functions, and I don't want to program it in LUA.</p> <p>I even checked the makefiles provided by espressif and the only difference I can see are the BOOT and APP variables. I even tried modifying them, but still .. no changes. </p> <p>Can anybody help me?</p>
<c><eclipse><esp8266><nodemcu>
2016-08-28 21:52:32
HQ
39,196,812
Finding 2nd largest number in array (one look at array)
<p>I did a class earlier where we went through this kind of algorithm but can't find my code. How do I find the 2nd biggest number in an array with only 1 scan?</p> <p>I was thinking about using nodes but that would screw up if the largest and 2nd largest one starts on same side. And an ugly way is to have two extra temp-variables and "find" the smaller one of them. </p> <p>So anyone got any tip? Oh and it's java if you have the code. In the meantime I'll try to search more on google!</p>
<java><arrays><search>
2016-08-28 23:45:14
LQ_CLOSE
39,197,217
Using geom_abline() and ggplot
<p>I am a beginner in <code>ggplot2</code>--it's been only 4 days since I have started experimenting with it. So, I apologize if this question sounds too basic. I'd appreciate any guidance--I've been struggling with this issue for about an hour.</p> <p>I was experimenting with using <code>geom_abline()</code> as below:</p> <pre><code> p &lt;- ggplot(mpg, aes(cty, hwy)) + geom_point() p + geom_abline() + facet_wrap(~cyl) </code></pre> <p>This works as in I can see a reference line in all four faceted graphs as below:</p> <p><a href="https://i.stack.imgur.com/VZGTv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VZGTv.png" alt="enter image description here"></a></p> <p>Later, I was using another related dataset <code>mtcars</code> to see what happens to <code>geom_abline()</code></p> <pre><code> p &lt;- ggplot(mtcars, aes(wt, mpg)) + geom_point() p + geom_abline() + facet_wrap(~cyl) </code></pre> <p>However, when I ran this command, I couldn't see <code>geom_abline().</code> Quite surprisingly, I found similar version of above command in the help file, and it says "<em><code>geom_abline()</code> is out of the range</em>"</p> <p>While I know what "out of range" means, but how do I know whether in a particular dataset, <code>abline()</code> will be out of range? I can override it by forcing it to use a specific slope and an intercept, but then I'd consider this a bit of hacking--i.e. modifying the code after seeing the output. Is there any way I can know what happens behind the scenes for <code>geom_abline()</code></p> <p>Here's the graph I got without any <code>abline()</code>s <a href="https://i.stack.imgur.com/o25Fh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/o25Fh.png" alt="enter image description here"></a></p> <p>I'd appreciate any thoughts. I am really confused.</p>
<r><ggplot2>
2016-08-29 01:01:40
HQ
39,197,530
Why is my c# code not working?
<p>I have made a console program in c# that is like a to-do task manager.<br> But it does not work when a certain code is reached:</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace To_Do_List { class Program { static void Main(string[] args) { string path = @"C:\ToDoTask.txt"; Console.WriteLine("To-do program"); while (true) { if (Console.ReadLine() == "exit") { Environment.Exit(0); } if (Console.ReadLine() == "add") { Console.WriteLine("Please write your task and then press enter"); string task = Console.ReadLine(); Console.WriteLine("Task added"); try { StreamWriter sw = new StreamWriter(path); sw.WriteLine(task); } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error: could not write task to file"); Console.ResetColor(); } } if (Console.ReadLine() == "show") { try { Console.WriteLine("Tasks:"); StreamReader sr = new StreamReader(path); if (sr.ReadToEnd() != "") { Console.WriteLine(sr.ReadToEnd()); } else { Console.WriteLine("No tasks left"); } } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error: could not read tasks file"); Console.ResetColor(); } } if (Console.ReadLine() == "help") { Console.WriteLine("Write 'add' to add a new task"); Console.WriteLine("Write 'show' to see current tasks"); Console.WriteLine("Write 'exit' to exit program"); } } } } } </code></pre> <p>I am new programming and I can't find the error. When I write add, show or exit, or help nothing happens. Thanks.</p>
<c#>
2016-08-29 01:55:40
LQ_CLOSE
39,197,866
No assembly found containing an OwinStartupAttribute Error
<p>This error </p> <p>The following errors occurred while attempting to load the app. - No assembly found containing an OwinStartupAttribute. - The given type or method 'false' was not found. Try specifying the Assembly. To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config. To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.</p> <p>appears on my screen on the most face burningly ugly error page ever created in history. </p> <p><a href="https://i.stack.imgur.com/rDKpi.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/rDKpi.jpg" alt="enter image description here"></a></p> <p>Ive tried to follow the instructions on the page by inserting the owin:AutomaticAppStartup in the config.</p> <pre><code> &lt;appSettings &gt; &lt;add key="owin:AppStartup" value="false"&gt;&lt;/add&gt; &lt;/appSettings&gt; </code></pre> <p>this did not fix the problem. Any suggestions?</p>
<c#><web-config><owin><.net-assembly>
2016-08-29 02:50:53
HQ
39,197,989
Laravel 5: using bcrypt on same string gives different values
<p>I am using Laravel's <code>bcrypt</code> function for hashing passwords. When I do,</p> <pre><code>bcrypt('secret') </code></pre> <p>I get</p> <pre><code>=&gt; "$2y$10$mnPgYt2xm9pxb/c2I.SH.uuhgrOj4WajDQTJYssUbTjmPOcgQybcu" </code></pre> <p>But if I run it again, I get</p> <pre><code>=&gt; "$2y$10$J8h.Xmf6muivJ4bDweUlcu/BaNzI2wlBiAcop30PbPoKa0kDaf9xi" </code></pre> <p>and so on...</p> <p>So, won't the password matching process fail if I get different values every time?</p>
<laravel><laravel-5><bcrypt>
2016-08-29 03:10:36
HQ
39,198,503
python - difference between print and return
<p>If I print the result of the <code>for loop</code> in this <code>function</code>:</p> <pre><code>def show_recommendations_for_track(tracks = [], *args): results = sp.recommendations(seed_tracks = tracks, limit=100) tracks = results['tracks'] for track in tracks: print track['name'] </code></pre> <p>It prints one hundred track names.</p> <p>If I swap <code>print</code> for <code>return track['name']</code>,</p> <p>it prints only one track name.</p> <p>why?</p>
<python>
2016-08-29 04:28:17
LQ_CLOSE
39,198,702
how can i have 2 language auto signature in outlook?
i have 2 languages installed in outlook, English (left to right) and Arabic (Right to left) and created 2 different signatures. I can assign each signature manually to each language but i want to know is it possible that signature assign automatically when i change the language or the direction. and how ? Thanks
<outlook><signature>
2016-08-29 04:55:29
LQ_EDIT
39,198,845
Sort Javascript Array by Json object in array
I have an array var a=[['test':'1','test1':'2','test2':{'test3':'3','test4':'4'}],['test':'2','test1':'2','test2':{'test3':'1','test4':'2'}]]; I can sort array using test and test 1 fields. But I have no idea to sort using test3 or test4. How can this array be sorted.
<javascript><arrays><sorting>
2016-08-29 05:10:01
LQ_EDIT
39,199,188
How do I only allow letters when asking for a name in python?
<p>I am new to coding in python and need to know how to only allow the user to enter letters when inputting a name. So if they input a number or nothing at all, I want the code to say something like "Please only use letters, try again".</p> <p>Cheers Chris</p>
<python><string><input>
2016-08-29 05:42:51
LQ_CLOSE
39,199,303
Pass data from parent to child component in vue.js
<p>I am trying to pass data from a parent to a child component. However, the data I am trying to pass keeps printing out as blank in the child component. My code:</p> <p>In <code>Profile.js</code> (Parent component)</p> <pre><code>&lt;template&gt; &lt;div class="container"&gt; &lt;profile-form :user ="user"&gt;&lt;/profile-form&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import ProfileForm from './ProfileForm' module.exports = { data: function () { return { user: '' } }, methods: { getCurrentUser: function () { var self = this auth.getCurrentUser(function(person) { self.user = person }) }, } &lt;/script&gt; </code></pre> <p>In <code>ProfileForm.js</code> (Child component)</p> <pre><code>&lt;template&gt; &lt;div class="container"&gt; &lt;h1&gt;Profile Form Component&lt;/h1&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; module.exports = { created: function () { console.log('user data from parent component:') console.log(this.user) //prints out an empty string }, } &lt;/script&gt; </code></pre> <p>Note - my <code>user</code> is loaded via my <code>getCurrentUser()</code> method... Can someone help?</p> <p>Thanks in advance!</p>
<components><vue.js>
2016-08-29 05:52:29
HQ
39,201,137
Facebook and Twitter data scraping using perl
<p>I want to create a web dashboard where i can search any user by name from facebook, &amp; twitter and then show all the details (public like educations about , likes ) on my dashboard.</p> <p>How this can be done using perl?</p> <p>I cant use graph API as it shows for only users allow my app (permission based.)</p> <p>Please guide me .</p>
<perl><facebook-like>
2016-08-29 07:53:37
LQ_CLOSE
39,201,916
find the key of groupby in linq C#
var aaa = newList.GroupBy(o => o.Date).Select(o => new { o }).ToList(); //There is a error of `Key` var bbb = aaa.Select(o => o.Key).ToList(); does that mean the `Key` is only allowed for the original List after `GroupBy`. Is it possible to obtain the `Key` for any `Select` after `GroupBy`?(Surely, we can storge the `Key = o.Key` in the `Select` )
<c#><linq><key>
2016-08-29 08:40:21
LQ_EDIT
39,202,390
Parse error: syntax error in PHP
<p>I try to store a string to a PHP variable. But it shows an error "Parse error: syntax error, unexpected '='" Here is the code</p> <pre><code>$page-title = "Home Page"; </code></pre>
<php>
2016-08-29 09:08:10
LQ_CLOSE
39,203,215
Kafka - difference between Log end offset(LEO) vs High Watermark(HW)
<p>What is the difference between <code>LEO and HW</code> in Replica ( <code>Leader Replica</code>)?</p> <p>Will they contain the same number? I can understand HW is the <code>last committed message offset</code>.</p> <p>When LEO will be updated and how?</p>
<apache-kafka><kafka-consumer-api><kafka-producer-api>
2016-08-29 09:47:47
HQ
39,204,047
Rails mailer previews not available from spec/mailers/previews
<p>I would like to be able to preview my emails in the browser.</p> <p>I am using Rspec and have the following preview setup in spec/mailers/previews:</p> <pre><code># Preview all emails at http://localhost:3000/rails/mailers/employee_mailer class EmployeeMailerPreview &lt; ActionMailer::Preview def welcome Notifier.welcome_email(Employee.first) end end </code></pre> <p>When I try to access this I get the following error:</p> <pre><code>AbstractController::ActionNotFound at /rails/mailers/employee_mailer Mailer preview 'employee_mailer' not found </code></pre> <p>However, when I put the code for the preview inside of tests/mailers/previews it works.</p> <p>How can I configure my Rails app to look for the previews inside of spec/mailers/previews?</p>
<ruby-on-rails><rspec>
2016-08-29 10:30:40
HQ
39,205,362
Anroid - call a method in a service from its parent
It's sounds simple but I couldn't figure it out.. I there a way to call a method in a service I started from it's parent? (without using broadcast) Thanks.
<android><methods><service><call><parent>
2016-08-29 11:36:38
LQ_EDIT
39,205,788
Is it require app in our device for geofencing and what are requirements?
For Beacons, It is working BLE,So it requires bluetooth on. But why it requires location service on.Is it possible to without using location services in physical web to push notification from beacons just by using BLE range ? For Geofencing, I dont want to create a new app for geofencing.Is it possible without app in the device to geofencing. Please help me. Advance thanks...
<android><geofencing><beacon>
2016-08-29 11:58:16
LQ_EDIT
39,205,899
How to embed whole angularjs app into existing app which is separately deployed
<p>I have application with logic similar to google's app switcher, let me call it <code>Wrapper</code>. This application take place across all google services and has consistent UI everywhere. </p> <p>I am looking for solution to inject into my <code>Wrapper</code> application several finished different apps with their own styles, views and JS. They are written with different technologies like React and Angular. </p> <p>How can I implement such architecture? Are Web-components a solution for this, if yes - please provide me some examples. (The aim is to deploy wrapper separately and all content applications too, so they will have consistent UI and logic from wrapper).</p> <p>Please do not mention the <code>iframe</code>!</p>
<javascript><angularjs><web-component>
2016-08-29 12:03:54
HQ
39,206,599
Testing EditText errors with Espresso on Android
<p>I want to test if an EditText field has an error (set with editText.setError("Cannot be blank!")).</p> <p><a href="https://i.stack.imgur.com/fipqA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fipqA.png" alt="EditText field with error"></a></p> <p>I've created an Espresso test case with the new AndroidStudio 2.2 feature, to record Espresso tests. So the code is pretty much auto-generated. But for now it only checks if the editText is displayed.</p> <pre><code>@RunWith(AndroidJUnit4.class) public class CreateNoteActivityTitleCannotBeBlank { @Rule public ActivityTestRule&lt;CreateNoteActivity&gt; mActivityTestRule = new ActivityTestRule&lt;&gt;(CreateNoteActivity.class); @Test public void createNoteActivityTitleCannotBeBlank() { ViewInteraction floatingActionButton = onView( allOf(withId(R.id.fab_add_note), withParent(allOf(withId(R.id.activity_create_note), withParent(withId(android.R.id.content)))), isDisplayed())); floatingActionButton.perform(click()); ViewInteraction editText = onView( allOf(withId(R.id.tiet_note_title), childAtPosition( childAtPosition( withId(R.id.til_title), 0), 0), isDisplayed())); editText.check(matches(isDisplayed())); } private static Matcher&lt;View&gt; childAtPosition( final Matcher&lt;View&gt; parentMatcher, final int position) { return new TypeSafeMatcher&lt;View&gt;() { @Override public void describeTo(Description description) { description.appendText("Child at position " + position + " in parent "); parentMatcher.describeTo(description); } @Override public boolean matchesSafely(View view) { ViewParent parent = view.getParent(); return parent instanceof ViewGroup &amp;&amp; parentMatcher.matches(parent) &amp;&amp; view.equals(((ViewGroup) parent).getChildAt(position)); } }; } } </code></pre> <p>Is there a way to test if the error is displayed?</p>
<android><testing><junit4><android-espresso>
2016-08-29 12:40:03
HQ
39,207,048
How to define Object of Objects type in typescript
<p>I have an object to store cached data which should look like this:</p> <pre><code>private data = { 'some_thing': new DataModel(), 'another_name': new DataModel() } </code></pre> <p>I'm trying to assign an empty object to it in the constructor:</p> <pre><code>this.data = {}; // produces build error </code></pre> <p>Basically, i need to define the type of "data" field to say that it's going to have keys with random names and values of type DataModel. I've tried to do this:</p> <pre><code>private data: Object&lt;DataModel&gt; </code></pre> <p>But this is invalid. How would i specify a correct type?</p>
<typescript>
2016-08-29 13:03:42
HQ
39,207,798
Carbon - why addMonths() change the day of month?
<p>Here's the simple example (today is 2016-08-29):</p> <pre><code>var_dump(Carbon::now()); var_dump(Carbon::now()-&gt;addMonths(6)); </code></pre> <p>Output:</p> <pre><code>object(Carbon\Carbon)#303 (3) { ["date"] =&gt; string(26) "2016-08-29 15:37:11.000000" } object(Carbon\Carbon)#303 (3) { ["date"] =&gt; string(26) "2017-03-01 15:37:11.000000" } </code></pre> <p>For <code>Carbon::now()-&gt;addMonths(6)</code> I'm expecting <code>2017-02-29</code>, not <code>2017-03-01</code>.</p> <p>Am I missing something about date modifications?</p>
<php><laravel><date><datetime><php-carbon>
2016-08-29 13:42:34
HQ
39,207,924
Jenkins - How to get and use upstream info in downstream
<p>Executing upstream job called "A". On success of A executing test cases which is downstream project "B". But while sending mail from B we have to incorporate upstream project details (upstream project name, build no) in mail. So we can easily map / corelate the test run with respective upstream job. </p> <p>In downstream project dashboard below details are displaying.</p> <pre><code>Started by upstream project Dev_RM_3.0_CI_Test build number 10 originally caused by: </code></pre> <p>I checked in <a href="https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project" rel="noreferrer">https://wiki.jenkins-ci.org/display/JENKINS/Building+a+software+project</a>. but couldnt find anything to inherit in downstream.</p> <p>Created sample job with below details to display the current job details.</p> <pre><code>echo $BUILD_NUMBER echo $JOB_NAME echo $BUILD_ID </code></pre> <p>But the output is</p> <pre><code>Building on master in workspace /var/lib/jenkins/workspace/env [env] $ /bin/sh -xe /tmp/hudson970280339057643719.sh + echo 1 1 + echo env env + echo 1 1 Finished: SUCCESS </code></pre> <ol> <li>Any help to inherit upstream details in downstream job?</li> <li>How to get current job details?</li> </ol>
<jenkins><jenkins-plugins>
2016-08-29 13:48:23
HQ
39,207,976
How to print files in Visual Studio Code
<p>I tried to print a file from Visual Studio Code, but could neither find an entry in the menu nor an extension.</p> <p>I'm using Version 1.4.0 from August 4th, 2016.</p> <p>I ended up opening the file in Notepad++ for printing, which is quite cumbersome.</p>
<visual-studio-code>
2016-08-29 13:50:46
HQ
39,208,352
dictionary pythoon with a csv file
i'm new at all this coding but have loots of motivation even when thigs don't work. i'm trying to work on a dictionary with a CSV file i get to open a new file and edit it but i think i'm missing something when trying to read from the csv file.. here is the code i get errors in rows 39-41 i'm probably doing something wrong but what is it? import csv import os import os.path phonebook = {} def print_menu(): print('1. Print phone book') print('2. add phone book') print('3. look for number using first name only') print('4. look by last name') print('5. exit') print() menu_selection = 0 while menu_selection != 5: if os.path.isfile('my_phonebook.csv') == True: csv_file = open('my_phonebook.csv', 'a', newline = '') writer = csv.writer(csv_file) else: csv_file = open('my_phonebook.csv', 'w', newline = '') writer = csv.writer(csv_file) headers = ['first_name','last_name','phone_number'] writer.writerow(headers) print_menu() menu_selection = int(input('type menu selection number')) if menu_selection == 2: #add list in phone book first_name = input("enter first name: ") last_name = input("enter last name: ") phone_number = input("enter phone number: ") writer.writerow([first_name,last_name,phone_number]) csv_file.close() elif menu_selection == 1: #print phone book print("phone book:") listGen = csv.reader(csv_file, delimiter=' ', quotechar='|') #error starts here and in the next two rows... for row in csv_file: print(row) elif menu_selection == 3: #look for number using first name only print('look up number') first_name = input('first name:') if first_name in phonebook: print('the number is', phonebook[phone_number]) else: print('name not found') elif menu_selection == 4: #print all details of last name entered print('search by last name') last_name = input('please enter last name: ') for row in csv_file: print(row)
<python><csv><dictionary>
2016-08-29 14:10:18
LQ_EDIT
39,208,469
Regex in Javascript using OR
<p>I'm trying to write a regex expression to match multiple characters such as , OR . OR : OR ( OR )</p> <p>I have this</p> <pre><code>removePunctuation = /\.$|\,$|\:|\(|\)/; word = rawList[j].replace(removePunctuation,"") </code></pre> <p>I just want to remove periods &amp; commas at the end of the sentence but all instances of ( ) :</p> <p>What am I doing wrong?</p>
<javascript><regex>
2016-08-29 14:15:45
LQ_CLOSE