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
35,308,462
Can we run any user defined function before the main function?
<p>I want to run a user defined function before the main function in C. But I don't know how to do that. Is that possible?</p>
<c>
2016-02-10 06:40:03
LQ_CLOSE
35,309,115
Why constexpr is not the default for all function?
<p>After relaxing the rules for the constexpr it seems as these functions can be used everywhere. They can be called on both constant (constexpr) and local (mutable) variables as well. So for me it seem as just a hint for the compiler (like inline). I just keep writing it everywhere and remove it if compiler complains. So compiler seems to know everything if a function can be evaluated at compile time or not. Why is it not the default behavior and why do i have to mark anything as constexpr ?</p>
<c++><c++14><constexpr>
2016-02-10 07:22:28
HQ
35,309,220
Smart keyboard internalization for IDEA
<p>When I start IntelliJ IDEA, that message comes up, but I couldn't find any information about that feature and how it could help me.</p> <blockquote> <p>Enable smart keyboard internalization for IDEA.: We have found out that you are using a non-english keyboard layout. You can enable smart layout support for German language.You can change this option in the settings of IDEA more...</p> </blockquote>
<intellij-idea>
2016-02-10 07:30:05
HQ
35,310,212
Docker missing layer IDs in output
<p>I just did a fresh install of Docker on Ubuntu using the official guidelines: <a href="https://docs.docker.com/engine/installation/linux/ubuntulinux/" rel="noreferrer">https://docs.docker.com/engine/installation/linux/ubuntulinux/</a></p> <p>When I pull an image using "sudo docker pull ubuntu" and then "sudo docker history ubuntu" it returns missing layer IDs in the columns. Using the documentation example ( <a href="https://docs.docker.com/engine/reference/commandline/history/" rel="noreferrer">https://docs.docker.com/engine/reference/commandline/history/</a> ) my output is:</p> <pre><code>IMAGE CREATED CREATED BY SIZE COMMENT 3e23a5875458 8 days ago /bin/sh -c #(nop) ENV LC_ALL=C.UTF-8 0 B "missing" 8 days ago /bin/sh -c dpkg-reconfigure locales &amp;&amp; loc 1.245 MB "missing" 8 days ago /bin/sh -c apt-get update &amp;&amp; apt-get install 338.3 MB </code></pre> <p>and so on. Only the base layer ID shows, the rest is "missing". I tried installing on another Ubuntu machine connected to a different network and it has the same problem for any image that I download.</p> <p>Does someone know what's causing this or able to help me fix it? I rely on this layer ID since I'm gathering some statistics on the reusability of layers so I need this ID to show correctly.</p> <p>Thank you</p>
<ubuntu><docker>
2016-02-10 08:36:02
HQ
35,310,604
How to calculate same name as one?
I'm trying to calculate how many lines are there and my code is working but I failed to calculate if there is same name in each line as one for example john 01/2 john 02/3 def number_people(path): x = 0 with open(path) as f: for line in f: if line.strip(): x += 1 return x
<python>
2016-02-10 08:56:44
LQ_EDIT
35,310,695
Convert byte string to bytes or bytearray
<p>I have a string as follows:</p> <pre><code> b'\x00\x00\x00\x00\x07\x80\x00\x03' </code></pre> <p>How can I convert this to an array of bytes? ... and back to a string from the bytes?</p>
<python><byte><bytearray>
2016-02-10 09:01:50
HQ
35,311,052
How to upgrade/refresh the ag-grid after row delete?
<p>I have an ag grid where i am trying to delete a row...I am able to remove the row from data source using "splice" technique,after that i want to refresh the table.But it is showing error.This is the code which i am using to delete a row</p> <pre><code>selectedvalue={} //this holds the selected row value rowData=[]; //this holds all the row data onRowSelected(event) { this.selectedvalue = event; } deletebtn() { for (let i = 0; i &lt; this.rowData.length; i++) { if (this.selectedvalue.node.data.make === this.rowData[i].make) { this.rowData.splice(i, 1); this.gridOptions.api.refreshView(); } } } </code></pre> <p>It is showing erroe something like this--> Cannot read property 'refreshView' of undefined...How can watch the changes made in table after row delete.</p>
<angular><ag-grid>
2016-02-10 09:19:43
HQ
35,311,687
Unable to require directive in AngularJS 1.5 component
<p>I've created a directive which works perfectly fine. Now after bumping <code>angular</code> to <code>1.5.0</code>, I figured this directive is a typical example of what could be written using the new <code>.component()</code> notation.</p> <p>For some reason, the <code>require</code> property no longer seems to work.</p> <p>The following is a simplified example:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('myApp', []) .component('mirror', { template: '&lt;p&gt;{{$ctrl.modelValue}}&lt;/p&gt;', require: ['ngModel'], controller: function() { var vm = this; var ngModel = vm.ngModel; ngModel.$viewChangeListeners.push(onChange); ngModel.$render = onChange; function onChange() { vm.modelValue = ngModel.$modelValue; } } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="myApp"&gt; &lt;input ng-model="someModel"/&gt; &lt;mirror ng-model="someModel"&gt;&lt;/mirror&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I also tried using <code>require</code> as a simple string:</p> <pre><code>... require: 'ngModel' ... </code></pre> <p>and as an object:</p> <pre><code>... require: { ngModel: 'ngModel' } ... </code></pre> <p>I've looked at the docs for <a href="https://code.angularjs.org/1.5.0/docs/api/ng/service/$compile">$compile</a> and <a href="https://code.angularjs.org/1.5.0/docs/guide/component">component</a>, but I can't seem to get it to work.</p> <p>How can I require other directive controllers in an AngularJS 1.5 component?</p>
<angularjs><angularjs-1.5>
2016-02-10 09:48:18
HQ
35,311,755
Realm ORM: how to deal with Maps?
<p>I am creating an Android app and I need to persist a <code>Map&lt;String,MyClass&gt;</code>. I've just started to use <a href="https://realm.io" rel="noreferrer">Realm ORM</a>, as it supports one-to-one and one-to-many, enumerations and lists. I also found a workaround for lists of strings (i.e. I have to create a StringWrapper class encapsulating a string. However, from the <a href="https://realm.io/docs/java/latest/" rel="noreferrer">documentation</a> I understand there is no easy way like <code>RealmMap</code>, as it happens for lists. So, I'm looking for the best way to persist a map. My current idea is to replace my map with a list of objects <code>KeyValueObject</code> encapsulating a <code>String</code> (the former map key) and a <code>MyClass</code>. Similarly to <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Map.Entry.html" rel="noreferrer"><code>Map.Entry</code></a>. Is there any other solution that does not need me to rework the domain model for technology reasons?</p>
<java><android><realm>
2016-02-10 09:50:52
HQ
35,311,780
How to show different value of input element with ng-model?
<p>In the controller if have a variable that tracks the index (starting at 0) of the page for a pagination table:</p> <pre><code>var page { pageNumber: 0; } </code></pre> <p>Question: how can I show this <code>pageNumber</code> variable in the html, but always incremented by +1? (as the index=0 page is obviously the 1st page and should thus be shown as <code>Page 1</code>)</p> <pre><code>&lt;input type="text" ng-model="page.pageNumber"&gt; </code></pre> <p>Also, when the model gets updated, the value in the input should automatically change (again: also incremented by +1).</p>
<javascript><angularjs>
2016-02-10 09:52:03
HQ
35,311,922
android selectableItemBackground selection
<p>i want to change background of my view when the state is "activated" and i want to preserve the effects(ripple) of <code>?attr:selectableItemBackground</code>. Is it possible to extend or combine selector of <code>?attr:selectableItemBackground</code>?</p>
<android><android-selector>
2016-02-10 09:58:19
HQ
35,312,274
Jenkins git submodule update fails
<p>I have a git repo which has one submodule. Both belong to a team on BitBucket. My jenkins machine is a AWS windows server with the git plugin. I am using SSH keys for authentication. I have three jenkins jobs. One clones the main repo. This is successful. One clones the second repo on its own (the repo which will be used as a submodule). This is also successful. In my third build job I tell jenkins to recursively update the submodules. This fails and says public-key error. How can this be the case if I can clone the repo on its own?</p> <p>Console output below:</p> <pre><code>Started by user anonymous Building on master in workspace C:\Program Files (x86)\Jenkins\jobs\MainRepo\workspace Wiping out workspace first. Cloning the remote Git repository Cloning repository git@bitbucket.org:team/mainrepo.git &gt; git.exe init C:\Program Files (x86)\Jenkins\jobs\mainrepo\workspace # timeout=10 Fetching upstream changes from git@bitbucket.org:team/mainrepo.git &gt; git.exe --version # timeout=10 using GIT_SSH to set credentials &gt; git.exe -c core.askpass=true fetch --tags --progress git@bitbucket.org:team/mainrepo.git +refs/heads/*:refs/remotes/origin/* &gt; git.exe config remote.origin.url git@bitbucket.org:team/mainrepo.git # timeout=10 &gt; git.exe config --add remote.origin.fetch +refs/heads/*:refs/remotes/origin/* # timeout=10 &gt; git.exe config remote.origin.url git@bitbucket.org:team/mainrepo.git # timeout=10 Fetching upstream changes from git@bitbucket.org:team/mainrepo.git using GIT_SSH to set credentials &gt; git.exe -c core.askpass=true fetch --tags --progress git@bitbucket.org:team/mainrepo.git +refs/heads/*:refs/remotes/origin/* &gt; git.exe rev-parse "refs/remotes/origin/master^{commit}" # timeout=10 &gt; git.exe rev-parse "refs/remotes/origin/origin/master^{commit}" # timeout=10 Checking out Revision 6b3f6535c45e79ee88f4918d464edead48d83369 (refs/remotes/origin/master) &gt; git.exe config core.sparsecheckout # timeout=10 &gt; git.exe checkout -f 6b3f6535c45e79ee88f4918d464edead48d83369 &gt; git.exe rev-list 6b3f6535c45e79ee88f4918d464edead48d83369 # timeout=10 &gt; git.exe remote # timeout=10 &gt; git.exe submodule init # timeout=10 &gt; git.exe submodule sync # timeout=10 &gt; git.exe config --get remote.origin.url # timeout=10 &gt; git.exe submodule update --init --recursive FATAL: Command "git.exe submodule update --init --recursive" returned status code 128: stdout: stderr: Cloning into 'my-submodule'... Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. fatal: clone of 'git@bitbucket.org:team/my-submodule.git' into submodule path 'my-submodule' failed hudson.plugins.git.GitException: Command "git.exe submodule update --init --recursive" returned status code 128: stdout: stderr: Cloning into 'my-submodule'... Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. fatal: clone of 'git@bitbucket.org:team/my-submodule.git' into submodule path 'my-submodule' failed at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:1693) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$500(CliGitAPIImpl.java:62) at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$7.execute(CliGitAPIImpl.java:953) at hudson.plugins.git.extensions.impl.SubmoduleOption.onCheckoutCompleted(SubmoduleOption.java:90) at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1098) at hudson.scm.SCM.checkout(SCM.java:485) at hudson.model.AbstractProject.checkout(AbstractProject.java:1276) at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:607) at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86) at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:529) at hudson.model.Run.execute(Run.java:1738) at hudson.matrix.MatrixBuild.run(MatrixBuild.java:301) at hudson.model.ResourceController.execute(ResourceController.java:98) at hudson.model.Executor.run(Executor.java:410) Finished: FAILURE </code></pre>
<git><jenkins><bitbucket><git-submodules>
2016-02-10 10:12:51
HQ
35,312,410
java.lang.IncompatibleClassChangeError: Implementing class with ScalaCheck and ScalaTest
<p>I'm facing a nasty exception when trying to write a test using ScalaCheck and ScalaTest. Here's my dependencies:</p> <pre><code>libraryDependencies ++= Seq( "org.scalatest" %% "scalatest" % "2.2.6" % "test", "org.scalacheck" %% "scalacheck" % "1.13.0" % "test" ) </code></pre> <p>Here's my test:</p> <pre><code>import org.scalatest.PropSpec import org.scalatest.prop.Checkers class MyPropSpec extends PropSpec with Checkers { property("List.concat") { check((a: List[Int], b: List[Int]) =&gt; a.size + b.size == (a ::: b).size) } } </code></pre> <p>When I try to run this I'm getting:</p> <pre><code>DeferredAbortedSuite: Exception encountered when attempting to run a suite with class name: org.scalatest.DeferredAbortedSuite *** ABORTED *** java.lang.IncompatibleClassChangeError: Implementing class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:760) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ... java.lang.IncompatibleClassChangeError: Implementing class at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:760) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) at java.net.URLClassLoader.access$100(URLClassLoader.java:73) at java.net.URLClassLoader$1.run(URLClassLoader.java:368) at java.net.URLClassLoader$1.run(URLClassLoader.java:362) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:361) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ... </code></pre> <p>What am I missing here?</p>
<scala><scalatest><scalacheck>
2016-02-10 10:19:07
HQ
35,313,012
how extract data from json in php
<p>how to extract from json </p> <pre><code>{"aaData":[["Hitech Institute","0shoaib0@gmail.com","8149587579","2016-02-04 16:55:37","5"],["Hitech Institute","0shoaib0@gmail.com","8149587579","2016-02-04 16:55:38","6"],["Hitech Institute","0shoaib0@gmail.com","8149587579","2016-02-04 16:55:40","9"],["fdsf","fds","654545","2016-02-08 13:52:40","12"],["fsdf","fsdfsdfds","546","2016-02-08 13:53:51","13"],["hjgh","hg","3123123","2016-02-08 14:35:31","14"]]} foreach($data-&gt;aaData as $row) { echo $row-&gt;aaData[1]; } </code></pre> <p>Its not working please Help me someone</p>
<php><mysql><json>
2016-02-10 10:44:49
LQ_CLOSE
35,313,244
How to filter invisible files in c#?
<p>I want to find all the invisible files in a folder in C#. I can enumerate the files </p> <pre><code>var files = from file in Directory.EnumerateFiles(@"c:\", "*.txt", SearchOption.AllDirectories) select new { File = file }; </code></pre>
<c#>
2016-02-10 10:55:47
LQ_CLOSE
35,313,395
regular expression for a to z in jquery not working on mvc 5
**my code is look like this. help me** $('#form').validate({ errorElement: "span", // contain the error msg in a span tag errorClass: 'help-block', ignore: "", rules: { CountryName: { required: true, regex: /^[a-zA-Z]+$/ } }, messages: { CountryName:{ required: "Enter Country name", regex: "Enter Correct Country name", }, },
<jquery><regex>
2016-02-10 11:02:35
LQ_EDIT
35,313,747
Passing data with unwind segue
<p>I created two view controllers. I created a segue from the first to the second to pass data. Now I want to pass data from the second view controller to the first one. I went through many similar questions and I'm not able to implement those as I lack the knowledge on how unwinding works. </p> <p><strong>ViewController.swift</strong></p> <pre><code>class ViewController: UIViewController { var dataRecieved: String? @IBOutlet weak var labelOne: UILabel! @IBAction func buttonOne(sender: UIButton) { performSegueWithIdentifier("viewNext", sender: self) } override func prepareForSegue(segue: (UIStoryboardSegue!), sender: AnyObject!) { var svc: viewControllerB = segue.destinationViewController as! viewControllerB svc.dataPassed = labelOne.text } } </code></pre> <p>This will pass the data to dataPassed in view controller "viewControllerB". Say, now I want to pass some data from viewControllerB to dataRecieved in ViewController. How can I do this with only unwind segue and not by using delegate. I'm quite new to swift, would appreciate a detailed explanation.</p>
<ios><swift><segue><unwind-segue>
2016-02-10 11:19:54
HQ
35,314,138
What is the best approach database structure for teacher, students and address table?
<p>I have the following tables in my database</p> <ul> <li>students</li> <li>teachers </li> <li>address</li> </ul> <p>I Want to store basic information about students and teacher in its own table, but the address and contact information in address table. If I store the <code>student_id</code> or <code>teacher_id</code> in address table, the student might have same <code>id</code> as any teacher. If I try to query any teacher address by <code>teacher_id</code>. It will query the student who has the same <code>id</code> as well. </p> <p>So what the best way to figure out this problem? should I create any other table as well or .... </p> <p>Please suggest me an easiest and best approach.</p> <p>thanks.</p>
<php><jquery><mysql><database>
2016-02-10 11:37:11
LQ_CLOSE
35,314,429
hi im new and need a timer in batch
hi im currently working whit batch and made a prank thing (obligates you to close your pc) and an override section for me to get all my coding back so i wanted the person whit the wrong code to have my prank activate in 20 minutes i would like suggestions on how to do it plz :system cls set /p assurance=are you sure you want to do this (I AM NOT RESPONSABLE FOR ANY DAMAGE DONE BY THIS COMMAND IF YOU ACCEPT TO MOVE ON.I WARN YOU THE ONLY WAY TO STOP THIS COMMAND IS RESTART YOUR PC.) echo -accept and move on echo or echo -stop this command pause if %assurance%==accept and move on goto initiate if %assurance%==stop this command goto home :wrong cls echo you have 20 minutes :initiate cls echo KILL CODE ACTIVATED ACTIVATED HAVE FUN!!! :killer start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start start goto killer :override cls echo i need the override code to activate this command. set /p code=code: if %code%==42 is the answer to life but my answer is 2029 goto right if not %code%==42 is the answer to life but my answer is 2029 goto wrong :right
<batch-file>
2016-02-10 11:50:10
LQ_EDIT
35,315,039
How do I write clipboard contents to text file?
<p>I need to write the contents of the clipboard to a text file. I've searched here for an answer but didn't find anything that worked for my situation. Just need a simple example.</p> <p>Thanks in advance...</p>
<.net>
2016-02-10 12:15:52
LQ_CLOSE
35,315,404
Custom init for UIViewController in Swift with interface setup in storyboard
<p>I'm having issue for writing custom init for subclass of UIViewController, basically I want to pass the dependency through the init method for viewController rather than setting property directly like <code>viewControllerB.property = value</code></p> <p>So I made a custom init for my viewController and call super designated init</p> <pre><code>init(meme: Meme?) { self.meme = meme super.init(nibName: nil, bundle: nil) } </code></pre> <p>The view controller interface resides in storyboard, I've also make the interface for custom class to be my view controller. And Swift requires to call this init method even if you are not doing anything within this method. Otherwise the compiler will complain...</p> <pre><code>required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } </code></pre> <p>The problem is when I try to call my custom init with <code>MyViewController(meme: meme)</code> it doesn't init properties in my viewController at all...</p> <p>I was trying to debug, I found in my viewController, <code>init(coder aDecoder: NSCoder)</code> get called first, then my custom init get called later. However these two init method return different <code>self</code> memory addresses.</p> <p>I'm suspecting something wrong with the init for my viewController, and it will always return <code>self</code> with the <code>init?(coder aDecoder: NSCoder)</code>, which, has no implementation.</p> <p>Does anyone know how to make custom init for your viewController correctly ? Note: my viewController's interface is set up in storyboard</p> <p>here is my viewController code:</p> <pre><code>class MemeDetailVC : UIViewController { var meme : Meme! @IBOutlet weak var editedImage: UIImageView! // TODO: incorrect init init(meme: Meme?) { self.meme = meme super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { /// setup nav title title = "Detail Meme" super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) editedImage = UIImageView(image: meme.editedImage) } } </code></pre>
<ios><swift><uiviewcontroller><initialization>
2016-02-10 12:31:34
HQ
35,316,728
Does setting numpy arrays to None free memory?
<p>I have hundreds of really larges matrices, like (600, 800) or (3, 600, 800) shape'd ones.</p> <p>Therefore I want to de-allocate the memory used as soon as I don't really need something anymore.</p> <p>I thought:</p> <pre><code>some_matrix = None </code></pre> <p>Should do the job, or is just the reference set to None but somewhere in the Memory the space still allocated? (like preserving the allocated space for some re-initialization of <code>some_matrix</code> in the future)</p> <p>Additionally: sometimes I am slicing through the matrices, calculated something and put the values into a buffer (a list, because it gets appended all the time). So setting a list to None will definitely free the memory, right?</p> <p>Or does some kind of <code>unset()</code> method exist where whole identifiers plus its referenced objects are "deleted"?</p>
<python><arrays><numpy><memory-management><memory-leaks>
2016-02-10 13:34:28
HQ
35,317,029
How to implement pixel-wise classification for scene labeling in TensorFlow?
<p>I am working on a deep learning model using <strong>Google's TensorFlow</strong>. The model should be used to <strong>segment and label scenes</strong>. </p> <ol> <li>I am using the <strong>SiftFlow dataset</strong> which has <em>33 semantic classes</em> and <em>images with 256x256 pixels</em>. </li> <li>As a result, at my final layer using convolution and deconvolution I arrive at the following tensor(array) <em>[256, 256, 33]</em>. </li> <li>Next I would like to apply <em>Softmax</em> and compare the results to a semantic label of size <em>[256, 256]</em>.</li> </ol> <p><strong>Questions:</strong> Should I apply mean averaging or argmax to my final layer so its shape becomes <em>[256,256,1]</em> and then loop through each pixel and classify as if I were classying <em>256x256</em> instances? If the answer is yes, how, if not, what other options?</p>
<computer-vision><classification><tensorflow><scene><labeling>
2016-02-10 13:49:53
HQ
35,318,121
Glide Cache does not persist when app is killed
<p>I'm monitoring my web calls with Charles.</p> <p>I have a GlideModule changing cache folder by overriding applyOption(...) like this : </p> <pre><code> @Override public void applyOptions(Context context, GlideBuilder builder) { builder.setDiskCache( new InternalCacheDiskCacheFactory(context, "/media/", 1500000) ); } </code></pre> <p>Then, I do my Glide images loads and the cache works just fine while I'm in the app. Here is an example : </p> <pre><code>Glide.with(this) .load("http://www.wired.com/wp-content/uploads/2015/09/google-logo.jpg") .into(mImageView); </code></pre> <p>Only the first call make a web call and then it use cache to retrieve it. However, if I kill the app then relaunch it, instead of continuing to use the cache, the app make a new web call. Isn't the cache supposed to be persistent inside the Internal storage ? </p>
<android><caching><android-glide>
2016-02-10 14:38:37
HQ
35,318,416
Android Center Align Images
I have a very simple html here. It's an email header. My problem is, it displays perfectly on iOS but Android center aligns the logo and the button, when I run an actual email test. Browsers displays it well. It's just email clients where it change. The logo is suppose to be left aligned and the orange button, right aligned. Please help. Code in the fiddle bellow
<android><html><css><html-email>
2016-02-10 14:52:11
LQ_EDIT
35,318,727
Python Questions help. Im lost
Write a program that asks a user how many numbers they wish to process, then ask for that many numbers. Find the total and the maximum of the numbers processed. Example output: Enter the number of values to process: 5 First value: 3 Next value: 9.2 Next value: -2.5 Next value: 0.25 Next value: 6 The total is 15.95 The maximum is 9.20 One thing im lost on is that if if have for num in (1, 3) and num gets assigned multiples values how do I extract both those values
<python>
2016-02-10 15:06:41
LQ_EDIT
35,318,849
How can I get what i'm reading in from a file to an output file
I'm able to pull out the 20 names randomly but how do I store them in a output file rather then displaying them to the screen? I tried filewriter but couldn't get it to work. public class Assignment2 { public static void main(String[] args) throws IOException { // Read in the file into a list of strings BufferedReader reader = new BufferedReader(new FileReader("textfile.txt")); //BufferedWriter bw = new BufferedWriter(new FileWriter("out.txt")); List<String> lines = new ArrayList<String>(); String line = reader.readLine(); while( line != null ) { lines.add(line); line = reader.readLine(); } // Choose a random one from the list Random r = new Random(); FileWriter letters = new FileWriter("out.txt"); for (int i = 0; i < 20; i++) { int rowNum = r.nextInt(lines.size ()); System.out.println(lines.get(rowNum)); } } }
<java>
2016-02-10 15:12:19
LQ_EDIT
35,319,131
Using variables from previous maven phases
<p>I created a mojo intended to just run test cases. In the <code>compile</code> phase of my mojo, the only thing I do is to obtain a list of paths for running dynamic tests with TestNG. However when the test phase is reached, the list has no longer anything inside it.</p> <p>Should I move my mojo's goal execution to another phase? How should be this implementation?</p>
<java><maven><testng>
2016-02-10 15:23:24
LQ_CLOSE
35,319,463
Mean as a window-function in dplyr
<p>I want to calculate group means but save them as a vector next to the raw data. Is there an efficient way to do this in <code>dplyr</code>?</p> <p>Original <code>data.frame</code>: </p> <pre><code>dat &lt;- data.frame( group = c("A","A","A","B","B","B"), value = c(4, 5, 6, 7, 8, 9) ) &gt; dat group value 1 A 4 2 A 5 3 A 6 4 B 7 5 B 8 6 B 9 </code></pre> <p>Desired <code>data.frame</code> with full vector of group means:</p> <pre><code>dat2 &lt;- data.frame( group = c("A","A","A","B","B","B"), value = c(4, 5, 6, 7, 8, 9), groupmeanvalue = c(5, 5, 5, 8, 8, 8) ) &gt; dat2 group value groupmeanvalue 1 A 4 5 2 A 5 5 3 A 6 5 4 B 7 8 5 B 8 8 6 B 9 8 </code></pre>
<r><dplyr>
2016-02-10 15:38:08
LQ_CLOSE
35,319,476
Any way to test EventEmitter in Angular2?
<p>I have a component that uses an EventEmitter and the EventEmitter is used when someone on the page is clicked. Is there any way that I can observe the EventEmitter during a unit test, and use TestComponentBuilder to click the element that triggers the EventEmitter.next() method and see what was sent?</p>
<unit-testing><angular>
2016-02-10 15:38:37
HQ
35,319,597
How to stop/kill a query in postgresql?
<p>This question is while postmaster is running your query in the background, how to kill or stop it?</p> <p>For example, your shell or any frontend may be disconnected due to network issue, you cannot use ctrl-D to kill it but the background postmaster is still running your query. How to kill it?</p>
<postgresql>
2016-02-10 15:43:21
HQ
35,319,680
how to update item from listview in main form to textbox in second form in wondows form aplication in c#?
I create a program for an accountant. I have buttons for add product, delete product, add quantity of products, sell product and profit(count profit from all products in list) and listview for products with columns product, quantity, purchase price and profit. I have problem with button "add quantity of products" my idea is, when I select product in listview and than click on the button "add quantity of products" I want to open a new window (new form) and to pass all the values from selected item from listview to second form, make mathematical calculations with that values and then pass that new values to selected item in first form ie to update select item in list view. How can I resolve that? This is my code: Form1: public string Proi; //Form 3 = Nabavka............................................................................................................ public string Kol; public string Nab; public string Prof; public int Index; private void button3_Click(object sender, EventArgs e) { Form3 form3 = new Form3(); form3.Show(); form3.Hide(); if (listView1.SelectedItems.Count > 0) { this.listView1.Items[0].Focused = true; this.listView1.Items[0].Selected = true; this.Index = listView1.FocusedItem.Index; ListViewItem selectedItem = new ListViewItem(); form3.GetData(listView1.Items[listView1.FocusedItem.Index].SubItems[0].Text, listView1.Items[listView1.FocusedItem.Index].SubItems[1].Text, listView1.Items[listView1.FocusedItem.Index].SubItems[2].Text, listView1.Items[listView1.FocusedItem.Index].SubItems[3].Text); if (form3.ShowDialog() == DialogResult.OK) { this.listView1.SelectedItems[Index].Remove(); Values(form3.Prozz, form3.Kolii, form3.Cenaa, form3.Proff); ListViewItem lvi = new ListViewItem(Proi); lvi.SubItems.Add(Kol); lvi.SubItems.Add(Nab); lvi.SubItems.Add(Prof); this.listView1.Items.Add(lvi); } } } public void Values(string P, string K, string N, string p) { Proi = P; Kol = K; Nab = N; Prof = p; } Form2: public void GetData(string Proi, string Kol, string Cena, string Profit) { textBox1.Text = Kol; textBox2.Text = Cena; textBox3.Text = Profit; textBox6.Text = Proi; } public void SetData(string Proz, string Kol, string NabCena, string Prof) { int x = int.Parse(textBox1.Text); double y = double.Parse(textBox2.Text); double z = double.Parse(textBox3.Text); int a = int.Parse(textBox4.Text); double b = double.Parse(textBox5.Text); int Kolicina = x + a; double sumNabavnaCena = (x * y + a * b) / (x + a); double Profit = z - Kolicina * sumNabavnaCena; Prozz = textBox6.Text; Kolii = Convert.ToString(Kolicina); Cenaa = Convert.ToString(sumNabavnaCena); Proff = Convert.ToString(Profit); } private void textBox3_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Form1 form1 = new Form1(); this.button1.Text = "OK"; this.button1.DialogResult = DialogResult.OK; this.Close(); } } }
<c#><visual-studio><windows-forms-designer>
2016-02-10 15:46:59
LQ_EDIT
35,319,842
Why C doesn't allow implicit conversion from char ** to const char *const * (and C++ does)?
<p>I know implicit conversion from <code>char **</code> to <code>const char **</code> cannot be done and why, and that the conversion to <code>char *const *</code> works. See bottom for links to explanation on that.</p> <p>It all makes sense apart from one particular thing. So I have the following code:</p> <pre><code>#include &lt;stdio.h&gt; void print(const char *const*param) { printf("%s\n", param[0]); } int main(int argc, char **argv) { print(argv); return 0; } </code></pre> <p>If I compile this as a C++ code, it compiles quite fine. However, if the same code is compiled as a C code only, I get an error (well, a warning, but let's suppose <code>-Werror</code>, i.e. treat warnings as errors).</p> <p>gcc:</p> <pre><code>test.c: In function ‘main’: test.c:12:11: warning: passing argument 1 of ‘print’ from incompatible pointer type [-Wincompatible-pointer-types] print(argv); ^ test.c:4:1: note: expected ‘const char * const*’ but argument is of type ‘char **’ print(const char *const*param) ^ </code></pre> <p>clang:</p> <pre><code>test.c:12:11: warning: passing 'char **' to parameter of type 'const char *const *' discards qualifiers in nested pointer types [-Wincompatible-pointer-types-discards-qualifiers] print(argv); ^~~~ test.c:4:25: note: passing argument to parameter 'param' here print(const char *const*param) ^ </code></pre> <p>Both behaviours are standard-independent and also compiler-independent. I tried various standards with both <code>gcc</code> and <code>clang</code>.</p> <p>There are two reasons for this inquiry. Firstly, I want to understand whether there is a difference and, secondly, I have a function that does nothing with any layer of the pointers and I need it to be able to work with <code>const char **</code> as well as <code>char *const *</code> and <code>char **</code>. Explicitly casting each call is not maintainable. And I have no idea how should the function prototype look like.</p> <hr> <p>This is the question that started my curiosity: <a href="https://stackoverflow.com/questions/7016098/implicit-conversion-from-char-to-const-char">Implicit conversion from char** to const char**</a></p> <p>And here is another nice explanation for the <code>char ** =&gt; const char**</code> problem: <a href="http://c-faq.com/ansi/constmismatch.html">http://c-faq.com/ansi/constmismatch.html</a></p> <p>If the links are confusing related to this question, feel free to edit them out.</p>
<c++><c><gcc><clang><constants>
2016-02-10 15:55:10
HQ
35,320,365
Using a GPU both as video card and GPGPU
<p>Where I work, we do a lot of numerical computations and we are considering buying workstations with NVIDIA video cards because of CUDA (to work with TensorFlow and Theano).</p> <p>My question is: should these computers come with another video card to handle the display and free the NVIDIA for the GPGPU?</p> <p>I would appreciate if anyone knows of hard data on using a video card for display and GPGPU at the same time.</p>
<gpu><gpgpu><theano><tensorflow>
2016-02-10 16:16:26
HQ
35,320,438
How to generate pdf report using thymeleaf as template engine?
<p>I want to create pdf report in a spring mvc application. I want to use themeleaf for designing the html report page and then convert into pdf file. I don't want to use xlst for styling the pdf. Is it possible to do that way? </p> <p>Note: It is a client requirement. </p>
<java><spring><pdf><thymeleaf>
2016-02-10 16:19:51
HQ
35,320,568
Mockito - separately verifying multiple invocations on the same method
<pre><code>import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.verify; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; public class MockitoTest { public static class TestMock { public void doIt(String s) { } } public static void main(String[] args) { TestMock mock = Mockito.mock(TestMock.class); mock.doIt("1"); mock.doIt("2"); ArgumentCaptor&lt;String&gt; argument = ArgumentCaptor.forClass(String.class); verify(mock, atLeastOnce()).doIt(argument.capture()); System.out.println(argument.getValue()); verify(mock, atLeastOnce()).doIt(argument.capture()); System.out.println(argument.getValue()); } } </code></pre> <p>I expected this to print <code>1 2</code> but it instead prints <code>2 2</code>. It seems the '1' invocation is lost. Is there a way that I can verify that verifications happened with <code>1</code> and then <code>2</code>?</p>
<java><mockito>
2016-02-10 16:25:04
HQ
35,320,925
Split a string in C#
<p>I have a string contains text "<strong>AA55BB10CC1DD10E123</strong>". I have to split the string and place it in List as text / value field like </p> <p>AA | 55</p> <p>BB | 10</p> <p>CC | 1</p> <p>DD | 10</p> <p>E | 123</p> <p>Thanks</p>
<c#><model-view-controller>
2016-02-10 16:39:38
LQ_CLOSE
35,321,004
MongoDB query $in with regex array of element
<p>Ok i am trying to implement a query, which is trying to perform regex search ( which contains an array list ) on a bunch of document</p> <p>Its hard for me to explain...so I am basically coming to direct point.</p> <p>There is query which works with regex array...</p> <pre><code>db.paper.find({"category": {$in: [ /xd/, /sd/, /ad/ ] }}) </code></pre> <p>There is query which doesn't works with regex array...</p> <pre><code>db.paper.find({"category": {$in: [ "/xd/", "/sd/", "/ad/" ] }}) </code></pre> <p>So basically what I want is remove "" sign from string array...so that i can perform below query..</p> <pre><code>var sea = [ "/xd/", "/sd/", "/ad/" ]; db.paper.find({"category": {$in: sea }}); </code></pre>
<arrays><regex><mongodb>
2016-02-10 16:43:23
HQ
35,321,334
javascript/HTML mouseover vs. "component-under"
I have some HTML (generated by jsf) that includes images. The user trigger some changes (ajax-calls) when clicking on an image or by pressing a key. To keep track of the latest image-component (client-side), I use javascript and onmouseover, assigning the img-id to a javascript-variable which in turn is used to fill the ajax-calls. Everything works well (even it there might be better ways to do it), but sometimes it takes some time to refresh the image. For a moment, the place is empty, the next-to-right picture *jumps* left, getting under the mouse pointer, triggering the mouseover event. Worse, when the original image is displayed, it fails to trigger the mouseover, so the next operation will get the wrong image a argument. I don't think this has to do with jsf and ajax but could also happen with plain HTML and javascript, so I'm not adding tags jsf nor ajax. Question is: how can I prevent this *unwanted feature*?
<javascript><html><onmouseover>
2016-02-10 16:58:37
LQ_EDIT
35,322,298
Does bash have a way to un-export a variable without unsetting it?
<p>Is it possible to <code>export</code> a variable in Bash, then later un-export it, without unsetting it entirely? I.e. have it still available to the current shell, but not to sub-processes.</p> <p>You can always do this, but it's ugly (and I'm curious):</p> <pre><code>export FOO #... _FOO=$FOO unset FOO FOO=$_FOO </code></pre> <p>Answers about other shells also accepted.</p>
<bash><shell><unix><sh><environment>
2016-02-10 17:44:41
HQ
35,322,846
How to read/parse Content from OkNegotiatedContentResult?
<p>In one of my API actions (<code>PostOrder</code>) I <em>may</em> be consuming another action in the API (<code>CancelOrder</code>). Both return a JSON formatted <code>ResultOrderDTO</code> type, set as a <code>ResponseTypeAttribute</code> for both actions, which looks like this:</p> <pre><code>public class ResultOrderDTO { public int Id { get; set; } public OrderStatus StatusCode { get; set; } public string Status { get; set; } public string Description { get; set; } public string PaymentCode { get; set; } public List&lt;string&gt; Issues { get; set; } } </code></pre> <p>What I need is reading/parsing the <code>ResultOrderDTO</code> response from <code>CancelOrder</code>, so that I can use it as response for <code>PostOrder</code>. This is what my <code>PostOrder</code> code looks like:</p> <pre><code>// Here I call CancelOrder, another action in the same controller var cancelResponse = CancelOrder(id, new CancelOrderDTO { Reason = CancelReason.Unpaid }); if (cancelResponse is OkNegotiatedContentResult&lt;ResultOrderDTO&gt;) { // Here I need to read the contents of the ResultOrderDTO } else if (cancelResponse is InternalServerErrorResult) { return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new ResultError(ErrorCode.InternalServer))); } </code></pre> <p>When I use the debugger, I can see that the <code>ResultOrderDTO</code> it is there <em>somewhere</em> in the response (looks like the <code>Content</code>) as shown in the pic below:</p> <p><a href="https://i.stack.imgur.com/dqXJT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dqXJT.png" alt="Debugger"></a></p> <p>but <code>cancelResponse.Content</code> does not exist (or at least I don't have access to it before I cast my response to something else) and I have no idea about how to read/parse this <code>Content</code>. Any idea?</p>
<c#><asp.net><api><asp.net-web-api><asp.net-web-api2>
2016-02-10 18:12:34
HQ
35,323,174
What are the advantages of @ControllerAdvice over @ExceptionHandler or HandlerExceptionResolver for handling exceptions?
<p><strong>Spring 3.2</strong> introduced <code>@ControllerAdvice</code> annotation for handling exceptions in a Spring MVC application. But prior to this version Spring had <code>@ExceptionHandler</code> or <code>HandlerExceptionResolver</code> to handling exceptions in a Spring MVC application. Then why <strong>Spring 3.2</strong> introduced <code>@ControllerAdvice</code> annotation for handling exceptions? I strongly believe that <strong>Spring 3.2</strong> introduced <code>@ControllerAdvice</code> annotation <strong><em>to address the limitations of</em></strong> <code>@ExceptionHandler</code> or <code>HandlerExceptionResolver</code> or make the <strong><em>exceptions handling more stronger</em></strong>.</p> <p>Can any one explain the advantages of <code>@ControllerAdvice</code> over <code>@ExceptionHandler</code> or <code>HandlerExceptionResolver</code> for handling exceptions?</p>
<java><spring><spring-mvc><exception-handling>
2016-02-10 18:30:54
HQ
35,324,053
Full screen IOS
<p>I just started on Xcode, and i have a little problem I would like to display the application on the entire screen</p> <p><a href="http://i.stack.imgur.com/NyXJ1.jpg" rel="nofollow">enter image description here</a></p>
<ios><iphone><display>
2016-02-10 19:19:27
LQ_CLOSE
35,325,103
Docker error when pulling Java 8 image - "failed to register layer"
<p>I am trying to pull the latest official Java docker image (java:8), but I keep getting a <code>failed to register layer</code> error. The Java 7 and 9 docker images download successfully. I am running OS X El Capitan version 10.11.1.</p> <pre><code>&gt; docker -v Docker version 1.10.0, build 590d5108 &gt; docker-machine -v docker-machine version 0.6.0, build e27fb87 &gt; docker pull java:8 8: Pulling from library/java 03e1855d4f31: Extracting [==================================================&gt;] 51.36 MB/51.36 MB a3ed95caeb02: Download complete 9269ba3950bb: Download complete 6ecee6444751: Download complete 5b865d39f77d: Download complete e7e5c0273866: Download complete 6a4effbc4451: Download complete 4b6cb08bb4bc: Download complete 7b07ad270e2c: Download complete failed to register layer: rename /mnt/sda1/var/lib/docker/image/aufs/layerdb/tmp/layer-273420626 /mnt/sda1/var/lib/docker/image/aufs/layerdb/sha256/78dbfa5b7cbc2bd94ccbdba52e71be39b359ed7eac43972891b136334f5ce181: directory not empty </code></pre> <p>Has anyone run across a similar error and successfully resolved it? Thanks</p>
<java><docker>
2016-02-10 20:20:11
HQ
35,325,195
Should I store function references in Redux store?
<p>I'm trying to build <strong>keyboard shortcut support</strong> into my React/Redux app in an <strong>idiomatic React/Redux way</strong>. The way I am planning to do this is to have the following action creator and associated action:</p> <pre><code>registerShortcut(keyCode, actionCreatorFuncReference) </code></pre> <p>The reducer would then update a registeredShortcuts object in the redux store with a mapping of keyCodes to actionCreatorFuncReferences. Then my root component would listen for keyup and see if there is an associated keyCode registered and if so, then dispatch the mapped action via the action creator function reference.</p> <p>However, this would be the first time I am <strong>storing function references in my Redux store</strong>. To date I've only had objects with keys with vanilla values (strings, ints, etc).</p> <p>The Redux docs says "You should do your best to keep the state serializable. Don’t put anything inside it that you can’t easily turn into JSON.". <strong>Does this suggest it's a bad idea to store such function references in my Redux store?</strong> If so, what is a better way to accomplish what I'm trying to do in React/Redux?</p> <p>An alternative approach is just to store the mapping of keyCodes and function references in the root react component itself, but that didn't feel very Redux-like since now application state is not in the Redux store.</p>
<redux>
2016-02-10 20:24:42
HQ
35,325,444
Try deserialize to object
<p>I have serializaed objects of different types as strings in sql table.</p> <p>Now need to deserialize them without knowing what type is the object. </p> <p>I am looking for sth like TryDeserializeToObject trying with different types.</p> <p>Offcourse I could use try catch, is there any better way ? </p>
<c#>
2016-02-10 20:39:16
LQ_CLOSE
35,325,785
I'm trying to create a program that creates anagrams from a string of words
<p>I'm new to python - so from a list of predetermined words jumble the letters and return the jumbled letters.</p>
<python><anagram>
2016-02-10 20:59:22
LQ_CLOSE
35,326,076
How does the prim's algorithm run when compared with Kruskal's algorithm in terms of efficiency?
<p>I would like to know how Prim's algorithm stand against Kruskal's algorithm in terms of efficiency</p>
<java><c#>
2016-02-10 21:17:29
LQ_CLOSE
35,326,558
How do I search for a pip package by name only?
<p>By default pip searches both package names and descriptions. For some packages this results in a huge number of spurious hits and finding the one I actually want is a pain.</p> <p>How I tell pip I want to search by name only?</p>
<pip>
2016-02-10 21:45:37
HQ
35,327,186
I have to set a heading to the font-family "Cooper Black" but it never actually goes to it.
<p>I'm submitting the gist I have of it with the questions as well. It is specifically question 8 on the full blown assignment. <a href="https://gist.github.com/JStrong0037/67c1a09ccd1943be84f4" rel="nofollow">This</a> is the gist with all my code, but I used the line, font-family: 'Cooper Black', serif; which isn't working. </p> <p>I feel pretty dumb that no matter what I've tried it never works for me. I've tried Chrome, Firefox, and Edge all three when opening this. I'm actually getting desperate to find the cause of the problem or what I'm doing wrong.</p> <p>Thanks for any help you guys can give me!</p>
<css>
2016-02-10 22:25:10
LQ_CLOSE
35,327,679
Validate or remove for extra fields in laravel
<p>It's posible to validate request with rules for additional fields, or remove that fields from request?</p> <p>Simple example, I have FormRequest object with rules:</p> <pre class="lang-php prettyprint-override"><code>public function rules() { return [ 'id' =&gt; 'required|integer', 'company_name' =&gt; 'required|max:255', ]; } </code></pre> <p>And when I get post request with any other fields I want to get error/exception in controller or I want to get only id and company_name fields, with no any others. It's exist any feature in laravel with that, or I must make it in my way?</p>
<php><forms><laravel>
2016-02-10 22:59:18
HQ
35,328,056
React-Redux: Should all component states be kept in Redux Store
<p>Say I have a simple toggle:</p> <p> </p> <p>When I click the button, the Color component changes between red and blue</p> <p>I might achieve this result by doing something like this.</p> <p>index.js</p> <pre><code>Button: onClick={()=&gt;{dispatch(changeColor())}} Color: this.props.color ? blue : red </code></pre> <p>container.js</p> <pre><code>connect(mapStateToProps)(indexPage) </code></pre> <p>action_creator.js</p> <pre><code>function changeColor(){ return {type: 'CHANGE_COLOR'} } </code></pre> <p>reducer.js</p> <pre><code>switch(){ case 'CHANGE_COLOR': return {color: true} </code></pre> <p>but this is a hell of a lot of code to write for something that I could have achieved in 5 seconds with jQuery, some classes, and some css...</p> <p>So I guess what I'm really asking is, what am I doing wrong here?</p>
<javascript><reactjs><redux>
2016-02-10 23:30:24
HQ
35,328,468
How to make a GUI in Julia?
<p>I'm new at programming in Julia and I need to create a GUI. I've been looking for information and I can't find anything useful. I tried to search information in the Julia official web page, but it seems to be down. I wonder if any of you guys knows where I can find information about it.</p>
<user-interface><julia>
2016-02-11 00:08:32
HQ
35,329,122
Find duplicates and delete all in notepad++
<p>I have multiple email addresses. I need to find and delete all (including found one). Is this possible in notepad++?</p> <p>example:<code>epshetsky@test.com, rek4@test.com, rajesh1239@test.com, mohanraj@test.com, sam@test.com, nithin@test.com, midhunvintech@test.com, karthickgm27@test.com, rajesh1239@test.com, mohanraj@test.com, nithin@test.com,</code></p> <p>I need results back like</p> <p><code>epshetsky@test.com, rek4@test.com, sam@test.com, nithin@test.com, midhunvintech@test.com, karthickgm27@test.com,</code></p> <p>How to do in notepad++?</p>
<notepad++><text-editor>
2016-02-11 01:15:44
HQ
35,329,166
Creating and using an Elixir helpers module in Phoenix
<p>I have a group of acceptance tests I've created in my faux blog phoenix app. There's some duplicated logic between them I'd like to move to a helpers module to keep things DRY. </p> <p>Here is the directory structure:</p> <pre><code>test/acceptance/post ├── create_test.exs ├── delete_test.exs ├── helpers.exs ├── index_test.exs └── update_test.exs </code></pre> <p>The <code>helpers.exs</code> file is where I'd like to stick the duplicated acceptance test logic. It looks something like:</p> <pre class="lang-rb prettyprint-override"><code>defmodule Blog.Acceptance.Post.Helpers do def navigate_to_posts_index_page do # some code end end </code></pre> <p>Then in one of my test files, say <code>index_test.exs</code>, I'd like to import the helpers module to use it's methods:</p> <pre class="lang-rb prettyprint-override"><code>defmodule Blog.Acceptance.Post.IndexTest do import Blog.Acceptance.Post.Helpers end </code></pre> <p>However, I'm getting this error:</p> <blockquote> <p>** (CompileError) test/acceptance/post/index_test.exs:7: module Blog.Acceptance.Post.Helpers is not loaded and could not be found</p> </blockquote> <p>How do I get access to or load the helper module in my test files?</p>
<elixir><phoenix-framework>
2016-02-11 01:20:55
HQ
35,329,532
Hello. I am working at a vending machine software. I cannot get the if statement to work. It just simply ignores it
// Program.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int main() { char number; cout << "Hello. Please choose a drink type ! \n\n1.Coca-Cola \n2.Coca-Cola ZERO \n3.Pepsi\n" ; cin >> number; if (number == 1) cout << "Please tip in 8$"; }
<c++>
2016-02-11 02:02:55
LQ_EDIT
35,329,850
Excel VBA, code to count the # of filled cells, then find highest and 2nd highest and subtract the corresponding column #'s
<p>I'm looking to count the # of items in a list from A11 to A90. And if that number is even subtract the max value from the 2nd max and then 3rd max from 4th max, etc.. If it's odd then it would start at the 2nd max minus the 3rd, and 4th to 5th etc.. Until all numbers have been subtracted from their counterpart. The tricky part is that the numbers which need to be subtracted are in a different column, C11 to C90. </p> <p>I'm basically trying to find the number of consecutive negative outcomes from column C using the 2 closest values from column A. </p> <p>Any input would be greatly appreciated!!</p>
<vba><excel>
2016-02-11 02:38:28
LQ_CLOSE
35,329,962
File Upload in Elm
<p>How does one upload a file (image or excel) in Elm? </p> <p>Can't seem to find any examples.</p> <p>The answer is fine even if the native code is used. Have seen <code>Data</code> in <code>Elm-Html</code> but it appears files and blobs are not supported. What is the way around this?</p>
<elm>
2016-02-11 02:52:17
HQ
35,330,015
Error in a selection sort c++
I have this action for order array in sort selection method, but this code dont order my array correctly void selectionsort(int* b,int size) { int i, k,menor,posmenor; for(i=0;i<size-1;i++) { posmenor=i; menor=b[i]; for(k=i+1;k<size;k++) { if(b[k]<menor) { menor=b[k]; posmenor=k; } } b[posmenor]=b[i]; b[i]=menor; } } I Dont found the error. Im newbie in c++ Thanks for help.
<c++><arrays><algorithm><sorting>
2016-02-11 02:58:04
LQ_EDIT
35,330,066
django 1.9 createsuperuser bypass the password validation checking
<p>Try to work on the new django 1.9 version, and create a super user by this: </p> <pre><code>python manage.py createsuperuser </code></pre> <p>And I just want to use a simple password for my local development environment, like only one character, django1.9 upgrade to a very strict password validation policy, how can I bypass it?</p> <pre><code>Password: Password (again): This password is too short. It must contain at least 8 characters. This password is too common. This password is entirely numeric. </code></pre>
<django><passwords>
2016-02-11 03:03:40
HQ
35,332,464
currentTime() in video js
The following is my code which is not working. Any help would be appreciated. var myPlayer; videojs("example_video_1").ready(function(){ myPlayer = this; if(myPlayer.currentTime()>3) { alert("STARTED"); }); });
<video.js>
2016-02-11 06:40:31
LQ_EDIT
35,332,614
perl code to find sum and average of specific columns
i want to calculate the average over all itemsX (where X is a digit) for each row in perl using windows i have file in format <p>id1 item1 cart1 id2 item2 cart2 id3 item3 cart3</p> <p>0 11 34 1 22 44 2 44 44</p> <p>1 44 44 55 66 34 45 55 33</p> want to find sum of item blocks and there average Any help in this regard thanks in anticipation
<perl>
2016-02-11 06:50:11
LQ_EDIT
35,333,848
how to use array_push()
<p>I want to push new data in array which each value of them.</p> <pre><code>$array = array("menu1" =&gt; "101", "menu2" =&gt; "201"); array_push($array, "menu3" =&gt; "301"); </code></pre> <p>But I got an error syntax.</p> <p>And if I use like this :</p> <pre><code>$array = array("menu1" =&gt; "101", "menu2" =&gt; "201"); array_push($array, "menu3", "301"); result is : Array ( [menu1]=&gt;101 [menu2]=&gt;201 [0]=&gt;menu3 [1]=&gt;301 ) My hope the result is : Array ( [menu1]=&gt;101 [menu2]=&gt;201 [menu3]=&gt;301 ) </code></pre> <p>I want push new [menu3]=>'301' but I dont know how. Please help me, the answer will be appreciate</p>
<php><arrays>
2016-02-11 08:07:15
LQ_CLOSE
35,337,493
Parse Server: hosting MongoDB on AWS vs hosting on MongoLab
<p>AWS published a <a href="http://mobile.awsblog.com/post/TxCD57GZLM2JR/How-to-set-up-Parse-Server-on-AWS-using-AWS-Elastic-Beanstalk" rel="nofollow" title="blog post">blog post</a> about migrating from Parse. I wonder why they suggest hosting MongoDB on MongoLab instead of hosting it directly on AWS?</p> <p>What's the advantage of hosting MongoDB on MongoLab? </p>
<mongodb><amazon-web-services><parse-platform><mlab>
2016-02-11 10:59:47
LQ_CLOSE
35,337,524
How can i add inline style in JS code?
Is it possible to style inline the div ".trigger" on the following code and set its display to block ? $('.trigger').toggle(function(){ $('.greendiv').animate({'height': '300px', 'width': '400px'}, 200); }, function(){ $('.greendiv').animate({'height': '200px', 'width': '200px'}, 200); });
<javascript><jquery><css>
2016-02-11 11:01:37
LQ_EDIT
35,337,726
Can anyone give a simple code for houghlines using C#? As i got the transform, i want to detect the lines in images
Heloo all, Can anyone give me a simple code for houghlines in c# since i am new to .net,i didnt know how to do hough transform.Then i found the code for Hough transform but i need to detect the lines in images. for that theta and rho value is needed.
<c#>
2016-02-11 11:10:43
LQ_EDIT
35,338,072
How to create web-services in Zend Framework 2?
<p>How to create web services over HTTP REST protocol using Zend Framework 2 (third party)</p> <p>We use this code in Zend Framework 1 :</p> <pre><code> &lt;?php function methodName($name) { echo "Hello world - $name"; } $server = new Zend_Rest_Server(); $server-&gt;addFunction('methodName'); $server-&gt;handle(); ?&gt; </code></pre> <p>An example code will be useful.</p>
<php><zend-framework2>
2016-02-11 11:27:08
LQ_CLOSE
35,340,179
Scanner in a while loop
<p>I'm a beginner in java but I have worked c++ before in c++ we can code like this :</p> <pre><code>int num; while (cin&gt;&gt;num){ .... } </code></pre> <p>now I wonder how to do that in java.</p>
<java><while-loop><java.util.scanner>
2016-02-11 13:06:11
LQ_CLOSE
35,340,359
Following Java Tutorial - Need hep with errors
I've been following a java tutorials who has began learning via Sam's teach yourself java and although I have copied this to ensure I can run it before I begin to change and make it my own, it will not run and I am not sure why. I would appreciate if one of you guys/girls could help. I've put my java classes in the correct packages, but it doesn't run. Thanks. <!-- begin snippet: js hide: false --> <!-- language: lang-html --> package com.jackson.ecommerce; import java.util.*; public class Item implements Comparable { private String id; private String name; private double retail; private int quantity; private double price; Item(String idIn, String nameIn, String retailIn, String quanIn) { id = idIn; name = nameIn; retail = Double.parseDouble(retailIn); if (quantity > 400) price = retail * 5D; else if (quantity > 200) price = retail * .6D; else price = retail * .7D; price = Math.floor( price * 100 + .5) / 100; } public int compareTo(Object obj) { Item temp = (Item)obj; if (this.price < temp.price) return 1; return 0; } public String getId(){ return id; } public String getName(){ return name; } public double GetRetail(){ return retail; } public int getQuantity(){ return quantity; } public double getPrice(){ return price; } } <!-- end snippet --> <!-- begin snippet: js hide: false --> <!-- language: lang-html --> package com.jackson.ecommerce; import java.util.*; public class Storefront { private LinkedList catalog = new LinkedList(); public void addItem(String id, String name, String price, String quant){ Item it = new Item(id, name, price, quant); catalog.add(it); } public Item getItem(int i){ return (Item)catalog.get(i); } public int getSize(){ return catalog.size(); } public void sort() { Collections.sort(catalog); } <!-- end snippet --> <!-- begin snippet: js hide: false --> <!-- language: lang-html --> package Package1; import com.jackson.ecommerce.*; public class Giftshop { public static void main(String[] arguments){ Storefront store = new Storefront(); store.addItem("C01", "MUG, "9.99", "150"); store.addItem("C02", "LG MUG", "12.99", "82"); store.addItem(“C03”, “MOUSEPAD”, “10.49”, “800”); store.addItem(“D01”, “T SHIRT”, “16.99”, “90”); store.sort()); for (int i = 0; i < store.getSize(); i++) { Item show = (Item)store.getItem(i); System.out.println( show.getId() + show.getName() + show.getRetail() + show.getPrice() + show.getQuantity()); } } } <!-- end snippet -->
<java>
2016-02-11 13:14:31
LQ_EDIT
35,341,943
Executing program gives int cannot be converted into java.lang.string
<p>I am currently using BlueJ (forced to by the module tutor, I hate it) and I'm having an error come up every time I attempt to execute the code.</p> <blockquote> <p>incompatible types: java.lang.String cannot be converted into int</p> </blockquote> <p>My code is as follows:</p> <pre><code>public class middle { public static void main (String[] args) { String numeroUno = args[0]; String numeroDos = args[1]; String numeroTres = args[2]; double num1 = Double.parseDouble(args[0]); double num2 = Double.parseDouble(args[1]); double num3 = Double.parseDouble(args[2]); middle(num1, num2, num3); } public static void middle(double n1, double n2, double n3) { double [] values = {n1, n2, n3}; double newarr; boolean sorted = false; while(!sorted) { sorted = true; for(int i=0; i&lt;values.length-1; i++) { if(values[i] &gt; values[i+1]) { double swapsies = values[i+1]; values[i+1] = values[i]; values[i] = swapsies; sorted = false; } } } System.out.print(values[1] + " is between " + values[0] + " and " + values[2]); } } </code></pre> <p>Firstly my question is where have I made the error, but secondly, is there another way to structure this code i.e completely rewrite it to achieve the same thing. I'm not really used to writing code this way and I'm having a hard time with OOP. The object of this particular exercise is to write code that will return the middle value number from what the user has input.</p> <p>Thanks!</p>
<java><oop><bluej>
2016-02-11 14:25:33
LQ_CLOSE
35,343,083
how can we display long length integer values in UILabels in ios
Hi i am very new for Ios and in my app i am integrating services and after getting response from service i am storing that values in Array-list when i load that array list values in tableList showing exception like _Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0x7d7ca000' McoIdArray:-( 106314100491, 106314100492, 106314100493, 106314100494, 106314100495 ) -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *simpleTableIdentifier = @"MyCell"; Cell = (CoridersCell *)[tableList dequeueReusableCellWithIdentifier:simpleTableIdentifier]; if (Cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CoridersCell" owner:self options:nil]; Cell = [nib objectAtIndex:0]; } Cell.mcoId.text = [McoIdArray objectAtIndex:indexPath.row]; return Cell; }
<ios><objective-c>
2016-02-11 15:15:56
LQ_EDIT
35,343,090
how to keep opened developer tools while running a selenium nightwatch.js test?
<p>I am starting to write e2e tests using nightwatch.js and I noticed some errors that I would like to inspect manually in the target browser's console (developer tools). but always when I open the developer console, it is automatically closed by the browser. is this a intended feature of either selenium or nightwatch.js, and, if it is the case, how can I disable it? </p>
<selenium-webdriver>
2016-02-11 15:16:12
HQ
35,343,525
How do I order fields of my Row objects in Spark (Python)
<p>I'm creating Row objects in Spark. I do not want my fields to be ordered alphabetically. However, if I do the following they are ordered alphabetically.</p> <pre><code>row = Row(foo=1, bar=2) </code></pre> <p>Then it creates an object like the following:</p> <pre><code>Row(bar=2, foo=1) </code></pre> <p>When I then create a dataframe on this object, the column order is going to be bar first, foo second, when I'd prefer to have it the other way around.</p> <p>I know I can use "_1" and "_2" (for "foo" and "bar", respectively) and then assign a schema (with appropriate "foo" and "bar" names). But is there any way to prevent the Row object from ordering them?</p>
<python><apache-spark><pyspark><apache-spark-sql><pyspark-sql>
2016-02-11 15:33:39
HQ
35,343,557
Can anyone explain how this recursion code works exactly and what happens in the programs stack or in memory step by step?
<p>Here is my code:</p> <pre><code>#include &lt;stdio.h&gt; void fun(int n) { if(n &gt; 0) { fun(n-1); printf("%d ", n); fun(n-1); } } int main() { fun(4); return 0; } </code></pre> <p>and the output of this code is <code>1 2 1 3 1 2 1 4 1 2 1 3 1 2 1</code>. But I can't understand what happens exactly between to recursive calls, When the print statement will be executed and what is the value of <code>n</code> at every call. I'm beginner in coding please explain step by step. </p>
<c><recursion>
2016-02-11 15:35:13
LQ_CLOSE
35,344,981
Posting to a Web API using HttpClient and Web API method [FromBody] parameter ends up being null
<p>I am attempting to POST to a Web API using the HttpClient. When I put a breakpoint in the Save method of the Web API the [FromBody] Product is null. This means that something is wrong with the way I am posting the product over to the Web API. Can someone please take a look at the below code and see where I might be going wrong. I am assuming it is something to do with headers and content types.</p> <p><strong>POST call from a client repository to the Web API which should pass the product object through as JSON:</strong></p> <pre><code>public async Task&lt;Product&gt; SaveProduct(Product product) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:99999/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); StringContent content = new StringContent(JsonConvert.SerializeObject(product)); // HTTP POST HttpResponseMessage response = await client.PostAsync("api/products/save", content); if (response.IsSuccessStatusCode) { string data = await response.Content.ReadAsStringAsync(); product = JsonConvert.DeserializeObject&lt;Product&gt;(data); } } return product; } </code></pre> <p><strong>Web API Controller Method:</strong></p> <pre><code>[HttpPost] [Route("save")] public IActionResult Save([FromBody]Product product) { if (customer == null) { return HttpBadRequest(); } _manager.SaveCustomer(product); return CreatedAtRoute("Get", new { controller = "Product", id = product.Id }, product); } </code></pre> <p>[FromBody] Product product parameter ends up being null.</p>
<c#><asp.net><asp.net-web-api><httpclient>
2016-02-11 16:37:57
HQ
35,345,520
Detach ItemTouchHelper from RecyclerView
<p>I have a RecyclerView with a working ItemTouchHelper. Everything works great, but I am wondering if there is a way I can detach the ItemTouchHelper from the RecyclerView without re-creating the list? For fun, this is the code I'm using to attach:</p> <pre><code>ItemTouchHelper.Callback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) { ... }; mItemTouchHelper = new ItemTouchHelper(callback); mItemTouchHelper.attachToRecyclerView(mPasswordList); </code></pre> <p>Ideally, I'd like to check a preference in say <code>onResume()</code> of the Activity this RecyclerView lives in and detach the ItemTouchHelper based on that.</p>
<android>
2016-02-11 17:01:30
HQ
35,345,747
PHP Notice: Undefined variable: str in
<p>My code</p> <pre><code>function rand_string($length) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $size = strlen( $chars ); for( $i = 0; $i &lt; $length; $i++ ) { $str .= $chars[ rand( 0, $size - 1 ) ]; // this line error } return $str; } </code></pre> <p>Error</p> <blockquote> <p>PHP Notice: Undefined variable: str in ... on line 5 </p> </blockquote>
<php>
2016-02-11 17:10:57
LQ_CLOSE
35,345,834
Android Json and AsyncTask Error
<p>i had written an code that sends data from the android application to the database using JSON Form but i am having some errors when it sends.</p> <p>this is the class for registration:</p> <pre><code>package com.subhi.tabhost; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.regex.Pattern; import AddUser.AllUsersLoadSpinner; import ConnectionDetector.ConnectionDetector; import SpinnerFirstLoad.MultiSelectionSpinner; import SpinnerFirstLoad.PlayersLoadSpinner; import SpinnerFirstLoad.TeamsLoadSpinner; public class Registeration extends AppCompatActivity { ConnectionDetector connectionDetector; private MultiSelectionSpinner multiSelectionSpinner; private MultiSelectionSpinner PlayersSelectSpinier; Button save; TextView name, email, userexists; ArrayList&lt;String&gt; TeamsList = new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; UsersList = new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; PlayersList = new ArrayList&lt;String&gt;(); public static final String MyPREFERENCES = "MyPrefs"; public static final String Name = "nameKey"; public static final String EMAIL = "emailKey"; SharedPreferences sharedpreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registeration); sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); String restoredText = sharedpreferences.getString(Name, null); /* if (restoredText != null) { // Intent intent = new Intent(getApplicationContext(), MainMenu.class); //startActivity(intent); // finish(); }*/ sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE); // if (connectionDetector.isConnectingToInternet()) { name = (TextView) findViewById(R.id.name); email = (TextView) findViewById(R.id.email); userexists = (TextView) findViewById(R.id.btnLinkToLoginScreen); save = (Button) findViewById(R.id.btnRegister); multiSelectionSpinner = (MultiSelectionSpinner) findViewById(R.id.mySpinner); PlayersSelectSpinier = (MultiSelectionSpinner) findViewById(R.id.mySpinner2); TeamsLoadSpinner x1 = new TeamsLoadSpinner(this); x1.execute("http://192.168.1.106/add/index.php"); AllUsersLoadSpinner allUsersLoadSpinner = new AllUsersLoadSpinner(this); allUsersLoadSpinner.execute("http://192.168.1.106/add/allusers.php"); PlayersLoadSpinner x2 = new PlayersLoadSpinner(this); x2.execute("http://192.168.1.106/add/print.php"); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { InsertData adduser = new InsertData(); String txtname = name.getText().toString(); String txtemail = email.getText().toString(); if (txtname.equals("")) Toast.makeText(getApplicationContext(), "UserName Cannot Be Empty", Toast.LENGTH_LONG).show(); else { if (txtemail.equals("")) Toast.makeText(getApplicationContext(), "Email Cannot Be Empty ", Toast.LENGTH_LONG).show(); else { if (isValidEmail(txtemail)) { boolean x = false; for (int i = 0; i &lt; UsersList.size(); i++) { if (UsersList.get(i).equals(txtname)) { x = true; } } if (x == false) { SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putString(Name, txtname); editor.putString(EMAIL, txtemail); editor.commit(); adduser.execute("192.168.1.106/add/add.php", txtname, txtemail, multiSelectionSpinner.getSelectedItemsAsString(), PlayersSelectSpinier.getSelectedItemsAsString()); } else { //Toast.makeText(getApplicationContext(),"USER EXISTS",Toast.LENGTH_LONG).show(); userexists.setText("User Alerady Exists, Please Choose Differnent User name "); } } else Toast.makeText(getApplicationContext(), "Please Enter A valid Email", Toast.LENGTH_LONG).show(); } } } }); // }else { // Internet connection is not present // Ask user to connect to Internet // showAlertDialog(Registeration.this, "No Internet Connection", // "You don't have internet connection.", false); // } } public void showAlertDialog(final Context context, String title, String message, Boolean status) { AlertDialog alertDialog = new AlertDialog.Builder(context).create(); // Setting Dialog Title alertDialog.setTitle(title); // Setting Dialog Message alertDialog.setMessage(message); // Setting alert dialog icon alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail); // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); // Showing Alert Message alertDialog.show(); } private boolean isValidEmail(String email) { Pattern pattern = Patterns.EMAIL_ADDRESS; return pattern.matcher(email).matches(); } public void SetTeams(ArrayList&lt;String&gt; list) { TeamsList = list; String[] stockArr = new String[TeamsList.size()]; stockArr = TeamsList.toArray(stockArr); multiSelectionSpinner.setItems(stockArr); } public void SetUsers(ArrayList&lt;String&gt; list) { UsersList = list; } public void SetPlayers(ArrayList&lt;String&gt; players) { PlayersList = players; String[] stockArr = new String[PlayersList.size()]; stockArr = PlayersList.toArray(stockArr); PlayersSelectSpinier.setItems(stockArr); } private class InsertData extends AsyncTask&lt;String,Void,Boolean&gt; { @Override protected Boolean doInBackground(String... urls) { OutputStream os=null; InputStream is=null; HttpURLConnection conn=null; try { URL url =new URL(urls[0]); JSONObject jsonObject=new JSONObject(); jsonObject.put("UserName", urls[1]); jsonObject.put("Email", urls[2]); jsonObject.put("Teams", urls[3]); jsonObject.put("Players", urls[4]); String message=jsonObject.toString(); Log.d(message, "Test"); conn=(HttpURLConnection)url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setFixedLengthStreamingMode(message.getBytes().length); conn.setRequestProperty("Content-Type", "application/json; charset=utf-8"); conn.setRequestProperty("X-Requested-With", "XMLHttpRequest"); conn.connect(); os=new BufferedOutputStream(conn.getOutputStream()); os.write(message.getBytes()); os.flush(); is=conn.getInputStream(); } catch (MalformedURLException e) { Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();; e.printStackTrace(); return false; } catch (IOException e) { Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();; e.printStackTrace(); return false; } catch (JSONException e) { e.printStackTrace(); } finally { try { assert os != null; os.close(); assert is != null; is.close(); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); } return true; } @Override protected void onPostExecute(Boolean result) { if(result) { Toast.makeText(getApplicationContext(),"Insert Success",Toast.LENGTH_LONG).show();; } else { Toast.makeText(getApplicationContext(),"Insert Fail",Toast.LENGTH_LONG).show();; } } } } </code></pre> <p>and this is the php code script:</p> <pre><code>&lt;?php require ('config.php'); $con=mysqli_connect($servername,$username,$password,$db); $json = file_get_contents('php://input'); $obj = json_decode($json,true); $txtname=$obj['UserName'];//$_POST['txtname']; $txtemail=$obj['Email'];//$_POST['txtemail']; $txtteam=$obj['Teams'];//$_POST['txtemail']; $txtplayer=$obj['Players'];//$_POST['txtemail']; mysqli_query($con,"insert into user (UserName,Email,TeamsInterested,PlayersIterested) values('$txtname','$txtemail','$txtteam','$txtplayer') "); echo "Inserted"; ?&gt; </code></pre> <p>and this is the log cat :</p> <pre><code>02-11 12:06:15.197 2301-2319/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3 Process: com.subhi.tabhost, PID: 2301 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException at com.subhi.tabhost.Registeration$InsertData.doInBackground(Registeration.java:287) at com.subhi.tabhost.Registeration$InsertData.doInBackground(Registeration.java:221) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)  at java.lang.Thread.run(Thread.java:841)  02-11 12:06:15.201 530-843/? W/ActivityManager: Force finishing activity com.subhi.tabhost/.Registeration 02-11 12:06:15.265 153-502/? W/genymotion_audio: out_write() limiting sleep time 42152 to 39909 02-11 12:06:15.469 530-843/? D/dalvikvm: GC_FOR_ALLOC freed 621K, 27% free 9319K/12628K, paused 6ms, total 7ms 02-11 12:06:15.481 530-843/? D/dalvikvm: GC_FOR_ALLOC freed 376K, 27% free 9315K/12628K, paused 12ms, total 12ms 02-11 12:06:15.497 530-545/? D/dalvikvm: GC_FOR_ALLOC freed 13K, 23% free 9791K/12628K, paused 12ms, total 12ms 02-11 12:06:15.501 530-545/? I/dalvikvm-heap: Grow heap (frag case) to 10.747MB for 1127532-byte allocation 02-11 12:06:15.509 530-539/? D/dalvikvm: GC_FOR_ALLOC freed 15K, 21% free 10876K/13732K, paused 11ms, total 11ms </code></pre> <p>and the log cat errors shows that are in code in two places:</p> <pre><code>1- `os.close();` 2- private class InsertData extends AsyncTask&lt;String,Void,Boolean&gt; </code></pre> <p>so if anyone can help me please?!</p>
<android><json><android-asynctask><android-json>
2016-02-11 17:15:12
LQ_CLOSE
35,345,927
Keeping track of changed properties in JPA
<p>Currently, I'm working on a Java EE project with some non-trivial requirements regarding persistence management. Changes to entities by users first need to be applied to some working copy before being validated, after which they are applied to the "live data". Any changes on that live data also need to have some record of them, to allow auditing.</p> <p>The entities are managed via JPA, and Hibernate will be used as provider. That is a given, so we don't shy away from Hibernate-specific stuff. For the first requirement, two persistence units are used. One maps the entities to the "live data" tables, the other to the "working copy" tables. For the second requirement, we're going to use Hibernate Envers, a good fit for our use-case.</p> <p>So far so good. Now, when users view the data on the (web-based) front-end, it would be very useful to be able to indicate which fields were changed in the working copy compared to the live data. A different colour would suffice. For this, we need some way of knowing which properties were altered. My question is, what would be a good way to go about this?</p> <p>Using the JavaBeans API, a <code>PropertyChangeListener</code> could suffice to be notified of any changes in an entity of the working copy and keep a set of them. But the set would also need to be persisted, since the application could be restarted and changes can be long-lived before they're validated and applied to the live data. And applying the changes on the live data to obtain the working copy every time it is needed isn't feasible (hence the two persistence units). We could also compare the working copy to the live data and find fields that are different. Some introspection and reflection code would suffice, but again that seems rather processing-intensive, not to mention the live data would need to be fetched. Maybe I'm missing something simple, or someone know of a wonderful JPA/Hibernate feature I can use. Even if I can't avoid making (a) separate database table(s) for storing such information until it is applied to the live data, some best-practices or real-life experience with this scenario could be very useful.</p> <p>I realize it's a semi-open question but surely other people must have encountered a requirement like this. Any good suggestion is appreciated, and any pointer to a ready-made solution would be a good candidate as accepted answer.</p>
<jpa><jakarta-ee><properties><javabeans><audit>
2016-02-11 17:20:28
HQ
35,346,088
Draw geom_tile borders inside squares to prevent overlap
<p>I would like to be able to draw borders on <code>geom_tile</code> that do not overlap so that borders can convey their own information without confusing the viewer with disappearing borders.</p> <pre><code>library(ggplot2) state &lt;- data.frame(p=runif(100), x=1:10, y=rep(1:10, each=10), z=rep(1:5, each=20)) ggplot(state, aes(x, y)) + geom_tile(aes(fill = p, color=as.factor(z)), size=2) </code></pre> <p><a href="https://i.stack.imgur.com/6TGew.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6TGew.png" alt="geom_tile plot with overlapping borders"></a></p> <p>I trust you can see how confusing overlapping borders can be.</p>
<r><ggplot2>
2016-02-11 17:28:03
HQ
35,346,433
visual studio 2010 syntax error but compile successfully
I have many many syntax errors but my solution ando proyect compiled fine help me pleasee!!!!! adding doestn appear "clean solution" [enter image description here][1] [1]: http://i.stack.imgur.com/uFxo5.png
<c#><asp.net><visual-studio>
2016-02-11 17:45:10
LQ_EDIT
35,347,818
How to use a two dimensional array in function declaration statement?
<pre><code>void sort(int [],int); </code></pre> <p>This is how I usually use a single dimensional array(i.e: <code>int []</code> ) inside a function declaration statement for programs like sorting and it works fine without any problem</p> <p>But for my matrix addition program when I use a two dimensional array(i.e:<code>int [][]</code> ) inside a function declaration statement with the similar format <code>void mat(int [][],int [][],int ,int); </code>Iam getting some error messages like:-</p> <p>1.multidimensional array must have bounds for all dimensions except the first.</p> <p>2.invalid conversion from 'int (*)[10]' to 'int' [-fpermissive].</p> <p>So my question is how to write a two dimensional array inside a function declaration statement.</p> <p>Below I have attached my full Matrix addition program using functions:-</p> <pre><code>#include&lt;stdio.h&gt; void mat(int [][],int [][],int ,int); int main() { int a[10][10],b[10][10],m,n,i,j; printf("Enter the rows and coloumns: "); scanf("%d %d",&amp;m,&amp;n); printf("\nEnter the elements of 1st Matrix:"); for(i=0;i&lt;m;i++) for(j=0;j&lt;n;j++) scanf("%d",&amp;a[i][j]); printf("\nEnter the elements of the 2nd Matrix:"); for(i=0;i&lt;m;i++) for(j=0;j&lt;n;j++) scanf("%d",&amp;b[i][j]); mat(a,b,m,n); } void mat(int a[10][10],int b[10][10],int m,int n) { int i,j,c[10][10]; for(i=0;i&lt;m;i++) for(j=0;j&lt;n;j++) c[i][j]=a[i][j]+b[i][j]; printf("\nThe addition of the 2 Matrix is :"); for(i=0;i&lt;m;i++) { printf("\n"); for(j=0;j&lt;n;j++) printf("%d",c[i][j]); } } </code></pre>
<c><arrays><function><multidimensional-array>
2016-02-11 19:01:53
LQ_CLOSE
35,348,154
mongoDB query for count
I have a mongoDB question on count. I want to count the number of fields with the name 'appId' by month day year. I know in SQL you could do this by "SELECT COUNT(appID) FROM stats GROUP BY YEAR(record_date), MONTH(record_date)" How does that translate to mongodb? { $group : { _id: { month : { $month : "$date" }, day : { $dayOfMonth : "$date" }, year : { $year : "$date" }, }, count: { $sum: * } *all the fields? } } Also how would I could the number of 'appId' whos 'criticalThreshold' is greater than 'critical'
<mongodb><count>
2016-02-11 19:18:21
LQ_EDIT
35,348,288
How can I pass a structure pointer to a function properly?
c++ beginner here. So I have several functions in which I am trying to pass an element of array of pointers (which contains structures (records)). I'm having trouble doing this and I'm pretty stuck and frustrated. I'm very new to pointers and memory so go easy on me. I keep getting errors when I try to pass the specific structure element into the function. (BTW: The functions are declared in a header file) What can I do to fix/change this and make it work? Thank you for the help, it is very much appreciated. The error I get: 'changeAssignmentGradeForStudent' was not declared in this scope **Code:** Structure student: typedef struct { char firstName[50]; char lastName[50]; char studentNumber[10]; char NSID[10]; float assignments[10]; float midterm; float final; }Student; void useFunctions(int recordNum) { // array of 10 student references Student* students[recordNum]; // values received from the user for (int i = 0; i < recordNum; i++) { cout << "Student " << i+1 << ": " << endl; students[i] = readStudentRecordFromConsole(); } cout << "Would you like to make any changes to any student records? (N or Y)" << endl; cin >> answer; if (answer == 'N') { return; } else { cout << "Which student?" << endl; cin >> student; students[student-1] = gradeChanges(*students[student-1], recordNum, student); } Student * gradeChanges(Student* s, int recordNum, int student) { Student *changedStudent = s; int gradeChange, aNum; cout << "assignment number to change?" << endl; cin >> aNum; cout << "assignment to change?" << endl; cin >> gradeChange; changeAssignmentGradeForStudent(changedStudent, aNum, gradeChange); // where the errors are return changedStudent; } void changeAssignmentGradeForStudent(Student* s, int a, int g) { if (s != NULL) { s->assignments[a] += g; } } PS: Sorry if my code is not formatted correctly. If it isn't, please edit it for me, thank you.
<c++><pointers><reference>
2016-02-11 19:25:24
LQ_EDIT
35,348,356
How to compress image size using UIImagePNGRepresentation - iOS?
<p>I'm using <code>UIImagePNGRepresentation</code> to save an image. The result image is of size 30+ KB and this is BIG in my case. </p> <p>I tried using <code>UIImageJPEGRepresentation</code> and it allows to compress image, so image saves in &lt; 5KB size, which is great, but saving it in JPEG gives it white background, which i don't want (my image is circular, so I need to save it with transparent background).</p> <p>How can I compress image size, using <code>UIImagePNGRepresentation</code>?</p>
<ios><objective-c><uiimage><uiimagejpegrepresentation><uiimagepngrepresentation>
2016-02-11 19:28:35
HQ
35,348,632
Android studio activity main
<p>When I make a new project from android studio. New blank activity has title bar and floating icon. How to get rid of it when I'm getting a new blank activity. And how i make a real blank activity.</p>
<android><android-activity><android-studio>
2016-02-11 19:43:28
LQ_CLOSE
35,348,988
How to add more Css properties in this Javascript
Javascript experts can anyone tell me how to add or assign more properties to this given javascript. $('#mydoom').each(function () { if ($(this).css('visibility') == 'hidden') { document.location.href = "http://www.example.com"; } }); you see the above script has only one css tag/property **visibility:hidden**, how can i add more properties... some like thats; **example**: $('#mydoom').each(function () { if ($(this).css('visibility') == 'hidden') ($(this).css('display') == 'none') ($(this).css('font-size') == '25px') ($(this).css('color') == 'red') { document.location.href = "http://www.example.com"; } }); You see the above scripts holds many properties...so how can i do that, this is not working which i show you above as example.
<javascript><jquery><html><css><redirect>
2016-02-11 20:04:10
LQ_EDIT
35,349,136
array of image url to ui collectionview
I am doing a json quarry to get an array of image urls. I want to display the images on a uicollection view. But I am missing something. I think I have to parse thru the array and set nsurl to each item. Then put each item in nsdata. But I am not sure. I dont want to use 3rd party software either. Here is a sample of my code. - (void)viewDidLoad { [super viewDidLoad]; dispatch_async(kBgQueue, ^{ NSData* data = [NSData dataWithContentsOfURL: coProFeedURL]; [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES]; }); } ///new return all company data array - (void)fetchedData:(NSData *)responseData { //parse out the json data NSError* error; NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1 options:kNilOptions error:&error]; NSArray * getProductsArray = [json objectForKey:@"CompanyProduct"]; //2 get all product info NSPredicate *predicate = [NSPredicate predicateWithFormat:@"companyID = %@", passCoData];//added create filter to only selected company NSArray * filteredProductArray = [getProductsArray filteredArrayUsingPredicate:predicate];//only products for selected company ///doing parsing here to get array of image urls finalImageArray = [filteredProductArray allObjects];//original NSLog(@" url images :%@", finalImageArray); //NEED TO GET FINALIMAGEARRAY TO NSURL TYPE AND SET TO IMAGE? } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return finalImageArray.count; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"Cell";//test form file works ItemCollectionViewCell *cell = (ItemCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];//test form file works ///then add the finalImageArray? return cell; } Here the output of my finalImageArray that i want to apply to uicollectionview, here is the log data: {( "http://www.test/inventory/images/bball.jpg", "http://www.test/images/bird%20tank_0.jpg" )} So am i missing something like nsurl, or nsdata, or what. How do i get this array of image url to display on a uicollectionview? Thanks for the help!
<objective-c><uicollectionview><nsarray>
2016-02-11 20:11:48
LQ_EDIT
35,349,174
Make Segue programmatically in Swift
<p>I have two VCs: VC1 and VC2. In VC1, I have a <code>finish button</code> which I programmatically made and a <code>result array</code> I want to pass to VC2.</p> <p>I know how to make Segue in Storyboard, but I cannot do that at this moment since the <code>finish button</code> is programmatically made. </p> <p>If I want to pass result array using segue, is there a way to make the segue programmatically? If this is not possible, should I just present VC2 using <code>presentViewController</code> and set a delegate to pass the <code>result array</code>?</p>
<ios><swift><segue>
2016-02-11 20:14:36
HQ
35,349,305
cant find out why valgrind gives errors in my code which has array of structures
<p>I have the following code is code snippet of large code. I am trying to free an array of structures for which I have allocated memory in this code. Unfortunately I get either a seg fault or no segfault (error free) when I change specific line in the code. I am not able to find the reason why. Can somebody please have a look and point out the reason. So If I change atom[i]->natoms to atom[i]->natoms-1 in void_free_atom I get no segault but valgrind shows that heap is not completely free. Note atom[i]->natoms is a constant number. </p> <pre><code>#include "stdheader.h" #include "Atom.h" Atom **atominfo(FILE *fp1,size_t nbytes,char *my_string,Ljcoeff *lj, int natoms) { int i; Atom **atom=(Atom **) malloc(sizeof(Atom *)*natoms); // printf("%d\n",natoms); for (i = 0; i &lt; natoms; i++) { atom[i]=(Atom *) malloc(sizeof(Atom)); atom[i]-&gt;natoms=natoms; atom[i]-&gt;eps=lj-&gt;eps[i]; atom[i]-&gt;sigma=lj-&gt;sigma[i]; getline(&amp;my_string, &amp;nbytes, fp1); sscanf(my_string, "%d %*d %lf %lf %lf %lf\n", &amp;atom[i]-&gt;id, &amp;atom[i]-&gt;x, &amp;atom[i]-&gt;y, &amp;atom[i]-&gt;z, &amp;atom[i]-&gt;q); // printf("%d %d %lf %lf %lf %lf\n",i+1,atom[i]-&gt;id,atom[i]-&gt;x,atom[i]-&gt;y,atom[i]-&gt;z,atom[i]-&gt;q); } return atom; } void free_atom(Atom **atom) { int i; for(i=0;i&lt; atom[i]-&gt;natoms;i++){ //printf("%d\n",atom[i]-&gt;natoms-1); free(atom[i]); } free(atom); } </code></pre>
<c>
2016-02-11 20:23:02
LQ_CLOSE
35,350,240
October CMS - How to correctly route
<p>I've been reviewing the documentation for October CMS routing (<a href="https://octobercms.com/docs/plugin/registration#routing-initialization" rel="noreferrer">https://octobercms.com/docs/plugin/registration#routing-initialization</a>), but I think that I am missing something. I have a page called 'deals' that renders some basic information along with a plugin (called 'deals') component. The page normally appears at the url:</p> <pre><code>http://www.example.com/deals </code></pre> <p>However, I want to create a route so that if someone visits the url:</p> <pre><code>http://www.example.com/deals2 </code></pre> <p>it will automatically route them back to</p> <pre><code>http://www.example.com/deals </code></pre> <p>I know that I should create a routes.php file in my plugin directory. However, when I try using </p> <pre><code>Route::get('/deals2', function() { return View::make('deals'); }); </code></pre> <p>It complains that it can't find the 'deals' view. What am I doing wrong?</p> <p>Additionally, how can I route it so that my homepage</p> <pre><code>http://www.example.com </code></pre> <p>would route to </p> <pre><code>http://www.example.com/deals </code></pre>
<php><laravel><routing><octobercms>
2016-02-11 21:19:55
HQ
35,350,763
please Help Me (PHP CLASS)
Class RUNcookieDescutes Extends DF_CookiesDescutes { function RUNcookieDescutes($Cookietype) { // parent the faiamal father object parent::$this->EachDescute = array("fsr" => array(0,1), // order by date "prf" => array(0,1,5,10,15), // refrech page url "ths" => array(0,1), // type of signature "tps" => array(10,30,50,70), // size of reply pages "por" => array(0,1), // order by reply or not "psa" => array(0,1,2), // find the display fined "pfr" => array("absulot")); // selected forums posts // parent the faiamal father object if ($Cookietype == 0) { parent::findElementsDescuteCookie(); } else { parent::findElementsDescuteSession(); } } } **Fatal error: Access to undeclared static property: DF_CookiesDescutes::$this in C:\xampp\htdocs\cp_inc\class_object.php on line 441**
<php>
2016-02-11 21:51:01
LQ_EDIT
35,350,780
Offline sync and event sourcing
<p>The CRUD-based part of our application needs:</p> <ol> <li>Offline bidirectional "two-way" syncing</li> <li>Ability to modify data until ready and then "publish".</li> <li>Audit log</li> </ol> <p>Event Sourcing (or the "command pattern") is what I'm looking at to accomplish these items. I feel comfortable with solving 2&amp;3 with this, but not clear for item one, syncing. </p> <p>If timestamps are used for each command (if needed), do the offline commands need to be applied to master system as they would have been in real-time (coalesced), or can I just consider them applied as happening at the end of any command (with a more recent timestamp)? </p> <p>Any basic algorithm description for command-based sync would be helpful.</p>
<synchronization><crud><offline><event-sourcing><command-pattern>
2016-02-11 21:52:19
HQ
35,350,859
Problems with configuring Mtrg
Im trying to configure Mrtg on my Windows machine. im folowing the mrtg guide <b>http://oss.oetiker.ch/mrtg/doc/mrtg-nt-guide.en.html.</b> but i get this http://sv.tinypic.com/r/246w41d/9 ive trying to folow youtube video to, but i get the same fault.
<windows><snmp><mrtg>
2016-02-11 21:56:52
LQ_EDIT
35,350,950
generates all tuples (x, y) in a range
<p>I'd like to know what is the pythonic way to generate all tuples (x, y) where x and y are integers in a certain range. I need it to generate n points and I don't want to take the same point two or more times.</p>
<python><combinations>
2016-02-11 22:03:07
LQ_CLOSE
35,350,973
How can i setup my php code to change my CSS background picture daily
<p>I have a website that has a background, and i want it to change daily.</p> <p>In my directory I have a background. each background has a number at the end.</p> <pre><code>././background1.jpg </code></pre> <p>In this case this file has a 1 tacked to it. So depending on the day the php will rewrite the css such that on a new day a new background will be set.</p>
<php><html><css>
2016-02-11 22:04:38
LQ_CLOSE
35,351,948
How would I write a program that inputs a string that represents a binary number?
<p>Question: How would I write a python program that inputs a string that represents a binary number? I'm stuck on this one in my CIS class.</p> <p>Prompt: The program can only contain only 0s and 1s with no other characters (not even spaces) If it does not, display an error message. If it is a valid binary number, determine the number of 1s that it contains. If it has exactly two 1s, display "Accepted". Otherwise, display "Rejected". All input and output should be from the console.</p>
<python><string><input><binary>
2016-02-11 23:13:05
LQ_CLOSE
35,352,889
C++ Derived class constructors
<p>Say i have a class representing the subscribers for a library. I then want to create multiple other derived classes representing different types of subscribers such as students, professors etc.. </p> <ol> <li><p>How do i write the derived class constructor ? In my base class Subscriber I have the constructor which takes parameters such as name,age,id number etc.. However in my derived classes I have extra parameters such as "schoolName" for example. How do I setup the constructor for the derived class Student knowing that i want to call the base class constructor of Subscriber and also add a value to an extra parameter that being schoolName. </p></li> <li><p>Also my second question. Would it be preferable to make the shared parameters such as age,name etc (that both the base class and the derived class share) protected as apposed to private ? That way a student can access his name,age easily </p></li> </ol>
<c++><inheritance><constructor><derived-class>
2016-02-12 00:45:41
LQ_CLOSE
35,353,368
How to have python code and markdown in one cell
<p>Can jupyter notebook support inline python code (arthritic calculations, or plot a figure) in markdown cell, or verse visa. Have both python code and markdown in one cell.</p>
<python><ipython><jupyter-notebook>
2016-02-12 01:36:41
HQ
35,353,771
Invoke pytest from python for current module only
<p>I know that py.test can test a single module if I do:</p> <pre><code>py.test mod1.py </code></pre> <p>Or, I can invoke pytest inside python:</p> <pre><code>import pytest pytest.run(['mod1.py']) </code></pre> <p>Can I do it inside python, and let it to run the current module? I guess I can do:</p> <pre><code>import pytest import os pytest.main([os.path.basename(__file__)]) </code></pre> <p>But wonder whether this is the most "pythonic" way to do it. Thanks!</p>
<python><pytest>
2016-02-12 02:25:15
HQ