qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
Apple today released an Algorithms package available at: <https://github.com/apple/swift-algorithms> This package includes a `permutations` function that works like so: ```swift let string = "abc" string.permutations() /* ["a", "b", "c"] ["a", "c", "b"] ["b", "a", "c"] ["b", "c", "a"] ["c", "a", "b"] ["c", "b", "a"] */ ```
You can use the functions of this framework to calculate permutations and combinations both with repetition and without repetition. You can investigate the source code and compare with your own. <https://github.com/amirrezaeghtedari/AECounting> This library calculates the results based on lexicographic order. For example the result of permutation 3 items out of 5 items are same as below: ``` let result = Permutation.permute(n: 5, r: 3) //result //[ // [1, 2, 3], // [1, 2, 4], // [1, 2, 5], // ..., // 5, 4, 3] //]. ``` You can easily assign your problem items to 1 to n numbers in the result array. In case of your problem, you should call: ``` let result = Permutation.permute(n: 3, r: 3) ```
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
Here is my solution. ``` import Foundation class Permutator { class func permutation(_ str: String) -> Set<String> { var set = Set<String>() permutation(str, prefix: "", set: &set) return set } private class func permutation(_ str: String, prefix: String, set: inout Set<String>) { if str.characters.count == 0 { set.insert(prefix) } for i in str.characters.indices { let left = str.substring(to: i) let right = str.substring(from: str.index(after: i)) let rem = left + right permutation(rem, prefix: prefix + String(str[i]), set: &set) } } } let startTime = Date() let permutation = Permutator.permutation("abcdefgh") print("\(permutation) \n") print("COMBINAISON: \(permutation.count)") print("TIME: \(String(format: "%.3f", Date().timeIntervalSince(startTime)))s") ``` You can copy/paste it in a file and execute it with the command line swift binary. For a permutation of 7 all unique characters, this algorithm take around 0,06 second to execute.
You can use the functions of this framework to calculate permutations and combinations both with repetition and without repetition. You can investigate the source code and compare with your own. <https://github.com/amirrezaeghtedari/AECounting> This library calculates the results based on lexicographic order. For example the result of permutation 3 items out of 5 items are same as below: ``` let result = Permutation.permute(n: 5, r: 3) //result //[ // [1, 2, 3], // [1, 2, 4], // [1, 2, 5], // ..., // 5, 4, 3] //]. ``` You can easily assign your problem items to 1 to n numbers in the result array. In case of your problem, you should call: ``` let result = Permutation.permute(n: 3, r: 3) ```
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
A very straightforward approach as also suggested in Swift coding challenges. ``` func permutation(string: String, current: String = "") { let length = string.characters.count let strArray = Array(string.characters) if (length == 0) { // there's nothing left to re-arrange; print the result print(current) print("******") } else { print(current) // loop through every character for i in 0 ..< length { // get the letters before me let left = String(strArray[0 ..< i]) // get the letters after me let right = String(strArray[i+1 ..< length]) // put those two together and carry on permutation(string: left + right, current: current + String(strArray[i])) } } } ```
I was searching to solve the same problem, but I wanted a solution that worked with Generic data type, so I wrote one by looking at a scala code (<http://vkostyukov.ru/posts/combinatorial-algorithms-in-scala/>) <https://gist.github.com/psksvp/8fb5c6fbfd6a2207e95638db95f55ae1> ``` /** translate from Scala by psksvp@gmail.com http://vkostyukov.ru/posts/combinatorial-algorithms-in-scala/ */ extension Array { func combinations(_ n: Int) -> [[Element]] { guard self.count > 0 else {return [[Element]]()} guard n <= self.count else {return [[Element]]()} if 1 == n { return self.map {[$0]} } else { let head = self.first! // at this point head should be valid let tail = Array(self.dropFirst()) let car = tail.combinations(n - 1).map {[head] + $0} // build first comb let cdr = tail.combinations(n) // do the rest return car + cdr } } func variations(_ n:Int) -> [[Element]] { func mixone(_ i: Int, _ x: Element, _ ll: [Element]) -> [Element] { return Array( ll[0 ..< i] + ([x] + ll[i ..< ll.count]) ) } func foldone(_ x: Element, _ ll: [Element]) -> [[Element]] { let r:[[Element]] = (1 ... ll.count).reduce([[x] + ll]) { a, i in [mixone(i, x, ll)] + a } return r } func mixmany(_ x: Element, _ ll: [[Element]]) -> [[Element]] { guard ll.count > 0 else {return [[Element]]()} let head = ll.first! let tail = Array<Array<Element>>(ll.dropFirst()) return foldone(x, head) + mixmany(x, tail) } guard self.count > 0 else {return [[Element]]()} guard n <= self.count else {return [[Element]]()} if 1 == n { return self.map {[$0]} } else { let head = self.first! // at this point head should be valid let tail = Array(self.dropFirst()) return mixmany(head, tail.variations(n - 1)) + tail.variations(n) } } var permutations: [[Element]] { variations(self.count) } } print([1, 2, 3, 4].combinations(2)) print([1, 2, 3, 4].variations(2)) print([1, 2, 3, 4].permutations) print(Array("ABCD").permutations) ```
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
Here's an expression of Heap's (Sedgewick's?) algorithm in Swift. It is efficient because the array is passed by reference instead of being passed by value (though of course this means you must be prepared to have the array tampered with). Swapping is efficiently expressed through the use of the built-in `swapAt(_:_:)` function: ``` func permutations(_ n:Int, _ a: inout Array<Character>) { if n == 1 {print(a); return} for i in 0..<n-1 { permutations(n-1,&a) a.swapAt(n-1, (n%2 == 1) ? 0 : i) } permutations(n-1,&a) } ``` Let's try it: ``` var arr = Array("ABC".characters) permutations(arr.count,&arr) ``` Output: ``` ["A", "B", "C"] ["B", "A", "C"] ["C", "A", "B"] ["A", "C", "B"] ["B", "C", "A"] ["C", "B", "A"] ``` If what you wanted to do with each permutation was not merely to print it, replace `print(a)` with something else. For example, you could append each permutation to an array, combine the array of characters into a string, whatever.
Here is my solution. ``` import Foundation class Permutator { class func permutation(_ str: String) -> Set<String> { var set = Set<String>() permutation(str, prefix: "", set: &set) return set } private class func permutation(_ str: String, prefix: String, set: inout Set<String>) { if str.characters.count == 0 { set.insert(prefix) } for i in str.characters.indices { let left = str.substring(to: i) let right = str.substring(from: str.index(after: i)) let rem = left + right permutation(rem, prefix: prefix + String(str[i]), set: &set) } } } let startTime = Date() let permutation = Permutator.permutation("abcdefgh") print("\(permutation) \n") print("COMBINAISON: \(permutation.count)") print("TIME: \(String(format: "%.3f", Date().timeIntervalSince(startTime)))s") ``` You can copy/paste it in a file and execute it with the command line swift binary. For a permutation of 7 all unique characters, this algorithm take around 0,06 second to execute.
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
A very straightforward approach as also suggested in Swift coding challenges. ``` func permutation(string: String, current: String = "") { let length = string.characters.count let strArray = Array(string.characters) if (length == 0) { // there's nothing left to re-arrange; print the result print(current) print("******") } else { print(current) // loop through every character for i in 0 ..< length { // get the letters before me let left = String(strArray[0 ..< i]) // get the letters after me let right = String(strArray[i+1 ..< length]) // put those two together and carry on permutation(string: left + right, current: current + String(strArray[i])) } } } ```
For those looking to calculate all permutations of an array: ``` func permutations<T>(_ arr: [T]) -> [[T]] { if arr.count < 2 { return [arr] } var ret: [[T]] = [] let rest = Array(arr[1...]) for p in permutations(rest) { for i in 0...p.count { ret.append(Array(p[0..<i]) + [arr[0]] + Array(p[i...])) } } return ret } ``` > > Update: just use `array.permuations()` [as noted by](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md) @Caleb > > >
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
While Stefan and Matt make a good point about using Heap's algorithm, I think you have an important question about why *your* code doesn't work and how you would debug that. In this case, the algorithm is simply incorrect, and the best way to discover that is with pencil and paper IMO. What you are doing is picking each element, removing it from the array, and then injecting it into each possible location. Your code does what you have asked it to do. But it's not possible to get to "CBA" that way. You're only moving one element at a time, but "CBA" has *two* elements out of order. If you expanded to ABCD, you'd find many more missing permutations (it only generates 10 of the 24). While Heap's algorithm is nicely efficient, the deeper point is that it walks through the entire array and swaps every possible pair, rather than just moving a single element through the array. Any algorithm you choose must have that property. And just to throw my hat into the ring, I'd expand on Matt's implementation this way: ``` // Takes any collection of T and returns an array of permutations func permute<C: Collection>(items: C) -> [[C.Iterator.Element]] { var scratch = Array(items) // This is a scratch space for Heap's algorithm var result: [[C.Iterator.Element]] = [] // This will accumulate our result // Heap's algorithm func heap(_ n: Int) { if n == 1 { result.append(scratch) return } for i in 0..<n-1 { heap(n-1) let j = (n%2 == 1) ? 0 : i scratch.swapAt(j, n-1) } heap(n-1) } // Let's get started heap(scratch.count) // And return the result we built up return result } // We could make an overload for permute() that handles strings if we wanted // But it's often good to be very explicit with strings, and make it clear // that we're permuting Characters rather than something else. let string = "ABCD" let perms = permute(string.characters) // Get the character permutations let permStrings = perms.map() { String($0) } // Turn them back into strings print(permStrings) // output if you like ```
**100% working tested** ``` func permute(strInput:String,l:Int,r:Int){ var inputCharacter = Array(strInput) if ( l==r){ print(strInput) }else{ for var i in l..<r{ // Swapping done inputCharacter.swapAt(l, i); // Recursion called permute(strInput: String(inputCharacter), l: l+1, r: r); //backtrack inputCharacter.swapAt(l, i); } } } ``` This way you can call method: ``` permute(strInput: "ABC", l: 0, r: 3) ``` Output: ``` ABC ACB BAC BCA CBA CAB ```
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
Here is my solution. ``` import Foundation class Permutator { class func permutation(_ str: String) -> Set<String> { var set = Set<String>() permutation(str, prefix: "", set: &set) return set } private class func permutation(_ str: String, prefix: String, set: inout Set<String>) { if str.characters.count == 0 { set.insert(prefix) } for i in str.characters.indices { let left = str.substring(to: i) let right = str.substring(from: str.index(after: i)) let rem = left + right permutation(rem, prefix: prefix + String(str[i]), set: &set) } } } let startTime = Date() let permutation = Permutator.permutation("abcdefgh") print("\(permutation) \n") print("COMBINAISON: \(permutation.count)") print("TIME: \(String(format: "%.3f", Date().timeIntervalSince(startTime)))s") ``` You can copy/paste it in a file and execute it with the command line swift binary. For a permutation of 7 all unique characters, this algorithm take around 0,06 second to execute.
For those looking to calculate all permutations of an array: ``` func permutations<T>(_ arr: [T]) -> [[T]] { if arr.count < 2 { return [arr] } var ret: [[T]] = [] let rest = Array(arr[1...]) for p in permutations(rest) { for i in 0...p.count { ret.append(Array(p[0..<i]) + [arr[0]] + Array(p[i...])) } } return ret } ``` > > Update: just use `array.permuations()` [as noted by](https://github.com/apple/swift-algorithms/blob/main/Guides/Permutations.md) @Caleb > > >
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
**100% working tested** ``` func permute(strInput:String,l:Int,r:Int){ var inputCharacter = Array(strInput) if ( l==r){ print(strInput) }else{ for var i in l..<r{ // Swapping done inputCharacter.swapAt(l, i); // Recursion called permute(strInput: String(inputCharacter), l: l+1, r: r); //backtrack inputCharacter.swapAt(l, i); } } } ``` This way you can call method: ``` permute(strInput: "ABC", l: 0, r: 3) ``` Output: ``` ABC ACB BAC BCA CBA CAB ```
You can use the functions of this framework to calculate permutations and combinations both with repetition and without repetition. You can investigate the source code and compare with your own. <https://github.com/amirrezaeghtedari/AECounting> This library calculates the results based on lexicographic order. For example the result of permutation 3 items out of 5 items are same as below: ``` let result = Permutation.permute(n: 5, r: 3) //result //[ // [1, 2, 3], // [1, 2, 4], // [1, 2, 5], // ..., // 5, 4, 3] //]. ``` You can easily assign your problem items to 1 to n numbers in the result array. In case of your problem, you should call: ``` let result = Permutation.permute(n: 3, r: 3) ```
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
While Stefan and Matt make a good point about using Heap's algorithm, I think you have an important question about why *your* code doesn't work and how you would debug that. In this case, the algorithm is simply incorrect, and the best way to discover that is with pencil and paper IMO. What you are doing is picking each element, removing it from the array, and then injecting it into each possible location. Your code does what you have asked it to do. But it's not possible to get to "CBA" that way. You're only moving one element at a time, but "CBA" has *two* elements out of order. If you expanded to ABCD, you'd find many more missing permutations (it only generates 10 of the 24). While Heap's algorithm is nicely efficient, the deeper point is that it walks through the entire array and swaps every possible pair, rather than just moving a single element through the array. Any algorithm you choose must have that property. And just to throw my hat into the ring, I'd expand on Matt's implementation this way: ``` // Takes any collection of T and returns an array of permutations func permute<C: Collection>(items: C) -> [[C.Iterator.Element]] { var scratch = Array(items) // This is a scratch space for Heap's algorithm var result: [[C.Iterator.Element]] = [] // This will accumulate our result // Heap's algorithm func heap(_ n: Int) { if n == 1 { result.append(scratch) return } for i in 0..<n-1 { heap(n-1) let j = (n%2 == 1) ? 0 : i scratch.swapAt(j, n-1) } heap(n-1) } // Let's get started heap(scratch.count) // And return the result we built up return result } // We could make an overload for permute() that handles strings if we wanted // But it's often good to be very explicit with strings, and make it clear // that we're permuting Characters rather than something else. let string = "ABCD" let perms = permute(string.characters) // Get the character permutations let permStrings = perms.map() { String($0) } // Turn them back into strings print(permStrings) // output if you like ```
``` func generate(n: Int, var a: [String]){ if n == 1 { print(a.joinWithSeparator("")) } else { for var i = 0; i < n - 1; i++ { generate(n - 1, a: a) if n % 2 == 0 { let temp = a[i] a[i] = a[n-1] a[n-1] = temp } else { let temp = a[0] a[0] = a[n-1] a[n-1] = temp } } generate(n - 1, a: a) } } func testExample() { var str = "123456" var strArray = str.characters.map { String($0) } generate(str.characters.count, a: strArray) } ``` Don't reinvent the wheel. Here's a simple port of [Heap's algorithm](https://en.wikipedia.org/wiki/Heap%27s_algorithm).
34,968,472
I am running the following tutorial: crunchify.com/how-to-create-dynamic-web-project-using-maven-in-eclipse/ I am getting the following error: [404 error](http://i.stack.imgur.com/RZXH9.png) I have confirmed my index.jsp is not in the WEB-INF folder: [project files](http://i.stack.imgur.com/vaxAJ.png) JSP is located in webapp folder: ``` <html> <body> <h2>Hello World!</h2> </body> </html> ``` My pom.xml: ``` <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.crunchify</groupId> <artifactId>CrunchifyMavenTutorial</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>CrunchifyMavenTutorial Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> </dependencies> <build> <finalName>CrunchifyMavenTutorial</finalName> </build> </project> ``` My web.xml ``` <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> </web-app> ``` I have gone through the steps several times. The Tomcat server is started with no console errors. There are no problems/warnings.
2016/01/23
[ "https://Stackoverflow.com/questions/34968472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4403658/" ]
``` func generate(n: Int, var a: [String]){ if n == 1 { print(a.joinWithSeparator("")) } else { for var i = 0; i < n - 1; i++ { generate(n - 1, a: a) if n % 2 == 0 { let temp = a[i] a[i] = a[n-1] a[n-1] = temp } else { let temp = a[0] a[0] = a[n-1] a[n-1] = temp } } generate(n - 1, a: a) } } func testExample() { var str = "123456" var strArray = str.characters.map { String($0) } generate(str.characters.count, a: strArray) } ``` Don't reinvent the wheel. Here's a simple port of [Heap's algorithm](https://en.wikipedia.org/wiki/Heap%27s_algorithm).
I was searching to solve the same problem, but I wanted a solution that worked with Generic data type, so I wrote one by looking at a scala code (<http://vkostyukov.ru/posts/combinatorial-algorithms-in-scala/>) <https://gist.github.com/psksvp/8fb5c6fbfd6a2207e95638db95f55ae1> ``` /** translate from Scala by psksvp@gmail.com http://vkostyukov.ru/posts/combinatorial-algorithms-in-scala/ */ extension Array { func combinations(_ n: Int) -> [[Element]] { guard self.count > 0 else {return [[Element]]()} guard n <= self.count else {return [[Element]]()} if 1 == n { return self.map {[$0]} } else { let head = self.first! // at this point head should be valid let tail = Array(self.dropFirst()) let car = tail.combinations(n - 1).map {[head] + $0} // build first comb let cdr = tail.combinations(n) // do the rest return car + cdr } } func variations(_ n:Int) -> [[Element]] { func mixone(_ i: Int, _ x: Element, _ ll: [Element]) -> [Element] { return Array( ll[0 ..< i] + ([x] + ll[i ..< ll.count]) ) } func foldone(_ x: Element, _ ll: [Element]) -> [[Element]] { let r:[[Element]] = (1 ... ll.count).reduce([[x] + ll]) { a, i in [mixone(i, x, ll)] + a } return r } func mixmany(_ x: Element, _ ll: [[Element]]) -> [[Element]] { guard ll.count > 0 else {return [[Element]]()} let head = ll.first! let tail = Array<Array<Element>>(ll.dropFirst()) return foldone(x, head) + mixmany(x, tail) } guard self.count > 0 else {return [[Element]]()} guard n <= self.count else {return [[Element]]()} if 1 == n { return self.map {[$0]} } else { let head = self.first! // at this point head should be valid let tail = Array(self.dropFirst()) return mixmany(head, tail.variations(n - 1)) + tail.variations(n) } } var permutations: [[Element]] { variations(self.count) } } print([1, 2, 3, 4].combinations(2)) print([1, 2, 3, 4].variations(2)) print([1, 2, 3, 4].permutations) print(Array("ABCD").permutations) ```
60,130,669
I spent many hours trying to find some way to create a new .NET Core 3.1 web app under Windows subscription. I found that if you pick up the Runtime stack as .Net Core 3.1 (LTS) the only option is to create an app under the Linux. I tried to play with different regions and Sku and sizes as well but for all cases, it's just the same. There is no option to configure App Insight during the creation time either when using the Linux. [![enter image description here](https://i.stack.imgur.com/8DZqS.jpg)](https://i.stack.imgur.com/8DZqS.jpg) The interesting thing is that when I created the Web App under .net core 3.0 marked as current I was able to deploy .net core 3.1 web app and it all worked including the app insights stuff. My question: is it just a bug in the Azure UI that you cannot create .net core 3.1 web app under Windows or there is some specific reason behind it?
2020/02/08
[ "https://Stackoverflow.com/questions/60130669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9918730/" ]
This option is going to be available once the deployment of .NET Core 3.1 has been rolled out to all AppServices worldwide. So far, this is only been completed for Linux. <https://github.com/Azure/app-service-announcements/issues/217> <https://github.com/Azure/app-service-announcements-discussions/issues/129#issuecomment-565620039> > > Windows hosted App Service option will be enabled once world wide rollout of 3.1 SDK to App Service backend is complete. > > > Since Windows AppServices have all required runtimes installed, you can select 3.0 and try to deploy your app regardles of what the portal says. I was able to host a WebApi in west Europe this week with .NET Core 3.1, but from what I read that might just have been luck. Deploying a self contained version is probably also possible from what I read in the linked Github issue. edit2:Note that the accouncement talks about the SDK. As of the writing of this post, most of the app services have the 3.1 **runtime** installed, while the SDK will take a while longer. edit: You can also check manually if your AppService has the runtimes installed already: * Go to Kudu ([https://myappservicename.**scm**.azurewebsites.net/](https://myappservicename.scm.azurewebsites.net/)) * Open the Debug console (e.g. CMD) * type in `dotnet --list-runtimes` [![enter image description here](https://i.stack.imgur.com/ouB0m.png)](https://i.stack.imgur.com/ouB0m.png)
I had the same problem. I could not get windows selected in Azure. What I did was let Visual Studio create the App in my App Services. (Note the app insights!) [![enter image description here](https://i.stack.imgur.com/CI57h.png)](https://i.stack.imgur.com/CI57h.png) [![enter image description here](https://i.stack.imgur.com/rNy97.png)](https://i.stack.imgur.com/rNy97.png) When this profile finished creating I went into the created App in the Azure portal. Settings - Configuration and changed the stack from 4.7 to .Net Core (Sorry this is in dutch, I hope you can manage...) [![enter image description here](https://i.stack.imgur.com/CCNKB.png)](https://i.stack.imgur.com/CCNKB.png) And now I also had the standard documents available which I did not have creating it in Azure portal! I changed it to only have index as landing page : [![enter image description here](https://i.stack.imgur.com/SoWL3.png)](https://i.stack.imgur.com/SoWL3.png) After I did this the homepage of my website showed up. Hope this helps someone!
72,049,340
I want to add text above the dialog box as shown in the image below (on barrier) [![How can I overwrite the dialog like this?](https://i.stack.imgur.com/CYQvt.jpg)](https://i.stack.imgur.com/CYQvt.jpg) This is the code for the dialog box that I want to modify to be as in the picture Please help me to solve my problems. ``` @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( child: const Text("Show Dialog"), onPressed: () { showDialog( context: context, barrierColor: Colors.black.withOpacity(0.8), builder: (BuildContext context) => StatefulBuilder(builder: (context, setState) => LayoutBuilder( builder: (context, constraints) { return Dialog( insetPadding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.h), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), child: DecoratedBox( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), gradient: LinearGradient( colors: [ const Color(0xFFE64978), const Color(0xFFed8c41).withOpacity(0.5), Colors.white.withOpacity(0.1), Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Padding( padding: EdgeInsetsDirectional.only(top: 25.h,bottom: 10.h), child: Column( mainAxisSize: MainAxisSize.min, children: [ const DialogTitleWidget(), SizedBox(height: 10.h), DialogPageViewWidget(controller: controller, dialogModelList: dialogModelList,constraints: constraints), SizedBox(height: 10.h), DialogPageIndicatorWidget(controller: controller, dialogModelList: dialogModelList), SizedBox(height: 20.h), const DialogContent(), ], ), ), ), ), ); }, ), ), ); }, ), ), ); } ``` I have another problem that appears to me when I minimize the screen or rotate the phone screen (the problem appears when the dimensions change) [![enter image description here](https://i.stack.imgur.com/at1N2.png)](https://i.stack.imgur.com/at1N2.png)
2022/04/28
[ "https://Stackoverflow.com/questions/72049340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15297263/" ]
It's not clear what your Insert logic is and what exactly you want to insert but let me give you how I would structure such a query (including some safeguards such as prepared statements) and hopefully you can just change the SQL statements based on what you need. I have left comments on most rows to explain ``` <?php include 'includes/conn.php'; include 'includes/scripts.php'; if (isset($_POST['no'])) { $sca=trim($_POST['no'],""); $credentials=""; $sql = "SELECT * FROM `barcode`"; $mysqli = new $conn; // Prepare the statement $stmt = $mysqli->prepare($sql); // Attempt to execute if ($stmt->execute()) { // Save result $result = $stmt->get_result(); // save the result in an assoc array $row = $result->fetch_all(MYSQL_ASSOC); // If there is a returned entry if (count($row) > 0) { if ($row['credentials'] === $sca) { // close the statement so we can re-use $stmt->close(); // We assume id is what we need $id = $row['id']; // Now you have to fix your INSERT statement here. I am not sure what you need to insert but follow the general docs on how to insert https://www.php.net/manual/en/mysqli-stmt.bind-param.php $stmt = $mysqli->prepare("INSERT IGNORE INTO `voters` (columnName) VALUES (?)"); // Here you need to decide what you are inserting and change the variable $stmt->bind_param("s", $whatever_variable_you_insert); // Attempt to execute if ($stmt->execute()) { // if successful, proceed with the deletion too... or you can put it outside this execute condition $stmt->close(); // Prepare the delete statement $stmt = $mysqli->prepare("DELETE FROM `barcode` WHERE id=?"); // Bind the param $stmt->bind_para("s", $id); if ($stmt->exceute()) { // something else or as you wanted - refresh header("refresh: .5"); } } } } } } ?> ```
This is an ideal situation for a stored procedure. I assume you try to Your logic seems to be: 1. find a barcode (by id and sca?) 2. if a barcode is found insert into voters table 3. delete barcode from the barcode table So something like ``` create procedure `check_barcode` (sca int) begin select * into result from `code` where id = sca limit 1; if not result is null then insert into `voters` select * from `barcode` where id = sca; delete from `barcode` where id = sca; end if; end ``` You did not include the table design it is a bit guesswork.
72,049,340
I want to add text above the dialog box as shown in the image below (on barrier) [![How can I overwrite the dialog like this?](https://i.stack.imgur.com/CYQvt.jpg)](https://i.stack.imgur.com/CYQvt.jpg) This is the code for the dialog box that I want to modify to be as in the picture Please help me to solve my problems. ``` @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( child: const Text("Show Dialog"), onPressed: () { showDialog( context: context, barrierColor: Colors.black.withOpacity(0.8), builder: (BuildContext context) => StatefulBuilder(builder: (context, setState) => LayoutBuilder( builder: (context, constraints) { return Dialog( insetPadding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.h), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), child: DecoratedBox( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), gradient: LinearGradient( colors: [ const Color(0xFFE64978), const Color(0xFFed8c41).withOpacity(0.5), Colors.white.withOpacity(0.1), Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Padding( padding: EdgeInsetsDirectional.only(top: 25.h,bottom: 10.h), child: Column( mainAxisSize: MainAxisSize.min, children: [ const DialogTitleWidget(), SizedBox(height: 10.h), DialogPageViewWidget(controller: controller, dialogModelList: dialogModelList,constraints: constraints), SizedBox(height: 10.h), DialogPageIndicatorWidget(controller: controller, dialogModelList: dialogModelList), SizedBox(height: 20.h), const DialogContent(), ], ), ), ), ), ); }, ), ), ); }, ), ), ); } ``` I have another problem that appears to me when I minimize the screen or rotate the phone screen (the problem appears when the dimensions change) [![enter image description here](https://i.stack.imgur.com/at1N2.png)](https://i.stack.imgur.com/at1N2.png)
2022/04/28
[ "https://Stackoverflow.com/questions/72049340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15297263/" ]
It's not clear what your Insert logic is and what exactly you want to insert but let me give you how I would structure such a query (including some safeguards such as prepared statements) and hopefully you can just change the SQL statements based on what you need. I have left comments on most rows to explain ``` <?php include 'includes/conn.php'; include 'includes/scripts.php'; if (isset($_POST['no'])) { $sca=trim($_POST['no'],""); $credentials=""; $sql = "SELECT * FROM `barcode`"; $mysqli = new $conn; // Prepare the statement $stmt = $mysqli->prepare($sql); // Attempt to execute if ($stmt->execute()) { // Save result $result = $stmt->get_result(); // save the result in an assoc array $row = $result->fetch_all(MYSQL_ASSOC); // If there is a returned entry if (count($row) > 0) { if ($row['credentials'] === $sca) { // close the statement so we can re-use $stmt->close(); // We assume id is what we need $id = $row['id']; // Now you have to fix your INSERT statement here. I am not sure what you need to insert but follow the general docs on how to insert https://www.php.net/manual/en/mysqli-stmt.bind-param.php $stmt = $mysqli->prepare("INSERT IGNORE INTO `voters` (columnName) VALUES (?)"); // Here you need to decide what you are inserting and change the variable $stmt->bind_param("s", $whatever_variable_you_insert); // Attempt to execute if ($stmt->execute()) { // if successful, proceed with the deletion too... or you can put it outside this execute condition $stmt->close(); // Prepare the delete statement $stmt = $mysqli->prepare("DELETE FROM `barcode` WHERE id=?"); // Bind the param $stmt->bind_para("s", $id); if ($stmt->exceute()) { // something else or as you wanted - refresh header("refresh: .5"); } } } } } } ?> ```
I get what I was looking for! ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <?php include "includes/scripts.php"; ?> </head> <body> <div class="container mt-5 pt-5"> <form id="scanform" autocomplete="off" method="POST"> <div class="row"> <div class="col-sm-3"> <h1>Scan:</h1> </div> <div class="col-sm-6"> <div class="form-group"> <input type="text" id="no" name="no" class="form-control" required> </div> </div> <div class="col-sm-3"> <button class="btn btn-info" name="sub" type="submit">Buscar</button> </div> </div> </form> </div> </body> </html> <?php include 'includes/conn.php'; if (isset($_POST['no'])) { $sca = trim($_POST['no'],""); $flag = 0; $id= ""; $credentials = ""; $password = ""; $firstname = ""; $lastname = ""; $sql = "SELECT * FROM `barcode` WHERE credentials = '" . $sca . "' LIMIT 1"; $result = mysqli_query($conn , $sql); $barcode = mysqli_fetch_assoc($result); if ($barcode) { $mod = "INSERT IGNORE INTO voters Select * from barcode where id = " . $barcode['id']; $insert_result = mysqli_query($conn , $mod); if ($insert_result) { $del = "DELETE from barcode where id = " . $barcode['id']; $del_result = mysqli_query($conn , $del); echo "<div class='alert alert-success d-flex justify-content-center mt-3'>Product has been removed from barcode!</div></div>"; } else { echo "<div class='alert alert-danger d-flex justify-content-center mt-3'>Something went wrong while deleting from barcode!</div></div>"; } } else { echo "<div class='alert alert-danger d-flex justify-content-center mt-3'>Product Not Found</div></div>"; return; } } mysqli_close($conn); ?> ```
72,049,340
I want to add text above the dialog box as shown in the image below (on barrier) [![How can I overwrite the dialog like this?](https://i.stack.imgur.com/CYQvt.jpg)](https://i.stack.imgur.com/CYQvt.jpg) This is the code for the dialog box that I want to modify to be as in the picture Please help me to solve my problems. ``` @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( child: const Text("Show Dialog"), onPressed: () { showDialog( context: context, barrierColor: Colors.black.withOpacity(0.8), builder: (BuildContext context) => StatefulBuilder(builder: (context, setState) => LayoutBuilder( builder: (context, constraints) { return Dialog( insetPadding: EdgeInsets.symmetric(horizontal: 15.w, vertical: 10.h), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)), child: DecoratedBox( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), gradient: LinearGradient( colors: [ const Color(0xFFE64978), const Color(0xFFed8c41).withOpacity(0.5), Colors.white.withOpacity(0.1), Colors.white, ], begin: Alignment.topCenter, end: Alignment.bottomCenter, ), ), child: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: Padding( padding: EdgeInsetsDirectional.only(top: 25.h,bottom: 10.h), child: Column( mainAxisSize: MainAxisSize.min, children: [ const DialogTitleWidget(), SizedBox(height: 10.h), DialogPageViewWidget(controller: controller, dialogModelList: dialogModelList,constraints: constraints), SizedBox(height: 10.h), DialogPageIndicatorWidget(controller: controller, dialogModelList: dialogModelList), SizedBox(height: 20.h), const DialogContent(), ], ), ), ), ), ); }, ), ), ); }, ), ), ); } ``` I have another problem that appears to me when I minimize the screen or rotate the phone screen (the problem appears when the dimensions change) [![enter image description here](https://i.stack.imgur.com/at1N2.png)](https://i.stack.imgur.com/at1N2.png)
2022/04/28
[ "https://Stackoverflow.com/questions/72049340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15297263/" ]
This is an ideal situation for a stored procedure. I assume you try to Your logic seems to be: 1. find a barcode (by id and sca?) 2. if a barcode is found insert into voters table 3. delete barcode from the barcode table So something like ``` create procedure `check_barcode` (sca int) begin select * into result from `code` where id = sca limit 1; if not result is null then insert into `voters` select * from `barcode` where id = sca; delete from `barcode` where id = sca; end if; end ``` You did not include the table design it is a bit guesswork.
I get what I was looking for! ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <?php include "includes/scripts.php"; ?> </head> <body> <div class="container mt-5 pt-5"> <form id="scanform" autocomplete="off" method="POST"> <div class="row"> <div class="col-sm-3"> <h1>Scan:</h1> </div> <div class="col-sm-6"> <div class="form-group"> <input type="text" id="no" name="no" class="form-control" required> </div> </div> <div class="col-sm-3"> <button class="btn btn-info" name="sub" type="submit">Buscar</button> </div> </div> </form> </div> </body> </html> <?php include 'includes/conn.php'; if (isset($_POST['no'])) { $sca = trim($_POST['no'],""); $flag = 0; $id= ""; $credentials = ""; $password = ""; $firstname = ""; $lastname = ""; $sql = "SELECT * FROM `barcode` WHERE credentials = '" . $sca . "' LIMIT 1"; $result = mysqli_query($conn , $sql); $barcode = mysqli_fetch_assoc($result); if ($barcode) { $mod = "INSERT IGNORE INTO voters Select * from barcode where id = " . $barcode['id']; $insert_result = mysqli_query($conn , $mod); if ($insert_result) { $del = "DELETE from barcode where id = " . $barcode['id']; $del_result = mysqli_query($conn , $del); echo "<div class='alert alert-success d-flex justify-content-center mt-3'>Product has been removed from barcode!</div></div>"; } else { echo "<div class='alert alert-danger d-flex justify-content-center mt-3'>Something went wrong while deleting from barcode!</div></div>"; } } else { echo "<div class='alert alert-danger d-flex justify-content-center mt-3'>Product Not Found</div></div>"; return; } } mysqli_close($conn); ?> ```
2,627,768
I am new to web design using tableless and I'm having problem positioning some elements on my page.. Here's the sample html: <http://christianruado.comuf.com/sample.html> [alt text http://christianruado.comuf.com/images/screen.jpg](http://christianruado.comuf.com/images/screen.jpg) As you can see from the screen shots I want my right div to be vertically stretched down to the same level of my footer and position my bottom element to the lowest part of the right container. CSS: ``` .container { width:88%; } #header { background:#CCCCCC; margin-bottom:5px; padding-bottom:2px; height:100px; text-align:center; } #content { background: #0099CC; margin-bottom:5px; } #main { margin: .5em 0 0 0; text-align: left; width:80%; } #right { float:right; width: 19%; background:#FF3300; margin-left:2px; height: 100%; min-height: 200px; } #right .top { top:0; display:block; background-color:#CCCCCC; } #right .bottom { bottom:0; display:block; background-color:#FFCCFF; height:30px; } #center { background:#00FF99; padding: 5px 0 0 10px; float:left; } #footer { clear:both; height:30px; background-color:#CCFF33; width:80%; text-align:left; } ``` **HTML markup:** ``` <div class="container showgrid"> <div id="header"> <h1>Header</h1> </div> <div id="right"><span class="top">Top element</span><span class="bottom">Bottom Element</span></div> <div id="main"> <div id="center"> <h3>Lorem ipsum dolor sit amet</h3> <p>Content here</p> </div> </div> <div id="footer"> <h3>Footer</h3> </div> </div> ```
2010/04/13
[ "https://Stackoverflow.com/questions/2627768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/114206/" ]
This is not exactly the answer to your problem, but it should get you on the right track. Behold! [The Holy Grail](http://www.alistapart.com/articles/holygrail)! If that doesn't work, another technique you can use is to fake the column. This is done by vertically tiling a background image the width of your column behind where you want your column to be. It's not bad and can work in a pinch.
css : ``` #header,#content,#main,#right, #right .top,#right .bottom,#center,#footer {float:left;} ``` html : ``` div.header <br> div.center + div.left <br> div.footer + div.right ``` should be like this/
901,962
What is the correct MIME type for a tar.gz file? I've searched around and found several values being used, including: ``` application/x-gzip application/x-gtar application/x-tgz ``` But I could find no indication as to which of these (if any) was the correct or canonical value.
2015/04/15
[ "https://superuser.com/questions/901962", "https://superuser.com", "https://superuser.com/users/229054/" ]
As of August 2012, the MIME type recommended in [RFC 6713](https://www.rfc-editor.org/rfc/rfc6713) is `application/gzip`. According to the [IANA registry](http://www.iana.org/assignments/media-types/media-types.xhtml), tar is not an official media type, so a GZipped tar file is officially only a compressed file. Hypothetically, if a tarball were an official media type and following conventions, its MIME type would be `application/tar` (file extension .tar) and its compressed version would be `application/tar+gzip` (file extensions .tar.gz and .tgz).
Although most are deprecated, they are all technically correct, just different MIME types. The correct MIME type is `application/x-gzip` according to cPanel standards.
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Most likely, you have simply forgotten to override `equals()` and `hashCode()` in your type. `equals()` is what `contains()` checks for. From the [Javadoc](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#contains(java.lang.Object)): > > Returns `true` if this list contains the specified element. More formally, returns `true` if and only if this list contains at least one element `e` such that `(o==null ? e==null : o.equals(e))`. > > > Since the default implementation of [`equals`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)) tests for reference equality, it's not suitable for custom data types like this one. (And if you didn't override `equals` and `hashCode`, using your types as keys in a `HashMap` would be equally futile.) --- **Edit:** Note that to override, you must provide the *exact* signature. ``` class MyDataType { public boolean equals(MyDataType other) { // WRONG! ... } public boolean equals(Object other) { // Right! ... } } ``` This is a very strong argument for using the [`@Override`](http://java.sun.com/javase/6/docs/api/java/lang/Override.html) annotation; the first example would have failed at compile time if annotated with `@Override`.
Did you override the equals method? This is required to make contains work correctly.
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Most likely, you have simply forgotten to override `equals()` and `hashCode()` in your type. `equals()` is what `contains()` checks for. From the [Javadoc](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#contains(java.lang.Object)): > > Returns `true` if this list contains the specified element. More formally, returns `true` if and only if this list contains at least one element `e` such that `(o==null ? e==null : o.equals(e))`. > > > Since the default implementation of [`equals`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)) tests for reference equality, it's not suitable for custom data types like this one. (And if you didn't override `equals` and `hashCode`, using your types as keys in a `HashMap` would be equally futile.) --- **Edit:** Note that to override, you must provide the *exact* signature. ``` class MyDataType { public boolean equals(MyDataType other) { // WRONG! ... } public boolean equals(Object other) { // Right! ... } } ``` This is a very strong argument for using the [`@Override`](http://java.sun.com/javase/6/docs/api/java/lang/Override.html) annotation; the first example would have failed at compile time if annotated with `@Override`.
maybe use the Integer class instead? then you can do object comparison
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Most likely, you have simply forgotten to override `equals()` and `hashCode()` in your type. `equals()` is what `contains()` checks for. From the [Javadoc](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#contains(java.lang.Object)): > > Returns `true` if this list contains the specified element. More formally, returns `true` if and only if this list contains at least one element `e` such that `(o==null ? e==null : o.equals(e))`. > > > Since the default implementation of [`equals`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)) tests for reference equality, it's not suitable for custom data types like this one. (And if you didn't override `equals` and `hashCode`, using your types as keys in a `HashMap` would be equally futile.) --- **Edit:** Note that to override, you must provide the *exact* signature. ``` class MyDataType { public boolean equals(MyDataType other) { // WRONG! ... } public boolean equals(Object other) { // Right! ... } } ``` This is a very strong argument for using the [`@Override`](http://java.sun.com/javase/6/docs/api/java/lang/Override.html) annotation; the first example would have failed at compile time if annotated with `@Override`.
My guess is that you've only written a "strongly typed" equals method instead of overriding equals(Object). In other words, if you've got: ``` public boolean equals(Foo f) ``` you need ``` public boolean equals(Object o) ``` as well to override Object.equals. That would fit with "equals works but contains doesn't because your tests probably call the strongly-typed equals, but ArrayList doesn't.
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Most likely, you have simply forgotten to override `equals()` and `hashCode()` in your type. `equals()` is what `contains()` checks for. From the [Javadoc](http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#contains(java.lang.Object)): > > Returns `true` if this list contains the specified element. More formally, returns `true` if and only if this list contains at least one element `e` such that `(o==null ? e==null : o.equals(e))`. > > > Since the default implementation of [`equals`](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)) tests for reference equality, it's not suitable for custom data types like this one. (And if you didn't override `equals` and `hashCode`, using your types as keys in a `HashMap` would be equally futile.) --- **Edit:** Note that to override, you must provide the *exact* signature. ``` class MyDataType { public boolean equals(MyDataType other) { // WRONG! ... } public boolean equals(Object other) { // Right! ... } } ``` This is a very strong argument for using the [`@Override`](http://java.sun.com/javase/6/docs/api/java/lang/Override.html) annotation; the first example would have failed at compile time if annotated with `@Override`.
Remember that if you don't override the equals() method, then two objects of your type are only equal if they are the *same instance* of that object. The ArrayList class uses this method to check that it contains the given object. Also, you need to match the signature exactly, which means that it must take an Object as a parameter and not a Foo. Also, the Object contract stipulates that you must override hashCode() whenever you override equals(). If you don't do this, then a HashMap or HashSet won't identify your two objects as being equal, even if the ArrayList does (HashMap checks for identical hashes and then calls equals() on them to check for actual equality). Thus, if ArrayList says that two items aren't equal, then there is no way that HashMap would either. This means that your second solution does not work. My recommendation is to check that you actually override equals() and hashCode() properly and that their signatures match the ones in the Object class.
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Did you override the equals method? This is required to make contains work correctly.
maybe use the Integer class instead? then you can do object comparison
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My guess is that you've only written a "strongly typed" equals method instead of overriding equals(Object). In other words, if you've got: ``` public boolean equals(Foo f) ``` you need ``` public boolean equals(Object o) ``` as well to override Object.equals. That would fit with "equals works but contains doesn't because your tests probably call the strongly-typed equals, but ArrayList doesn't.
Did you override the equals method? This is required to make contains work correctly.
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My guess is that you've only written a "strongly typed" equals method instead of overriding equals(Object). In other words, if you've got: ``` public boolean equals(Foo f) ``` you need ``` public boolean equals(Object o) ``` as well to override Object.equals. That would fit with "equals works but contains doesn't because your tests probably call the strongly-typed equals, but ArrayList doesn't.
maybe use the Integer class instead? then you can do object comparison
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Remember that if you don't override the equals() method, then two objects of your type are only equal if they are the *same instance* of that object. The ArrayList class uses this method to check that it contains the given object. Also, you need to match the signature exactly, which means that it must take an Object as a parameter and not a Foo. Also, the Object contract stipulates that you must override hashCode() whenever you override equals(). If you don't do this, then a HashMap or HashSet won't identify your two objects as being equal, even if the ArrayList does (HashMap checks for identical hashes and then calls equals() on them to check for actual equality). Thus, if ArrayList says that two items aren't equal, then there is no way that HashMap would either. This means that your second solution does not work. My recommendation is to check that you actually override equals() and hashCode() properly and that their signatures match the ones in the Object class.
maybe use the Integer class instead? then you can do object comparison
986,924
I have an ArrayList in Java which is made up of a type containing two strings and an integer. I can successfully test if one element of this ArrayList equals another but I find that the contains method fails. I believe this is due to the fact that my type is not primitive. Now I see two alternatives to this and I wonder which is the best option: 1. To implement my own contains method by iterating through the ArrayList and testing equality of each element against the one I'm looking for and then breaking the loop. 2. Or to use a HashMap of my type as key with an integer as value instead of the ArrayList. Here I can use method containsKey to check if an element already exists in the HashMap. The only caveat with approach to #2 is that the value is largely redundant in my case.
2009/06/12
[ "https://Stackoverflow.com/questions/986924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
My guess is that you've only written a "strongly typed" equals method instead of overriding equals(Object). In other words, if you've got: ``` public boolean equals(Foo f) ``` you need ``` public boolean equals(Object o) ``` as well to override Object.equals. That would fit with "equals works but contains doesn't because your tests probably call the strongly-typed equals, but ArrayList doesn't.
Remember that if you don't override the equals() method, then two objects of your type are only equal if they are the *same instance* of that object. The ArrayList class uses this method to check that it contains the given object. Also, you need to match the signature exactly, which means that it must take an Object as a parameter and not a Foo. Also, the Object contract stipulates that you must override hashCode() whenever you override equals(). If you don't do this, then a HashMap or HashSet won't identify your two objects as being equal, even if the ArrayList does (HashMap checks for identical hashes and then calls equals() on them to check for actual equality). Thus, if ArrayList says that two items aren't equal, then there is no way that HashMap would either. This means that your second solution does not work. My recommendation is to check that you actually override equals() and hashCode() properly and that their signatures match the ones in the Object class.
35,315,624
In Oracle the space allocated for data after `INSERT INTO` operation is not cleaned up when deleting rows from the table. Instead, after `DELETE FROM` operation some "waste space" is left. So what happens when I do `INSERT INTO` after `DELETE FROM` - does it span this "waste space" or allocates new space again?
2016/02/10
[ "https://Stackoverflow.com/questions/35315624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3787877/" ]
You could use [`Node.lookup()`](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#lookup-java.lang.String-) to get the `Circle`s using a css selector (or [`Node.lookupAll`](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/Node.html#lookupAll-java.lang.String-) for multiple nodes): ``` void change(String oldId, String newId) { change(oldId, Color.RED); change(newId, Color.GREEN); } void change(String id, Color color){ Circle circle = (Circle) slaveVbox.lookup('#'+id); circle.setFill(color); } ```
Its simple: Just add All Circles in a List -> ``` List<Circle> circles = new ArrayList<>(); public void creat(String s) { newNode = new ButtonBar(); Circle c = new Circle(); c.setRadius(11); c.setStrokeWidth(1); c.setStroke(Paint.valueOf("#ffffff")); c.setFill(Paint.valueOf("#15ff00")); c.setId(s); circles.add(c); newNode.getButtons().addAll(new Button("Mavero"), c); slaveVbox.getChildren().addAll(newNode); } @FXML public void newComp() { creat("id1"); creat("id2"); } @FXML public void change() { for (Circle c : circles) { c.setFill(Color.BLACK); } } ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
**In-place solution:** In order to shift all zeros rightwards, we iterate through the array keeping track of the last non-zero element's index `i` and shifting all non-zero elements to the left: ```js // Moves zeroes to the right: function moveZeroes(array) { let i = 0; for (let j = 0; j < array.length; ++j) { if (i < j) array[i] = array[j]; if (array[j] != 0) ++i; } return array.fill(0, i); } // Example: console.log(moveZeroes([0, 1, 0, 3, 12])); ``` **Explanation:** We start with `i` and `j` pointing to the first array element. Now we traverse the array elements from left to right. Whenever we encounter a zero, we only increment `j` but not `i`. Thus, the difference between `i` and `j` is equal to the number of zeros in the array up to `j`. Now the trick: In order to move zeros to the right, we actually need to move all non-zero to the left. How much to the left? Exactly the amount of zeros we encountered so far. This is done by `array[i] = array[j]`. At the end, the remaining space between the last non-zero element at `i` and the end is filled with zeros. Both operations - swapping values and filling with zero - are performed in-place, while splicing and pushing are usually not considered in-place as they change the array size and possibly memory location.
index is not updated when you delete an item in an array.use for loop instead. ```js var moveZeroes = function(nums) { var count=0; //Remove anything that's not Zero. for(var index=0;index<nums.length;index++){ if(nums[index]==0){ //when remove item from the array,the rest items index after removed item changed. //so you must change the index variable in the loop via:index--. nums.splice(index--, 1); count++; } }; //Fill in Zeros at the end for(var i=0; i< count ; i++){ nums.push(0); } }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); //Works too! ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
index is not updated when you delete an item in an array.use for loop instead. ```js var moveZeroes = function(nums) { var count=0; //Remove anything that's not Zero. for(var index=0;index<nums.length;index++){ if(nums[index]==0){ //when remove item from the array,the rest items index after removed item changed. //so you must change the index variable in the loop via:index--. nums.splice(index--, 1); count++; } }; //Fill in Zeros at the end for(var i=0; i< count ; i++){ nums.push(0); } }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); //Works too! ```
I think i got it. Whenever we do "Splice" we are changing the array size, hence in the second example, we need to also check the previous element. The completed code is/as follows: ``` var moveZeroes = function(nums) { var count=0; nums.forEach(function(val, index){ if(val==0){ nums.splice(index, 1); count++; } if(nums[index-1] == 0){ nums.splice(index-1, 1); count++; } }); for(var i=0; i< count ; i++){ nums.push(0); } }; ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
**In-place solution:** In order to shift all zeros rightwards, we iterate through the array keeping track of the last non-zero element's index `i` and shifting all non-zero elements to the left: ```js // Moves zeroes to the right: function moveZeroes(array) { let i = 0; for (let j = 0; j < array.length; ++j) { if (i < j) array[i] = array[j]; if (array[j] != 0) ++i; } return array.fill(0, i); } // Example: console.log(moveZeroes([0, 1, 0, 3, 12])); ``` **Explanation:** We start with `i` and `j` pointing to the first array element. Now we traverse the array elements from left to right. Whenever we encounter a zero, we only increment `j` but not `i`. Thus, the difference between `i` and `j` is equal to the number of zeros in the array up to `j`. Now the trick: In order to move zeros to the right, we actually need to move all non-zero to the left. How much to the left? Exactly the amount of zeros we encountered so far. This is done by `array[i] = array[j]`. At the end, the remaining space between the last non-zero element at `i` and the end is filled with zeros. Both operations - swapping values and filling with zero - are performed in-place, while splicing and pushing are usually not considered in-place as they change the array size and possibly memory location.
The problem is that you're modifying the array while you're looping over it. Every time you splice out an element, all the elements after it get shifted down. But the next iteration goes to the next element, so it skips the element that was moved into the place of the element that was removed. The first example seems to work because you don't have two `0` in a row in the array, so skipping the next element doesn't cause a problem. The second example has two `0` in a row, so it skips the second one of the pair. The simplest way to solve problems like this is to iterate in the reverse direction. ```js var moveZeroes = function(nums) { for (var i = nums.length-1; i >= 0; i--) { if (nums[i] == 0) { nums.splice(i, 1); nums.push(0); } } }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); //fails! ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
You ar cutting out (`splicing`) from an array that you are currently looping through (in the `forEach`), so it there is more successive `0` some of them will be skipped. So if the array is `[0, 0, 1]` here is what happens: ``` forEach: (case of two or more successive 0s) [0, 0, 1] // ^ cursor is here (0 === 0 then remove it) [0, 1] // ^ cursor is at the second item, the second 0 is safe because it is now occupy a place that is already looped over [0, 1] // fails forEach: (case of no successive 0s) [0, 1, 0, 1] // ^ cursor is here (0 === 0 then remove it) [1, 0, 1] // ^ (0 === 0 then remove) [1, 1] // works ``` To solve the problem, you'll have to use a basic `for` loop where you can control the position of the cursor (index), or alter the array in a way that dosent change it's length and not hiding 0 behind the cursor like this: ```js var moveZeroes = function(nums) { nums.forEach(function(val, index) { if (val) { // if it is a non-zero value nums.splice(index, 1); // remove it nums.unshift(val); // add it to the begining of the array (note that the order of non-zero values will be reversed) } }); }; var input1 = [0, 1, 0, 3, 12]; var input2 = [0, 0, 1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); // Now Works too! ```
here is an other implementation for it if you are interested . with a simple for loop ``` var moveZeroes = function(nums) { var res = [] var count=0 for(var i = 0 ; i < nums.length ; i++){ nums[i] == 0 ? count += 1 : res.push(nums[i]) } for(var j = 0 ; j < count ; j++){ res.push(0) } return res }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; console.log(moveZeroes(input1)) console.log(moveZeroes(input2)) ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
here is an other implementation for it if you are interested . with a simple for loop ``` var moveZeroes = function(nums) { var res = [] var count=0 for(var i = 0 ; i < nums.length ; i++){ nums[i] == 0 ? count += 1 : res.push(nums[i]) } for(var j = 0 ; j < count ; j++){ res.push(0) } return res }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; console.log(moveZeroes(input1)) console.log(moveZeroes(input2)) ```
I think i got it. Whenever we do "Splice" we are changing the array size, hence in the second example, we need to also check the previous element. The completed code is/as follows: ``` var moveZeroes = function(nums) { var count=0; nums.forEach(function(val, index){ if(val==0){ nums.splice(index, 1); count++; } if(nums[index-1] == 0){ nums.splice(index-1, 1); count++; } }); for(var i=0; i< count ; i++){ nums.push(0); } }; ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
**In-place solution:** In order to shift all zeros rightwards, we iterate through the array keeping track of the last non-zero element's index `i` and shifting all non-zero elements to the left: ```js // Moves zeroes to the right: function moveZeroes(array) { let i = 0; for (let j = 0; j < array.length; ++j) { if (i < j) array[i] = array[j]; if (array[j] != 0) ++i; } return array.fill(0, i); } // Example: console.log(moveZeroes([0, 1, 0, 3, 12])); ``` **Explanation:** We start with `i` and `j` pointing to the first array element. Now we traverse the array elements from left to right. Whenever we encounter a zero, we only increment `j` but not `i`. Thus, the difference between `i` and `j` is equal to the number of zeros in the array up to `j`. Now the trick: In order to move zeros to the right, we actually need to move all non-zero to the left. How much to the left? Exactly the amount of zeros we encountered so far. This is done by `array[i] = array[j]`. At the end, the remaining space between the last non-zero element at `i` and the end is filled with zeros. Both operations - swapping values and filling with zero - are performed in-place, while splicing and pushing are usually not considered in-place as they change the array size and possibly memory location.
As others have already mentioned, you are removing elements from an array you are iterating over. This causes the index provided in the `forEach` function (that is iterating over the original version of the array) to be out of the date with the current updated array. Here is one approach using the `filter` function: ```js var moveZeroesToEnd = function(nums) { var nonZeros = nums.filter(function(num) { return num != 0; }); var zeros = nums.filter(function(num) { return num == 0; }); return nonZeros.concat(zeros); }; var input1 = [0, 1, 0, 3, 12]; var input2 = [0, 0, 1]; console.log(moveZeroesToEnd(input1)) console.log(moveZeroesToEnd(input2)); ``` If you only want to loop through the array once, you could do: ```js var moveZeroesToEnd = function(nums) { var nonZeros = []; var zeros = []; nums.forEach(function(num) { var arr = num ? nonZeros : zeros; arr.push(num); }); return nonZeros.concat(zeros); }; var input1 = [0, 1, 0, 3, 12]; var input2 = [0, 0, 1]; console.log(moveZeroesToEnd(input1)) console.log(moveZeroesToEnd(input2)); ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
index is not updated when you delete an item in an array.use for loop instead. ```js var moveZeroes = function(nums) { var count=0; //Remove anything that's not Zero. for(var index=0;index<nums.length;index++){ if(nums[index]==0){ //when remove item from the array,the rest items index after removed item changed. //so you must change the index variable in the loop via:index--. nums.splice(index--, 1); count++; } }; //Fill in Zeros at the end for(var i=0; i< count ; i++){ nums.push(0); } }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); //Works too! ```
The problem is that you're modifying the array while you're looping over it. Every time you splice out an element, all the elements after it get shifted down. But the next iteration goes to the next element, so it skips the element that was moved into the place of the element that was removed. The first example seems to work because you don't have two `0` in a row in the array, so skipping the next element doesn't cause a problem. The second example has two `0` in a row, so it skips the second one of the pair. The simplest way to solve problems like this is to iterate in the reverse direction. ```js var moveZeroes = function(nums) { for (var i = nums.length-1; i >= 0; i--) { if (nums[i] == 0) { nums.splice(i, 1); nums.push(0); } } }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); //fails! ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
You ar cutting out (`splicing`) from an array that you are currently looping through (in the `forEach`), so it there is more successive `0` some of them will be skipped. So if the array is `[0, 0, 1]` here is what happens: ``` forEach: (case of two or more successive 0s) [0, 0, 1] // ^ cursor is here (0 === 0 then remove it) [0, 1] // ^ cursor is at the second item, the second 0 is safe because it is now occupy a place that is already looped over [0, 1] // fails forEach: (case of no successive 0s) [0, 1, 0, 1] // ^ cursor is here (0 === 0 then remove it) [1, 0, 1] // ^ (0 === 0 then remove) [1, 1] // works ``` To solve the problem, you'll have to use a basic `for` loop where you can control the position of the cursor (index), or alter the array in a way that dosent change it's length and not hiding 0 behind the cursor like this: ```js var moveZeroes = function(nums) { nums.forEach(function(val, index) { if (val) { // if it is a non-zero value nums.splice(index, 1); // remove it nums.unshift(val); // add it to the begining of the array (note that the order of non-zero values will be reversed) } }); }; var input1 = [0, 1, 0, 3, 12]; var input2 = [0, 0, 1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); // Now Works too! ```
index is not updated when you delete an item in an array.use for loop instead. ```js var moveZeroes = function(nums) { var count=0; //Remove anything that's not Zero. for(var index=0;index<nums.length;index++){ if(nums[index]==0){ //when remove item from the array,the rest items index after removed item changed. //so you must change the index variable in the loop via:index--. nums.splice(index--, 1); count++; } }; //Fill in Zeros at the end for(var i=0; i< count ; i++){ nums.push(0); } }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); //Works too! ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
You ar cutting out (`splicing`) from an array that you are currently looping through (in the `forEach`), so it there is more successive `0` some of them will be skipped. So if the array is `[0, 0, 1]` here is what happens: ``` forEach: (case of two or more successive 0s) [0, 0, 1] // ^ cursor is here (0 === 0 then remove it) [0, 1] // ^ cursor is at the second item, the second 0 is safe because it is now occupy a place that is already looped over [0, 1] // fails forEach: (case of no successive 0s) [0, 1, 0, 1] // ^ cursor is here (0 === 0 then remove it) [1, 0, 1] // ^ (0 === 0 then remove) [1, 1] // works ``` To solve the problem, you'll have to use a basic `for` loop where you can control the position of the cursor (index), or alter the array in a way that dosent change it's length and not hiding 0 behind the cursor like this: ```js var moveZeroes = function(nums) { nums.forEach(function(val, index) { if (val) { // if it is a non-zero value nums.splice(index, 1); // remove it nums.unshift(val); // add it to the begining of the array (note that the order of non-zero values will be reversed) } }); }; var input1 = [0, 1, 0, 3, 12]; var input2 = [0, 0, 1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); // Now Works too! ```
I think i got it. Whenever we do "Splice" we are changing the array size, hence in the second example, we need to also check the previous element. The completed code is/as follows: ``` var moveZeroes = function(nums) { var count=0; nums.forEach(function(val, index){ if(val==0){ nums.splice(index, 1); count++; } if(nums[index-1] == 0){ nums.splice(index-1, 1); count++; } }); for(var i=0; i< count ; i++){ nums.push(0); } }; ```
42,869,156
I have several .csv files in a folder. I want to read them all once by using the command ``` library(data.table) path <-path list <- list.files(path,pattern="*.csv") files <- paste(path,list,sep='/') DT <- do.call(rbind, lapply(files, fread)) ``` However, since the first column is a 12 digits number, data.table shows it in a scientific number way, like ``` 5.43971221673e-313 ``` How should I convert all the scientific numbers into normal integers? Thanks a lot! First edit: After I use the command ``` options("scipen"=100, "digits"=12) ``` It still shows the number like ``` 5.43971221673e-313 ``` Even after I applied the command ``` options(scipen=999) ``` It gives me back the number ``` 0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000543971221673 ``` And even 543971221673 is not the correct number, the correct one should be ``` 110101001001 ``` I was using data.frame to try to convert, it works. ``` a <- read.csv(files) a[,1] <- as.character(a[,1]) ``` But I would prefer to use data.table to make it fast. Thank you guys!
2017/03/18
[ "https://Stackoverflow.com/questions/42869156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7392051/" ]
index is not updated when you delete an item in an array.use for loop instead. ```js var moveZeroes = function(nums) { var count=0; //Remove anything that's not Zero. for(var index=0;index<nums.length;index++){ if(nums[index]==0){ //when remove item from the array,the rest items index after removed item changed. //so you must change the index variable in the loop via:index--. nums.splice(index--, 1); count++; } }; //Fill in Zeros at the end for(var i=0; i< count ; i++){ nums.push(0); } }; var input1 = [0,1,0,3,12]; var input2 = [0,0,1]; moveZeroes(input1) console.log(input1); //Works! moveZeroes(input2) console.log(input2); //Works too! ```
As others have already mentioned, you are removing elements from an array you are iterating over. This causes the index provided in the `forEach` function (that is iterating over the original version of the array) to be out of the date with the current updated array. Here is one approach using the `filter` function: ```js var moveZeroesToEnd = function(nums) { var nonZeros = nums.filter(function(num) { return num != 0; }); var zeros = nums.filter(function(num) { return num == 0; }); return nonZeros.concat(zeros); }; var input1 = [0, 1, 0, 3, 12]; var input2 = [0, 0, 1]; console.log(moveZeroesToEnd(input1)) console.log(moveZeroesToEnd(input2)); ``` If you only want to loop through the array once, you could do: ```js var moveZeroesToEnd = function(nums) { var nonZeros = []; var zeros = []; nums.forEach(function(num) { var arr = num ? nonZeros : zeros; arr.push(num); }); return nonZeros.concat(zeros); }; var input1 = [0, 1, 0, 3, 12]; var input2 = [0, 0, 1]; console.log(moveZeroesToEnd(input1)) console.log(moveZeroesToEnd(input2)); ```
12,282,450
I am completely new to moving codeigniter to my web-server and im having trouble with the configuration. Where do I place my codeigniter project folder in www under myurl.com in in the very root directory? Am i supposed to move out the application and system folders? I am trying to remove index.php? from my URL name where do i place my .htaccess file in the root or in the same folder as my codeigniter directory? I wish to be able to type in (www.myurl.com) and be redirected to my home\_controller/index is this possible? ![enter image description here](https://i.stack.imgur.com/dCuvv.png) *below is my .htaccess file in it's entirety* ``` <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /MMSFL/ #'system' can be replaced if you have renamed your system folder. RewriteCond %{REQUEST_URI} ^system.* RewriteRule ^(.*)$ /index.php/$1 [L] #Rename 'application' to your applications folder name. RewriteCond %{REQUEST_URI} ^application.* RewriteRule ^(.*)$ /index.php/$1 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA] </IfModule> <IfModule !mod_rewrite.c> ErrorDocument 404 /index.php </IfModule> ``` I have also made the following changes in config/routes ------------------------------------------------------- ``` $config['index_page'] = ""; $config['base_url'] = "http://myurl.com/"; $config['server_root'] = $_SERVER['DOCUMENT_ROOT']; $config['uri_protocol'] = 'AUTO'; $route['default_controller'] = "home_controller"; ```
2012/09/05
[ "https://Stackoverflow.com/questions/12282450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1546955/" ]
**Directory structure** If at all possible, it's advised that you keep your `system` and `application` folders above the web root. Your `index.php` file needs to be accessible from a browser, so that should go in your `public_html` folder. Here's a possible directory structure that you could use: ``` -/home/edd -public_html -index.html -.htaccess -system -application ``` You can rename your system and application folders, or create another sub-directory to put them in, if you want. --- **index.php** Within `index.php` you'll need to update `$system_path` and `$application_folder` to reflect the location and name of your system and application folders. You can use an absolute path or a relative path. Relative path shown below: ``` $system_path = '../../system'; $application_folder = '../../application'; ``` --- **.htaccess** The first two sections of your `.htaccess` file are there to prevent a user from accessing your system and application folders. If you're storing them above the web root then you don't really need this. If you keep them, then you need to update the paths. This file should be located in your `public_html` folder. --- **application/config/config.php** As you've already correctly done, the `index.php` value should be removed from the `index_page` config, so *index.php* can be removed from your url using your *.htaccess* file; ``` $config['index_page'] = 'index.php'; ``` should be changed to: ``` $config['index_page'] = ''; ``` You may also have to make this change: ``` $config['uri_protocol'] = 'REQUEST_URI'; ``` (If you have no luck with this value, try the others. One should work!) --- **application/config/routes.php** ``` $route['default_controller'] = "home_controller"; ``` (Assuming that is the name of your controller.) --- Your site is likely to depend on some *assets*, such as CSS and JavaScript. These should go in your web root - `public_html`. You can organise these file however you like.
Move all the files that reside inside your CI-folder into `public_html`. The `.htaccess` file should be located in the root of `public_html`(where application, system, index.php etc also reside). Side note: don't put `$config` values in `/config/routes.php` - those need to be in `/config/config.php`
24,287
I planted some beetroot from store bought seedlings in November, and they're fine. But this chap grew up with them, and I don't remember if it came with the others, or just grew from where ever. I just don't know what it is. Doesn't look like a turnip to me. And the leaves looked like a kind of spinach which is why I left it so long in the ground occupying valuable real estate. [![guest vegetable](https://i.stack.imgur.com/10n6t.jpg)](https://i.stack.imgur.com/10n6t.jpg) And a single leaf against a dibber with 2.5 cm markings [![mystery vegetable](https://i.stack.imgur.com/UouNQ.jpg)](https://i.stack.imgur.com/UouNQ.jpg)
2016/04/25
[ "https://gardening.stackexchange.com/questions/24287", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/1894/" ]
I think what you have here is a slightly misshapen Sugar Beet. Both Beetroot and Sugar Beets are *Beta vulgaris*, they're just different cultivars. The seeds are identical so telling them apart at planting would be impossible, and they cross-pollinate freely so it's no big surprise a sugar beet seed could have slipped into the mix.
I think it is really a beetroot (*Beta vugaris*). Just there are many different sorts. This seems something in direction of Swiss chard. Probably the seeds got mixed.
16,695,691
I know this is simple and the answer has got to be out there somewhere but I can't find it. How do I select all the values of a series of dropdown menus with a specific class inside a specific form? The specific form is important because I have dropdown menus with the same class outside the form that I do not wish to select. ``` <form action="http://link.com" method="post" accept-charset="utf-8" id="addInfoForm" class="form_standard"> <select name="item_id[]" class="addItems"> <option value="0">---</option> <option value="1">Value 1</option> <option value="2">Value 2</option> </select> <select name="item_id[]" class="addItems"> <option value="0">---</option> <option value="1">Value 1</option> <option value="2">Value 2</option> </select> </form> <select name="item_id[]" class="addItems"> <option value="0">---</option> <option value="1">Value 1</option> <option value="2">Value 2</option> </select> ```
2013/05/22
[ "https://Stackoverflow.com/questions/16695691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1132729/" ]
Try something like `$('#addInfoForm select.addItems option[selected="selected"]').each(function() { alert($(this).val()); });`
``` $("#addInfoForm select.addItems") ```
27,674
How can I modify (or replace) `elpy-shell-send-region-or-buffer` (bound to `C-c C-c`) to behave like `ess-eval-region-or-function-or-paragraph-and-step`, i.e. 1. if region is active, evaluate it (this currently works), goto 4. 2. if inside a function, evaluate it, goto 4. 3. evaluate current paragraph 4. Jump to the beginning of next paragraph Thank you very much!
2016/10/09
[ "https://emacs.stackexchange.com/questions/27674", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/5237/" ]
I haven't tried this thoroughly, but should work: 1. if region is active, evaluate it (this currently works), goto 3. 2. if region not active, evaluate current statement, goto 3. 3. Jump to the beginning of next paragraph ``` (defun python-shell-send-region-or-line nil "Sends from python-mode buffer to a python shell, intelligently." (interactive) (cond ((region-active-p) (setq deactivate-mark t) (python-shell-send-region (region-beginning) (region-end)) (python-nav-forward-statement) ) (t (elpy-shell-send-current-statement)))) ``` Taken from [this answer](https://stackoverflow.com/questions/35934972/emacs-elisp-send-line-if-no-region-active-python-mode/40152990#40152990).
`elpy-shell-send-region-or-buffer` is meant only to send entire buffer or a region. If you want to step through code, you should use `elpy-shell-send-current-statement`, which is bound to `C-ENTER`. This function sends current statement to Python shell and advances to next. If you want to send entire function, you have to use `python-shell-send-defun` which is bound to `C-M-x`.
12,495,049
What is the use of .rc files in Android framework. I see a lot of files what is there purpose. Also I have a little knowledge about linux but I see commands like ``` mkdir /dirName 0777 abc def ``` what does that mean. If I run this command on GNU-Linux it creates folder named dirName, 0777, abc and def. I know its like giving permissions while creating directory also abc and def are somewhat like owner or root, but not sure. Does commands in .rc file runs different in Linux normal kernel and in Android linux kernel. Is there any link or online material to study to learn the same that how can we write and use .rc files in Android. Thanks in advance.
2012/09/19
[ "https://Stackoverflow.com/questions/12495049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367661/" ]
Thanks for the reply. I already knew .rc files contains instructions for the compiler and what is the purpose of .rc files. ([Definition of .rc file](http://linux.about.com/cs/linux101/g/rcfile.htm)). I was more concerned about its usage with context of Android and how commands are used. After searching a lot I finally found a link explaining basics of it ([Android INIT Language](https://github.com/aosp-mirror/platform_system_core/blob/master/init/README.md)). As in my question I asked how mkdir command usage is different in android .rc file its well explaind in readme file in [this link](https://github.com/aosp-mirror/platform_system_core/blob/master/init/README.md). Thanks again.
.rc files contain instructions for the compiler. This [source](http://www.ehow.com/facts_5697167_file-extension-rc_.html) explains it so much better. [Marakana](http://marakana.com/static/courseware/android/internals/index.html) deals a little bit with GNU command line and things of that nature. I am not sure if I answered your question exactly how you wanted, but hopefully this points you in the right direction.
8,826,390
I'm trying to use some mysql data in creating part of a variable name to refer to another variable already declared elsewhere. Basically how can I get the $damage\_name be part of the if statement boolean check? ``` $conditions = array( 'bent_num' => 0, 'spine_torn' => 0, 'pages_torn' => 0, 'water_damage' => 0, 'pages_highlighted' => 0, 'pages_noted' => 0, 'taped' => 0, 'stained' => 0, 'mold' => 0, 'scratched' => 0 ); while ($row = mysql_fetch_assoc($res)) { $damage_name = $conditions[$row['type']]; if (isset($conditions[$row['type']]) && $_SESSION[SELL_is_ . $damage_name . ]; == 'y') { $condition_score = $condition_score - $row['value']; } } ```
2012/01/11
[ "https://Stackoverflow.com/questions/8826390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969621/" ]
Broken syntax and concatenation. Try: ``` $_SESSION['SELL_is_' . $damage_name]; ``` * SELL\_is\_ needs to be quoted. * You had an extra concatenation operator after `$damage_name` * An extra semicolon after the closing square bracket.
I think you mean: ``` $_SESSION[constant("SELL_is_" . $damage_name)] ``` I'm assuming SELL\_is\_ is a `define`d constant (because of the capitalization). To get the value of a define, either use the full name, or use `constant`.
8,826,390
I'm trying to use some mysql data in creating part of a variable name to refer to another variable already declared elsewhere. Basically how can I get the $damage\_name be part of the if statement boolean check? ``` $conditions = array( 'bent_num' => 0, 'spine_torn' => 0, 'pages_torn' => 0, 'water_damage' => 0, 'pages_highlighted' => 0, 'pages_noted' => 0, 'taped' => 0, 'stained' => 0, 'mold' => 0, 'scratched' => 0 ); while ($row = mysql_fetch_assoc($res)) { $damage_name = $conditions[$row['type']]; if (isset($conditions[$row['type']]) && $_SESSION[SELL_is_ . $damage_name . ]; == 'y') { $condition_score = $condition_score - $row['value']; } } ```
2012/01/11
[ "https://Stackoverflow.com/questions/8826390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969621/" ]
Broken syntax and concatenation. Try: ``` $_SESSION['SELL_is_' . $damage_name]; ``` * SELL\_is\_ needs to be quoted. * You had an extra concatenation operator after `$damage_name` * An extra semicolon after the closing square bracket.
try: ``` if (isset($conditions[$row['type']]) && $_SESSION["SELL_is_$damage_name"] == 'y') ```
8,826,390
I'm trying to use some mysql data in creating part of a variable name to refer to another variable already declared elsewhere. Basically how can I get the $damage\_name be part of the if statement boolean check? ``` $conditions = array( 'bent_num' => 0, 'spine_torn' => 0, 'pages_torn' => 0, 'water_damage' => 0, 'pages_highlighted' => 0, 'pages_noted' => 0, 'taped' => 0, 'stained' => 0, 'mold' => 0, 'scratched' => 0 ); while ($row = mysql_fetch_assoc($res)) { $damage_name = $conditions[$row['type']]; if (isset($conditions[$row['type']]) && $_SESSION[SELL_is_ . $damage_name . ]; == 'y') { $condition_score = $condition_score - $row['value']; } } ```
2012/01/11
[ "https://Stackoverflow.com/questions/8826390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969621/" ]
Broken syntax and concatenation. Try: ``` $_SESSION['SELL_is_' . $damage_name]; ``` * SELL\_is\_ needs to be quoted. * You had an extra concatenation operator after `$damage_name` * An extra semicolon after the closing square bracket.
``` $_SESSION[SELL_is_ . $damage_name . ]; ``` should be ``` $_SESSION["SELL_is_" . $damage_name]; ```
8,826,390
I'm trying to use some mysql data in creating part of a variable name to refer to another variable already declared elsewhere. Basically how can I get the $damage\_name be part of the if statement boolean check? ``` $conditions = array( 'bent_num' => 0, 'spine_torn' => 0, 'pages_torn' => 0, 'water_damage' => 0, 'pages_highlighted' => 0, 'pages_noted' => 0, 'taped' => 0, 'stained' => 0, 'mold' => 0, 'scratched' => 0 ); while ($row = mysql_fetch_assoc($res)) { $damage_name = $conditions[$row['type']]; if (isset($conditions[$row['type']]) && $_SESSION[SELL_is_ . $damage_name . ]; == 'y') { $condition_score = $condition_score - $row['value']; } } ```
2012/01/11
[ "https://Stackoverflow.com/questions/8826390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969621/" ]
I think you mean: ``` $_SESSION[constant("SELL_is_" . $damage_name)] ``` I'm assuming SELL\_is\_ is a `define`d constant (because of the capitalization). To get the value of a define, either use the full name, or use `constant`.
try: ``` if (isset($conditions[$row['type']]) && $_SESSION["SELL_is_$damage_name"] == 'y') ```
8,826,390
I'm trying to use some mysql data in creating part of a variable name to refer to another variable already declared elsewhere. Basically how can I get the $damage\_name be part of the if statement boolean check? ``` $conditions = array( 'bent_num' => 0, 'spine_torn' => 0, 'pages_torn' => 0, 'water_damage' => 0, 'pages_highlighted' => 0, 'pages_noted' => 0, 'taped' => 0, 'stained' => 0, 'mold' => 0, 'scratched' => 0 ); while ($row = mysql_fetch_assoc($res)) { $damage_name = $conditions[$row['type']]; if (isset($conditions[$row['type']]) && $_SESSION[SELL_is_ . $damage_name . ]; == 'y') { $condition_score = $condition_score - $row['value']; } } ```
2012/01/11
[ "https://Stackoverflow.com/questions/8826390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969621/" ]
``` $_SESSION[SELL_is_ . $damage_name . ]; ``` should be ``` $_SESSION["SELL_is_" . $damage_name]; ```
try: ``` if (isset($conditions[$row['type']]) && $_SESSION["SELL_is_$damage_name"] == 'y') ```
61,877,351
I want to display a maintenance page on an application running under Kubernetes whilst a deployment is in progress, in this “maintenance” window, I backup the database and then apply schema changes and then deploy the new version. I thought maybe what I could do is change the service selector so that it would point to a nginx container serving up a simple maintenance page whilst the deployment progressed. Once the deployment had succeeded, I would switch back the selector to point to the pods that do the actual work. My problem with this is approach is that unless I close and reopen the browser that is currently looking at the site then I never see the maintenance page; I’m guessing the browser is keeping a connection open. The public service address doesn’t change throughout this process. I’m testing this locally on a Docker Kubernetes installation using a type of NodePort . Any ideas on how to get it working or am I flogging a dead horse with this approach? Regards Lee
2020/05/18
[ "https://Stackoverflow.com/questions/61877351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1634174/" ]
This happens due to a combination of how browsers and k8s services work. Browsers cache TCP connections to servers: when requesting a page they will leave the TCP connection open, and if the user later requests more pages from the same domain, the browser will reuse the already-open TCP connection to save time. The k8s service load balancing operates at the TCP layer. When a new TCP connection is received, it will be assigned to a pod from the Service, and it will keep talking to that pod for the entire TCP connection's lifetime. So, the issue is your browser is keeping TCP connections open to your old pods, even if you modify the service. How can we fix this? Non-solution #1: have the browser not cache connections. As far as I know there's no way to do this, and you don't want it anyway because it'll make your site slower. Also, HTTP caching headers have no impact on this. Browsers always cache TCP connections. A no-cache header will make the browser request the page again, but over the already-open connection. Non-solution #2: have k8s kill TCP connections when updating the service. This is not possible and is not desirable either because this behavior is what makes "graceful shutdown / request draining" deployment strategies work. See [issue](https://github.com/kubernetes/kubernetes/issues/46753). Solution #1: Use Layer 7 (HTTP) load balancing instead of Layer 4 (TCP) load balancing, such as [nginx-ingress](https://github.com/kubernetes/ingress-nginx). L7 load balancing routes traffic to pods "per HTTP request", instead of "per TCP connection", so you won't have this problem even if browsers keep TCP connections open. Solution #2: do this from your application instead of from k8s. For example, have an "in-maintenance" DB flag, check it on every request and serve the maintenance page if it's set.
First of all make sure the content you are serving is not cached. Second, make sure to close all open TCP connections when you shut down your pods. The steps should be as follows: 1. Change service selector to route traffic to maintenance pods 2. Gracefully shutdown running pods (this includes closing all open TCP connections) 3. Do maintenance 4. Change service selector back As an alternative approach, you can use an ingress controller. That won't have this problem, because it doesn't maintain an open TCP connection to the pods.
61,877,351
I want to display a maintenance page on an application running under Kubernetes whilst a deployment is in progress, in this “maintenance” window, I backup the database and then apply schema changes and then deploy the new version. I thought maybe what I could do is change the service selector so that it would point to a nginx container serving up a simple maintenance page whilst the deployment progressed. Once the deployment had succeeded, I would switch back the selector to point to the pods that do the actual work. My problem with this is approach is that unless I close and reopen the browser that is currently looking at the site then I never see the maintenance page; I’m guessing the browser is keeping a connection open. The public service address doesn’t change throughout this process. I’m testing this locally on a Docker Kubernetes installation using a type of NodePort . Any ideas on how to get it working or am I flogging a dead horse with this approach? Regards Lee
2020/05/18
[ "https://Stackoverflow.com/questions/61877351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1634174/" ]
This happens due to a combination of how browsers and k8s services work. Browsers cache TCP connections to servers: when requesting a page they will leave the TCP connection open, and if the user later requests more pages from the same domain, the browser will reuse the already-open TCP connection to save time. The k8s service load balancing operates at the TCP layer. When a new TCP connection is received, it will be assigned to a pod from the Service, and it will keep talking to that pod for the entire TCP connection's lifetime. So, the issue is your browser is keeping TCP connections open to your old pods, even if you modify the service. How can we fix this? Non-solution #1: have the browser not cache connections. As far as I know there's no way to do this, and you don't want it anyway because it'll make your site slower. Also, HTTP caching headers have no impact on this. Browsers always cache TCP connections. A no-cache header will make the browser request the page again, but over the already-open connection. Non-solution #2: have k8s kill TCP connections when updating the service. This is not possible and is not desirable either because this behavior is what makes "graceful shutdown / request draining" deployment strategies work. See [issue](https://github.com/kubernetes/kubernetes/issues/46753). Solution #1: Use Layer 7 (HTTP) load balancing instead of Layer 4 (TCP) load balancing, such as [nginx-ingress](https://github.com/kubernetes/ingress-nginx). L7 load balancing routes traffic to pods "per HTTP request", instead of "per TCP connection", so you won't have this problem even if browsers keep TCP connections open. Solution #2: do this from your application instead of from k8s. For example, have an "in-maintenance" DB flag, check it on every request and serve the maintenance page if it's set.
Here is how services in Kubernetes work, they are basically a dummy loadbalancers forwarding requests to pods in a round robin fashion, and they select which pods to forward the requests to based on the labels as you have already figured out. Now here is how http/tcp work, I open the browser to visit your website www.example.com the tcp takes it's round of syn,ack,syn-ack and I receive the data. In your case once I open your website I get a reply from a certain pod based on how the service routed me, and that's it, no further communication is made. Afterwards you remove the functional pods from the service and add the maintenance page, this will be only shown to the new clients connecting to your website. I.E if I requested your website, and then you changed all the code and restarted NGINX, if I didn't refresh I would not receive new content
11,047,640
I have a normale jpg-photo and 2 textlink. When the user mouseover textlink 1 I would like to show a transparent png-photo on top of the jpg-photo, and when the user mouseover textlink 2, I would like to show another png-photo on top of the jpg. On mouseout the png should disappear again. Possible? And can it be done with CSS alone or do I need javascript to? Thanks in advanced.
2012/06/15
[ "https://Stackoverflow.com/questions/11047640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458216/" ]
Yes it is possible with JQuery, JS or CSS, depending on your requirements. Good script to use is here: <http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery>
Your request can be done easily using the power of jQuery :) I made something using jQuery and you can find it here <http://jsfiddle.net/xrmqq/> It is close to what you want to do.
11,047,640
I have a normale jpg-photo and 2 textlink. When the user mouseover textlink 1 I would like to show a transparent png-photo on top of the jpg-photo, and when the user mouseover textlink 2, I would like to show another png-photo on top of the jpg. On mouseout the png should disappear again. Possible? And can it be done with CSS alone or do I need javascript to? Thanks in advanced.
2012/06/15
[ "https://Stackoverflow.com/questions/11047640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458216/" ]
You can use hover CSS selector to solve such kind of problems depending upon html layout of your page ``` #11:hover img { display:inline: Add other blocks } ```
Your request can be done easily using the power of jQuery :) I made something using jQuery and you can find it here <http://jsfiddle.net/xrmqq/> It is close to what you want to do.
11,318,922
I've managed to successfully build my maven project which uses the [jasmine-maven-plugin](https://github.com/searls/jasmine-maven-plugin) to put the source and test javascript files in the right places. When I have a simple test such as: ``` describe('true', function() { it('should be true', function() { expect(true).toBe(true); }) }) ``` the whole thing builds with no problems, and all the jasmine specs pass. But when I try to create an instance of an object that I've outlined in one of the files that are included target/jasmine/src folder, I get a "ReferenceError: "Stat" is not defined" error. ``` describe('stat test',function() { var stat = new Stat(); it('get data',function() { stat.data = 13; expect(stat.getData()).toBe(13); }); }); ``` Are the js files not loading properly? Totally stumped here.
2012/07/03
[ "https://Stackoverflow.com/questions/11318922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1429419/" ]
Did you set up in the correct way jasmine? It seems that jasmine can't find your js files, here you have an example of the maven configuration: ``` <plugin> <groupId>com.github.searls</groupId> <artifactId>jasmine-maven-plugin</artifactId> <version>1.1.0</version> <executions> <execution> <goals> <goal> test </goal> </goals> </execution> </executions> <configuration> <jsSrcDir> main/www/js </jsSrcDir> <---HERE you define the source directory <haltOnFailure>false</haltOnFailure> <sourceIncludes> <---- HERE you specifies which files you include into the test <include>libs/jquery-1.7.1.js</include> <include>libs/underscore.js</include> <include>**/*.js</include> </sourceIncludes> <sourceExcludes> <----- HERE you define the files that you exclude <exclude>jsonresponses-mock.js</exclude> <exclude>libs/jquery.mockjax.js</exclude> </sourceExcludes> <jsTestSrcDir> test/www/fakeJs </jsTestSrcDir> <---Define your Test source Dir <haltOnFailure>true</haltOnFailure> <browserVersion>FIREFOX_3</browserVersion> <serverPort>8234</serverPort> <specDirectoryName>specs</specDirectoryName> </configuration> </plugin> ``` At the bottom of this page: <http://searls.github.com/jasmine-maven-plugin> you have all the possibles tags. Check if you have your pom in the correct way... Hope it can help!!
After much mental strain and not much luck, I just modified the plugin to ignore perceived javascript errors so that everything would compile. Lo and behold, it all worked! Scripts were just being added out of order. For those interested, I added "client.setThrowExceptionOnScriptError(false)" at line #90 in TestMojo.java, so now when the tag is set to false (default), javascript errors are ignored.
27,776,500
At the moment I have a bunch of functions that check if strings meet certain circumstances eg isValidAlphaNumericString or isValidUserName. Which uses my own implicit stringOps class. It is quite useful especially when dealing with complex requirements such as author names etc. Requiring string to have only no consecutive -\_. or space characters etc. Using complex regex's. But why stop there? The string isn't constrained properly meaning some function could map an anonymous function to it and break the variable after you have checked it. This is not a very safe way to proceed. I want a to create types for each of these constrained strings bound to a trait ConstrainedString which allows me to specify how each type deals with methods. I'm struggling with the design side of it. Basically there's two things I need help with. What happens when a function breaks the constraint? Is there a way to catch this at compile time? Do I restrict my type from only having methods that I *know* will not break the constraint ie. Concatenation of 2 AlphaNumericString's will always return alphanumeric String?? Or do I have the actual type as Option[String] so If the contract is broken the value becomes None?? There must be a better way aside from throwing exceptions everywhere. Im presuming the best way to achieve this is through a StringLike typeclass similar to this example <http://danielwestheide.com/blog/2013/02/06/the-neophytes-guide-to-scala-part-12-type-classes.html> eg Except i want to be able to write ``` val foo:Bar = "This is a valid Bar" ``` I presume the appropriate way is to provide an implicit conversion of string to Bar by pointing to a Bar apply() method which checks if the method is a valid Bar. The dream is to have is work like Numbers do in scala and having this fail to compile. ``` //fails to compile due to - not being a valid character val foo:AlphaNumericString = "-Adlsa85464" ``` If anyone has actually implemented something similar id love to look at the code otherwise: Is there a simple way to maintain the constraint regardless of function issues Is my theory on how to approach this issue correct?
2015/01/05
[ "https://Stackoverflow.com/questions/27776500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2541783/" ]
It seems like a good fit for Scala Macros. See [this post](https://blog.safaribooksonline.com/2013/12/20/scala-macros-that-wont-kill-you/) for details. You can have your own string types and perform compile time validation on them.
Imagine that you are a scala compiler :) How would *you* approach the task of failing an assignment like `val foo: AlphaNumericString = someString()` without actually evaluation the right hand side and the conversion function? This was just my long way to say, that what you are asking for is obviously impossible.
59,210,253
I am create custom search page. When this page is opened, hamburger menu is hide and search text field change size instantly. how to make it happen smoothly? [![enter image description here](https://i.stack.imgur.com/yTbpl.gif)](https://i.stack.imgur.com/yTbpl.gif) Now i make this code ``` class DefaultAppBar extends StatefulWidget implements PreferredSizeWidget { @override Size get preferredSize => Size.fromHeight(56.0); @override _DefaultAppBarState createState() => _DefaultAppBarState (); } class _DefaultAppBarState extends State<DefaultAppBar> with TickerProviderStateMixin { AnimationController _controller; double textWidth = 300.0; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { var future = new Future.delayed(const Duration(milliseconds: 100), ()=>setState(() { textWidth = 400.00; })); return Stack( children: [ Scaffold( appBar:AppBar( centerTitle: true, automaticallyImplyLeading: false, // ... title:AnimatedContainer ( duration: Duration (milliseconds: 500), width: loginWidth, // color: Colors.red, child: TextField( autofocus: true, // ... decoration: InputDecoration( fillColor: Colors.white, filled: true, prefixIcon: Icon(Icons.arrow_back,color: Colors.grey), hintText: 'Search something ...', border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), contentPadding: EdgeInsets.zero, // border: InputBorder.none, // hintText: "My Custom Search Label", // KEY PROP hintStyle: TextStyle(color: Colors.red), // KEY PROP ), ), ), ), ) ] ); } } ``` And get this result [![enter image description here](https://i.stack.imgur.com/PxzYE.gif)](https://i.stack.imgur.com/PxzYE.gif) Work, but not very smoothly and how to calculate start and finish for textWidth automatically and how make back animation like this <https://photos.app.goo.gl/mWpdsouLi4csptKb7>
2019/12/06
[ "https://Stackoverflow.com/questions/59210253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6919358/" ]
You can't return an array by value. However, you can do that with an `std::array`, which is a wrapper around an array: ``` #include <array> std::array<float, 5> FunctionName() { std::array<float, 5> data; //process data return data; } ```
> > You can return the pointer to array in C style doing: > > > ``` float* FunctionName(){ float myVar[5]; float* p = (float*) malloc(sizeof(float) * 5); //process data return p; } ```
5,987,935
I have an array of unknown (to the current method) class objects. I do know that each class has a property called "Number". I am trying to write a LINQ query where I am looking for the object with the next Number in sequence. AKA, I'm at Number 8, use a LINQ query to find the object where Number=9. Anyone got a suggestion? Also, I use reflection often so don't worry about avoiding it.
2011/05/13
[ "https://Stackoverflow.com/questions/5987935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681686/" ]
If as you indicated elsewhere that you designed all the classes then you could put that number property in an in interface and have all the classes implement that interface. Then, in the linq query, use the interface.
If you truly do not have a common type that you can reduce to and for some reason cannot introduce such a type, then you may be able to use the dynamic keyword. I don't have access to a compiler at the moment, but can your method accept a collection of dynamic objects and query them? For example: ``` IEnumerable<dynamic> collection = ...; var numbers = from x in collection select x.Number; ```
5,987,935
I have an array of unknown (to the current method) class objects. I do know that each class has a property called "Number". I am trying to write a LINQ query where I am looking for the object with the next Number in sequence. AKA, I'm at Number 8, use a LINQ query to find the object where Number=9. Anyone got a suggestion? Also, I use reflection often so don't worry about avoiding it.
2011/05/13
[ "https://Stackoverflow.com/questions/5987935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681686/" ]
You can create an interface - INumber with a property Number. Each of the objects that you are having in the array can implemen this interface. That way, you will have an array of known type INumber. This way your query will be easy to debug and maintain.
If you truly do not have a common type that you can reduce to and for some reason cannot introduce such a type, then you may be able to use the dynamic keyword. I don't have access to a compiler at the moment, but can your method accept a collection of dynamic objects and query them? For example: ``` IEnumerable<dynamic> collection = ...; var numbers = from x in collection select x.Number; ```
5,987,935
I have an array of unknown (to the current method) class objects. I do know that each class has a property called "Number". I am trying to write a LINQ query where I am looking for the object with the next Number in sequence. AKA, I'm at Number 8, use a LINQ query to find the object where Number=9. Anyone got a suggestion? Also, I use reflection often so don't worry about avoiding it.
2011/05/13
[ "https://Stackoverflow.com/questions/5987935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681686/" ]
If the objects all inherit from a known interface then you can cast them, e.g. ``` var next = items.Cast<IHasNumber>.FirstOrDefault(x => x.Number == index + 1); ``` If they don't, then you can use `dynamic`, e.g. ``` var next = items.Cast<dynamic>.FirstOrDefault(x => x.Number == index + 1); ``` If you have control of the types, then I would make them implement an interface so that you can use the first method, which should be significantly faster than the second. In that case, your collection will probably be `IEnumerable<IHasNumber>` to start with and you won't even have to cast.
If you truly do not have a common type that you can reduce to and for some reason cannot introduce such a type, then you may be able to use the dynamic keyword. I don't have access to a compiler at the moment, but can your method accept a collection of dynamic objects and query them? For example: ``` IEnumerable<dynamic> collection = ...; var numbers = from x in collection select x.Number; ```
5,987,935
I have an array of unknown (to the current method) class objects. I do know that each class has a property called "Number". I am trying to write a LINQ query where I am looking for the object with the next Number in sequence. AKA, I'm at Number 8, use a LINQ query to find the object where Number=9. Anyone got a suggestion? Also, I use reflection often so don't worry about avoiding it.
2011/05/13
[ "https://Stackoverflow.com/questions/5987935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681686/" ]
If as you indicated elsewhere that you designed all the classes then you could put that number property in an in interface and have all the classes implement that interface. Then, in the linq query, use the interface.
To avoid performance issues you can use the following method: ``` static void Main(string[] args) { object[] objs = GetInitialData(); var accessor = GetGetterHelper<int>(objs[0].GetType(), "Number"); var res = from a in objs where accessor(a) == 7 select a; } static Func<object, T> GetGetterHelper<T>(Type type, string methodName) { var methodInfo = type.GetProperty(methodName).GetGetMethod(); return x => (T)methodInfo.Invoke(x, new object[] {}); } ```
5,987,935
I have an array of unknown (to the current method) class objects. I do know that each class has a property called "Number". I am trying to write a LINQ query where I am looking for the object with the next Number in sequence. AKA, I'm at Number 8, use a LINQ query to find the object where Number=9. Anyone got a suggestion? Also, I use reflection often so don't worry about avoiding it.
2011/05/13
[ "https://Stackoverflow.com/questions/5987935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681686/" ]
You can create an interface - INumber with a property Number. Each of the objects that you are having in the array can implemen this interface. That way, you will have an array of known type INumber. This way your query will be easy to debug and maintain.
To avoid performance issues you can use the following method: ``` static void Main(string[] args) { object[] objs = GetInitialData(); var accessor = GetGetterHelper<int>(objs[0].GetType(), "Number"); var res = from a in objs where accessor(a) == 7 select a; } static Func<object, T> GetGetterHelper<T>(Type type, string methodName) { var methodInfo = type.GetProperty(methodName).GetGetMethod(); return x => (T)methodInfo.Invoke(x, new object[] {}); } ```
5,987,935
I have an array of unknown (to the current method) class objects. I do know that each class has a property called "Number". I am trying to write a LINQ query where I am looking for the object with the next Number in sequence. AKA, I'm at Number 8, use a LINQ query to find the object where Number=9. Anyone got a suggestion? Also, I use reflection often so don't worry about avoiding it.
2011/05/13
[ "https://Stackoverflow.com/questions/5987935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681686/" ]
If the objects all inherit from a known interface then you can cast them, e.g. ``` var next = items.Cast<IHasNumber>.FirstOrDefault(x => x.Number == index + 1); ``` If they don't, then you can use `dynamic`, e.g. ``` var next = items.Cast<dynamic>.FirstOrDefault(x => x.Number == index + 1); ``` If you have control of the types, then I would make them implement an interface so that you can use the first method, which should be significantly faster than the second. In that case, your collection will probably be `IEnumerable<IHasNumber>` to start with and you won't even have to cast.
To avoid performance issues you can use the following method: ``` static void Main(string[] args) { object[] objs = GetInitialData(); var accessor = GetGetterHelper<int>(objs[0].GetType(), "Number"); var res = from a in objs where accessor(a) == 7 select a; } static Func<object, T> GetGetterHelper<T>(Type type, string methodName) { var methodInfo = type.GetProperty(methodName).GetGetMethod(); return x => (T)methodInfo.Invoke(x, new object[] {}); } ```
9,818,772
<http://ideone.com/u0bVy> the link above contain the code that i wrote for a class project.I have a question about the output file for this code.The output file was created but was empty why is this happen ? I don't see anything wrong with the output function.Could it be that I did something wrong in the other functions? thank you here is the data for the code ``` LYSACEK Evan 1 7.5 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 2 10.0 1 2 2 1 1 1 1 2 0 1 1 1 3 3.0 1 2 2 2 1 0 1 2 1 1 1 2 4 3.1 1 1 1 1 1 0 0 0 1 0 1 0 5 1.7-3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 6 2.1 0 0 1 1 1 1 1 1 1 1 1 1 7 3.1 0 0 1 1 0 0 1 1 1 1 1 1 8 3.5 0 1 1 2 1 1 1 1 1 1 0 1 WEIR Johnny 1 7.5 2 2 2 2 1 1 1 1 1 2 1 1 2 10.0 1 1 1 1 2 0 1 1 1 1 2 1 3 3.0 1 1 1 2 1 0 1 1 2 2 2 2 4 3.1 1 2 1 2 1 1 0 0 2 1 1 0 5 5.5 0 -1 0 -1 -1 0 -1 -1 1 -2 -2 -2 6 1.3 1 1 1 2 1 1 1 0 1 1 1 2 7 3.1 0 1 1 1 1 0 0 1 2 1 1 1 8 3.0 -1 1 1 2 1 0 1 0 2 1 -1 1 PLUSHENKO Evgeni 1 13.0 0 2 1 1 1 0 1 0 1 1 1 1 2 7.5 1 2 2 2 2 1 2 1 2 2 2 2 3 6.0 2 1 1 1 1 0 0 2 1 2 1 2 4 2.3 2 1 1 1 1 1 2 1 1 1 1 1 5 3.4 2 2 2 2 1 2 3 3 2 3 2 1 6 2.1 1 1 1 2 2 0 0 0 1 2 1 1 7 3.1 1 0 2 2 1 1 1 2 2 2 2 1 8 3.5 1 1 2 2 1 1 1 1 2 2 1 1 SAVOIE Matthew 1 3.0 0 0 0 1 0 0 0 0 0 0 0 -1 2 7.5 1 2 2 1 1 1 1 1 1 1 2 2 3 9.5 0 1 1 0 0 0 0 0 0 0 1 1 4 3.1 1 1 1 1 1 1 0 0 1 1 0 0 5 1.9 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 -3 6 2.1 0 0 1 0 1 0 0 1 1 1 1 1 7 3.1 0 0 1 0 0 0 1 1 2 0 2 1 8 3.0 0 0 1 1 1 0 1 1 1 1 1 1 ```
2012/03/22
[ "https://Stackoverflow.com/questions/9818772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1276591/" ]
In the absence of errors in the console and no visible activity on the page it usually means that the page is not set-up correctly so: * Make sure your host page is set up correctly as per the [documentation](http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideHostPage). * Make sure you are using [standards mode](http://code.google.com/webtoolkit/doc/latest/DevGuideUiPanels.html#Standards) and your page declares the HTML5 doctype `<!DOCTYPE html>`. Post more code/information if you would like a further discussion.
The strange part about this issue is that it does work, but with any other browser, including IE!? And not Chrome?! What I did was to follow step by step the GWT tutorial to create an app (StockWatcher) In development mode it worked flawlessly in Chrome, but after I compiled the project, the result was no longer working inside Chrome, though the rest of the browsers worked! So, try to see if the production version works inside other browsers.
56,168,993
I made a project where I write some stuff in a csv file, but special characters don't work correctly, for example characters such as : à, é, ï.. So I changed my code, so that the fileWriter would be encoded in ISO-8859-1. ``` OutputStreamWriter o = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-1"); writer = new CSVWriter(o, ';', CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); ``` Most of the characters work, but the characters `'`, doesn't work correctly, it's shown as a `?`. Perhaps, I need to change encoding, but CSV is supposed to use ISO-8859-1. Do you have any suggestion?
2019/05/16
[ "https://Stackoverflow.com/questions/56168993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8598112/" ]
You can capture the words in a capturing surrounded by an optional preceding comma or an optional trailing comma. You can test the [regex here](https://regex101.com/r/5OHAIc/1): `,?([A-Za-z]+),?` ```js const pattern = /,?([A-Za-z]+),?/gm; const str = `,IGORA,GIANC,LOLLI`; let matches = []; let match; // Iterate until no match found while ((m = pattern.exec(str))) { // The first captured group is the match matches.push(m[1]); } console.log(matches); ```
Is this what you're looking for? Explanation: > > `\b` word boundary (starting or ending a word) > > > `\w` a word ([A-z]) > > > `{5}` 5 characters of previous > > > So it matches all 5-character words but not NANANANA ```js var str = 'IGORA,CIAOA,POPOP,NANANANA'; var arr = str.match(/\b\w{5}\b/g); console.log(arr); //['IGORA', 'CIAOA', 'POPOP'] ``` If you only wish to select words separated by commas and nothing else, you can test for them like so: > > `(?<=,\s*|^)` preceded by `,` with any number of trailing space, OR is the first word in list. > > > `(?=,\s*|$)` followed by `,` and any number of trailing spaces OR is last word in list. > > > In the following code, POPOP and MOMMA are rejected because they are not separated by a comma, and NANANANA fails because it is not 5 character. ```js var str = 'IGORA, CIAOA, POPOP MOMMA, NANANANA, MEOWI'; var arr = str.match(/(?<=,\s*|^)\b\w{5}\b(?=,\s*|$)/g); console.log(arr); //['IGORA', 'CIAOA', 'MEOWI'] ``` If you can't have any trailing spaces after the comma, just leave out the `\s*` from both `(?<=,\s*|^)` and `(?=,\s*|$)`.
56,168,993
I made a project where I write some stuff in a csv file, but special characters don't work correctly, for example characters such as : à, é, ï.. So I changed my code, so that the fileWriter would be encoded in ISO-8859-1. ``` OutputStreamWriter o = new OutputStreamWriter(new FileOutputStream(file), "ISO-8859-1"); writer = new CSVWriter(o, ';', CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END); ``` Most of the characters work, but the characters `'`, doesn't work correctly, it's shown as a `?`. Perhaps, I need to change encoding, but CSV is supposed to use ISO-8859-1. Do you have any suggestion?
2019/05/16
[ "https://Stackoverflow.com/questions/56168993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8598112/" ]
You can capture the words in a capturing surrounded by an optional preceding comma or an optional trailing comma. You can test the [regex here](https://regex101.com/r/5OHAIc/1): `,?([A-Za-z]+),?` ```js const pattern = /,?([A-Za-z]+),?/gm; const str = `,IGORA,GIANC,LOLLI`; let matches = []; let match; // Iterate until no match found while ((m = pattern.exec(str))) { // The first captured group is the match matches.push(m[1]); } console.log(matches); ```
There are other ways to do this, but I found that one of the simple ways is by using the `replace` method, as it can replace all instances that match that regex. For example: ```js var regex = /^(?:(?:\,([A-Za-z]{5}))?)+$/g; var str = ',GIANC,IGORA'; var arr = []; str.replace(regex, function(match) { arr[arr.length] = match; return match; }); console.log(arr); ``` Also, in my code snippet you can see that there is an extra coma in each string, you can solve that by changing line 5 to `arr[arr.length] = match.replace(/^,/, '')`.
50,279,501
Can't make friends out of my AJAX and MVC 6 controller. This is how I define AJAX call for *SetFormValues* POST-action: **Index.cshtml** ```js $.ajax({ type: "Post", url: "Home/SetFormValues", data: { Name: name, Phone: phone }, dataType: "json", success: function (result) { SuccessFunction(result) }, error: function () { alert("ALARM!"); }, async: false }) ``` I see that the controller works and executes *SetFormValues* action which is defined as the following: **HomeController.cs** ```cs [HttpPost] public JsonResult SetFormValues(string Name, string Phone) { string NameErrorStr = string.IsNullOrWhiteSpace(Name) ? "Обязательное поле" : string.Empty; string PhoneErrorStr = string.IsNullOrWhiteSpace(Phone) ? "Обязательное поле" : string.Empty; var result = new { NameError = NameErrorStr, PhoneError = PhoneErrorStr }; var jresult = Json(result); return jresult; } ``` Debugger shows that action executes and my resulting JSON object fills correctly: [![Debugger enters SetFormValues action correctly](https://i.stack.imgur.com/HLDIC.jpg)](https://i.stack.imgur.com/HLDIC.jpg) Finally, his is how *SuccessFunction(result)* is defined: **Index.cshtml again** ```js function SuccessFunction(result) { alert("Success function shit executed. result=" + result + "NameError=" + result.NameError + ". PhoneError=" + result.PhoneError); $("#nameerror").append(result.NameError); $("#phoneerror").append(result.PhoneError); } ``` Function works, alert is raised but result stay 'undefined' no matter what I do: [![enter image description here](https://i.stack.imgur.com/vaxdC.jpg)](https://i.stack.imgur.com/vaxdC.jpg) ``` result = [object Object] result.val = undefined ``` Maybe I have to deserialize JSON result properly or fill some properties in it's declaration above, I don't know. I'm using the lattest libraries for jquery, validate and unobtrusive. I also tried *JSON.parse(result)*, as it mentioned in the lattest jQuery specification, but it didn't work as well. Please, help me :)
2018/05/10
[ "https://Stackoverflow.com/questions/50279501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3910087/" ]
In asp.net core, by default, the serializer uses **`camelCase`** property names for json serialization. So your result will be like this ``` {"nameError":"some message","phoneError":"some message here"} ``` **Javascript is case sensitive**. So use the correct case ``` $("#nameerror").append(result.nameError); $("#phoneerror").append(result.phoneError); ``` For reference : [MVC now serializes JSON with camel case names by default](https://github.com/aspnet/Mvc/issues/4842)
its working perfectly when i have added this line in startup file ``` public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver()); services.AddDbContext<DataContext>(option => option.UseSqlServer(Configuration.GetConnectionString("DbCrudOperation"))); } function Edit(id) { $.ajax({ type: 'GET', url: "/AjacCrud/EditPahe/" + id, dataType: 'JSON', contentType: "application/json", success: function (response) { $("#nameEmp").val(response.ID); console.log(response.ID); }, error: function (GetError) { alert(GetError.responseText); } }); }; ```
3,307,257
I Perfectly understand that this is not allowed by the App Store Policy but is programmatically possible to create ad hoc wireless network with the iphone SDK, with "is possible" I mean if the iPhone 3G and/or 3GS hardware support this "feauture" and if exists some kind of low-level api to do this. This question does NOT contemplate the jailbreak
2010/07/22
[ "https://Stackoverflow.com/questions/3307257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76593/" ]
Not with the SDK, no. Third-party apps don't get much access to the wireless hardware, and creating networks would definitely be a no-go.
I don't believe so; however, it's possible that there's something undocumented I'm not aware of.
60,128,156
I was working on a dropdown list and wanted the results shown in the second dropdown to be filtered according to the option selected in the first dropdown. My EJS file is as follows:- ``` <div class="form-group"> <label for="">Category</label> <select id="list" name="mainCategory" id="maincategory-dropdown" onchange="getSelectValue()" class="form-control"> <% mainCategories.forEach(function(cat){ %> <option value="<%= cat.slug %>" <% if (cat.slug == mainCategory) { %> selected="selected" <% } %> ><%= cat.title %></option> <% }); %> </select> </div> <div class="form-group"> <label for="">Subcategory</label> <select name="category" id="category-dropdown" class="form-control"> <% categories.forEach(function(cat){ %> <option value="<%= cat.slug %>" <% if (cat.slug == category) { %> selected="selected" <% } %> ><%= cat.title %></option> <% }); %> </select> </div> ``` I want the values in the subcategory dropdown to be shown as per the option selected in the category dropdown. I am getting the values from the backend. The JS file is as follows:- ``` router.get('/edit-product/:id',ensureAuthenticated, function (req, res) { MainCategory.find(function(err,mainCategories){ Category.find(function (err, categories) { Product.findById(req.params.id, function (err, p) { if (err) { console.log(err); res.redirect('/admin/products'); } else { var galleryDir = 'public/assets/img/products/' + p._id + '/gallery'; // var recommendationDir = 'public/assets/img/products/' + p._id + '/recommendation'; var galleryImages = null; // var recommendationImages = null; fs.readdir(galleryDir, function (err, files) { if (err) { console.log(err); } else { galleryImages = files; // console.log("The gallery image is" + galleryImages) //console.log(p); res.render('admin/edit_product', { product:p, title: p.title, description: p.description, categories: categories, category: p.category.replace(/\s+/g, '-').toLowerCase(), mainCategories: mainCategories, mainCategory: p.mainCategory.replace(/\s+/g, '-').toLowerCase(), mainImage: p.mainImage, thumbImage1 : p.thumbImage1, thumbImage2 : p.thumbImage2, thumbImage3: p.thumbImage3, recommendationImage1: p.recommendationImage1, recommendationImage2: p.recommendationImage2, recommendationImage3: p.recommendationImage3, recommendationUrl1: p.recommendationUrl1, recommendationUrl2: p.recommendationUrl2, recommendationUrl3: p.recommendationUrl3, galleryImages: galleryImages, id: p._id, productID:p.productID }); } }); } }); }); }) }); ``` I am stuck in it a bit. Please help me out
2020/02/08
[ "https://Stackoverflow.com/questions/60128156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7558969/" ]
If its Ok to use a pure javascript (jQuery) solution the following might help, its just filter the dropdown options based on `data-dep` attribute and return filtered options, or if you are looking for advanced dropdown options dependency check this [jQuery plugin](https://github.com/kartik-v/dependent-dropdown). ```js let $select1 = $( '#select1' ), $select2 = $( '#select2' ), $options = $select2.find( 'option' ); $select1.on( 'change', function() { $select2.html( $options.filter( '[data-dep="' + this.value + '"]' ) ); } ).trigger( 'change' ); ``` ```css option { margin: 0.5em; } ``` ```html <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <div class="col-xs-6"> <select class="form-control" name="select1" id="select1"> <option value="1">option 1</option> <option value="2">option 2</option> <option value="3">option 3</option> <option value="4">option 4</option> </select> </div> <div class="col-xs-6"> <select class="form-control" name="select2" id="select2"> <option value="1" data-dep="1">option 1 - 1</option> <option value="2" data-dep="1">option 1 - 2</option> <option value="3" data-dep="1">option 1 - 3</option> <option value="4" data-dep="2">option 2 - 1</option> <option value="5" data-dep="2">option 2 - 2</option> <option value="6" data-dep="3">option 3 - 1</option> <option value="7" data-dep="3">option 3 - 2</option> <option value="8" data-dep="3">option 3 - 3</option> <option value="9" data-dep="4">option 4 - 1<option> </select> </div> ```
```js const categories = ['a', 'b', 'c']; const subCategories = { a: ['a-1', 'a-2', 'a-3'], b: ['b-1', 'b-2', 'b-3'], c: ['c-1', 'c-2', 'c-3'], }; const catSelect = document.getElementById('cat'); const subCatSelect = document.getElementById('subcat'); catSelect.innerHTML = categories.map(cat => `<option val=${cat}>${cat}</option>`).join(''); catSelect.addEventListener('change', setSubcategories); setSubcategories(); function setSubcategories() { subCatSelect.innerHTML = subCategories[catSelect.value].map(cat => `<option val=${cat}>${cat}</option>`).join(''); } ``` ```html <select id="cat"></select> <select id="subcat"></select> ```
29,066,399
How to implement func function: ``` func(); // console.log('state1'); func(); // console.log('state2'); func(); // console.log('state1'); func(); // console.log('state2'); //... ``` But without setting properties to func and variables in closures.
2015/03/15
[ "https://Stackoverflow.com/questions/29066399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626347/" ]
Well, using global variables hasn't been denied, so I don't see a reason for this not to be a valid answer: ``` var func = function() { if (typeof state == 'undefined') { state = false; } state = !state; console.log(state ? 'state1' : 'state2'); }; ``` JSFiddle: <http://jsfiddle.net/zo94u90f/>
This does not match the "no-closures" requirement. But I don't know of any way to do that except to use global variables. This seems quite clean though. What's the objection to closure variables? ``` var func = (function() { var calls = 0; var states = ["state1", "state2"]; return function() { var state = states[calls++ % states.length]; console.log(state); }; }()); ```
29,066,399
How to implement func function: ``` func(); // console.log('state1'); func(); // console.log('state2'); func(); // console.log('state1'); func(); // console.log('state2'); //... ``` But without setting properties to func and variables in closures.
2015/03/15
[ "https://Stackoverflow.com/questions/29066399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626347/" ]
I find a trick: ``` func = (function* (){ while (true) { console.log('state1'); yield null; console.log('state2'); yield null; } })() func = func.next.bind(func); func(); func(); ```
This does not match the "no-closures" requirement. But I don't know of any way to do that except to use global variables. This seems quite clean though. What's the objection to closure variables? ``` var func = (function() { var calls = 0; var states = ["state1", "state2"]; return function() { var state = states[calls++ % states.length]; console.log(state); }; }()); ```
29,066,399
How to implement func function: ``` func(); // console.log('state1'); func(); // console.log('state2'); func(); // console.log('state1'); func(); // console.log('state2'); //... ``` But without setting properties to func and variables in closures.
2015/03/15
[ "https://Stackoverflow.com/questions/29066399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/626347/" ]
Well, using global variables hasn't been denied, so I don't see a reason for this not to be a valid answer: ``` var func = function() { if (typeof state == 'undefined') { state = false; } state = !state; console.log(state ? 'state1' : 'state2'); }; ``` JSFiddle: <http://jsfiddle.net/zo94u90f/>
I find a trick: ``` func = (function* (){ while (true) { console.log('state1'); yield null; console.log('state2'); yield null; } })() func = func.next.bind(func); func(); func(); ```
464,331
I have very little knowledge about power draw / conversions etc. I would like to power a Kinect v2 Sensor from a USB Power bank. I saw the USB C and QC3.0 on this [powerbank](https://www.amazon.co.uk/gp/product/B073FJ6Z8D/ref=ppx_yo_dt_b_asin_title_o01_s01?ie=UTF8&psc=1) has between 9 and 12V output. I have read although the Kinect sensor is 12V 2.67A it only draws 16w per hour according to [this user](https://www.reddit.com/r/kinect/comments/2yofgv/power_consumption_of_kinect_for_windows_v2/). So I would like to know can I splice up a USB-C cable (using red & black wires) to a wire that connects to my [Kinect to Windows Adapter](https://www.amazon.co.uk/gp/product/B07HT4224B/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1) Any advice would be great thanks. The goal is to have a mobile scanner with at least 3 to 4 hours battery life.
2019/10/24
[ "https://electronics.stackexchange.com/questions/464331", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/234767/" ]
> > has between 9 and 12V output > > > It's not that easy. To get power from that bank, you need to speak the USB-C PD protocol. Otherwise, you'd only be getting "normal" VUSB of 5V at low current capability. That's a pretty complicated protocol, and requires you to afterwards handle quite a bit of power, so that's why you'd typically do that by buying a special chip to talk to the power source. Frankly, considering the level of understanding for electrical units, this is probably nothing you'll achieve on your own. You'd be better off just buying a cheaper 5V power bank and buying a (good) 5V -> 12V step up converter.
As my understanding power bank circuit uses a bi-directional buck-boost converter. When you connect for charging, it boosts the voltage to 12V and charge battery. When you connect mobile for charging, the circuit steps down the 12V into 5V. So you cannot draw 12V from power bank USB output. What you can do is, you can solder wires from the internal battery which is not really recommended because you will break the Li-Ion protection mechanism and accidents might occur.
464,331
I have very little knowledge about power draw / conversions etc. I would like to power a Kinect v2 Sensor from a USB Power bank. I saw the USB C and QC3.0 on this [powerbank](https://www.amazon.co.uk/gp/product/B073FJ6Z8D/ref=ppx_yo_dt_b_asin_title_o01_s01?ie=UTF8&psc=1) has between 9 and 12V output. I have read although the Kinect sensor is 12V 2.67A it only draws 16w per hour according to [this user](https://www.reddit.com/r/kinect/comments/2yofgv/power_consumption_of_kinect_for_windows_v2/). So I would like to know can I splice up a USB-C cable (using red & black wires) to a wire that connects to my [Kinect to Windows Adapter](https://www.amazon.co.uk/gp/product/B07HT4224B/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1) Any advice would be great thanks. The goal is to have a mobile scanner with at least 3 to 4 hours battery life.
2019/10/24
[ "https://electronics.stackexchange.com/questions/464331", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/234767/" ]
> > has between 9 and 12V output > > > It's not that easy. To get power from that bank, you need to speak the USB-C PD protocol. Otherwise, you'd only be getting "normal" VUSB of 5V at low current capability. That's a pretty complicated protocol, and requires you to afterwards handle quite a bit of power, so that's why you'd typically do that by buying a special chip to talk to the power source. Frankly, considering the level of understanding for electrical units, this is probably nothing you'll achieve on your own. You'd be better off just buying a cheaper 5V power bank and buying a (good) 5V -> 12V step up converter.
If the voltage needed is between 9V and 12V you could use an 11.1V RC car/plane battery, but the Kinect might need too much current and the battery would be low in a couple of hours.
464,331
I have very little knowledge about power draw / conversions etc. I would like to power a Kinect v2 Sensor from a USB Power bank. I saw the USB C and QC3.0 on this [powerbank](https://www.amazon.co.uk/gp/product/B073FJ6Z8D/ref=ppx_yo_dt_b_asin_title_o01_s01?ie=UTF8&psc=1) has between 9 and 12V output. I have read although the Kinect sensor is 12V 2.67A it only draws 16w per hour according to [this user](https://www.reddit.com/r/kinect/comments/2yofgv/power_consumption_of_kinect_for_windows_v2/). So I would like to know can I splice up a USB-C cable (using red & black wires) to a wire that connects to my [Kinect to Windows Adapter](https://www.amazon.co.uk/gp/product/B07HT4224B/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1) Any advice would be great thanks. The goal is to have a mobile scanner with at least 3 to 4 hours battery life.
2019/10/24
[ "https://electronics.stackexchange.com/questions/464331", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/234767/" ]
If the voltage needed is between 9V and 12V you could use an 11.1V RC car/plane battery, but the Kinect might need too much current and the battery would be low in a couple of hours.
As my understanding power bank circuit uses a bi-directional buck-boost converter. When you connect for charging, it boosts the voltage to 12V and charge battery. When you connect mobile for charging, the circuit steps down the 12V into 5V. So you cannot draw 12V from power bank USB output. What you can do is, you can solder wires from the internal battery which is not really recommended because you will break the Li-Ion protection mechanism and accidents might occur.
28,530,209
How can I centrally align 2 columns taking up 1/3 of the width in bootstrap? I tried searching Google and have found solutions with 3 columns but I need 2. Thanks for your answers **HTML** ``` <div class="row circles"> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="img-circle"></div> <strong>Loren ipsum</strong> <div class="text">Og at profilen gir et solid og Og at profilen gir et solid og </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="img-circle"></div> <strong>Loren ipsum</strong> <div class="text">Og at profilen gir et solid og Og at profilen gir et solid og </div> </div> </div> ``` **CSS**: ``` ul.circles { list-style-type: none; margin: 0px auto 0px; } ul.circles p { text-align: center; } ul.circles .text,strong { display: block; text-align: center; margin: 20px 0px 20px; } .img-circle { background-color: #2d0e1e; height: 200px; width: 200px; margin: 0px auto; margin-top: 50px; } ``` Here's an image for example: ![Example of what I need](https://i.stack.imgur.com/aSLaw.png)
2015/02/15
[ "https://Stackoverflow.com/questions/28530209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You could offset your first column, using the `col-lg-offset-2` and `col-md-offset-2` classes: ``` <div class="row circles"> <div class="col-lg-4 col-md-4 col-lg-offset-2 col-md-offset-2 col-sm-6 col-xs-12"> <div class="img-circle"></div> <strong>Loren ipsum</strong> <div class="text">Og at profilen gir et solid og Og at profilen gir et solid og </div> </div> <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="img-circle"></div> <strong>Loren ipsum</strong> <div class="text">Og at profilen gir et solid og Og at profilen gir et solid og </div> </div> </div> ``` Note: In this particular case, your `col-md-*` classes are redundant and can be removed. [**Bootply**](http://www.bootply.com/mQ51DC289d)
I'm not sure what you want but in your CSS you could use the following: ``` .row.circles {margin: 0px auto;} ``` Would that work?
10,958,191
Im tring to send a simple email with this code using google app engine. But nothing happens, is there something i have to configure in order to use the mail api? This runs on localhost. I am using gmail as mail host. ``` String host = "smtp.google.com"; String to = "example@yahoo.fr"; String from = "example@gmail.com"; String subject = "this is a test"; String messageText = "test"; boolean sessionDebug = false; // Create some properties and get the default Session. Properties props = System.getProperties(); props.put("mail.host", host); props.put("mail.transport.protocol", "smtp"); Session mailSession = Session.getDefaultInstance(props, null); // Set debug on the Session // Passing false will not echo debug info, and passing True will. mailSession.setDebug(sessionDebug); // Instantiate a new MimeMessage and fill it with the // required information. Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(messageText); // Hand the message to the default transport service // for delivery. Transport.send(msg); ```
2012/06/09
[ "https://Stackoverflow.com/questions/10958191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1401253/" ]
When running the AppEngine development server locally, anything sent via the Mail service will not actually be sent - it will just be logged to the console See [here](https://developers.google.com/appengine/docs/java/mail/overview#Development_Server) > > When an application running in the development server calls the Mail service to send an email message, the message is printed to the log. The Java development server does not send the email message. > > > In addition, the `from` address must be (from [here](https://developers.google.com/appengine/docs/java/mail/usingjavamail#Senders_and_Recipients)) * The email of an app administrator * The email of the currently logged in user who signed in using a Google Account * A valid email receiving address from the app
The sender should be your own Gmail email address instead of `example@gmail.com` Reason is because the SMTP server needs to authenticate you.
10,958,191
Im tring to send a simple email with this code using google app engine. But nothing happens, is there something i have to configure in order to use the mail api? This runs on localhost. I am using gmail as mail host. ``` String host = "smtp.google.com"; String to = "example@yahoo.fr"; String from = "example@gmail.com"; String subject = "this is a test"; String messageText = "test"; boolean sessionDebug = false; // Create some properties and get the default Session. Properties props = System.getProperties(); props.put("mail.host", host); props.put("mail.transport.protocol", "smtp"); Session mailSession = Session.getDefaultInstance(props, null); // Set debug on the Session // Passing false will not echo debug info, and passing True will. mailSession.setDebug(sessionDebug); // Instantiate a new MimeMessage and fill it with the // required information. Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(messageText); // Hand the message to the default transport service // for delivery. Transport.send(msg); ```
2012/06/09
[ "https://Stackoverflow.com/questions/10958191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1401253/" ]
The sender should be your own Gmail email address instead of `example@gmail.com` Reason is because the SMTP server needs to authenticate you.
Other than email not working on localhost or due to the sender email not being the authenticated one, I have experienced that email does not work even when the version is not the default one. I could not find this documented anywhere. For example: `nondefaultversion-dot-myapp.appspot.com` (email does not work, no error logs) `myapp.appspot.com` (email works) Please confirm if others have also faced this issue.
10,958,191
Im tring to send a simple email with this code using google app engine. But nothing happens, is there something i have to configure in order to use the mail api? This runs on localhost. I am using gmail as mail host. ``` String host = "smtp.google.com"; String to = "example@yahoo.fr"; String from = "example@gmail.com"; String subject = "this is a test"; String messageText = "test"; boolean sessionDebug = false; // Create some properties and get the default Session. Properties props = System.getProperties(); props.put("mail.host", host); props.put("mail.transport.protocol", "smtp"); Session mailSession = Session.getDefaultInstance(props, null); // Set debug on the Session // Passing false will not echo debug info, and passing True will. mailSession.setDebug(sessionDebug); // Instantiate a new MimeMessage and fill it with the // required information. Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(messageText); // Hand the message to the default transport service // for delivery. Transport.send(msg); ```
2012/06/09
[ "https://Stackoverflow.com/questions/10958191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1401253/" ]
When running the AppEngine development server locally, anything sent via the Mail service will not actually be sent - it will just be logged to the console See [here](https://developers.google.com/appengine/docs/java/mail/overview#Development_Server) > > When an application running in the development server calls the Mail service to send an email message, the message is printed to the log. The Java development server does not send the email message. > > > In addition, the `from` address must be (from [here](https://developers.google.com/appengine/docs/java/mail/usingjavamail#Senders_and_Recipients)) * The email of an app administrator * The email of the currently logged in user who signed in using a Google Account * A valid email receiving address from the app
Other than email not working on localhost or due to the sender email not being the authenticated one, I have experienced that email does not work even when the version is not the default one. I could not find this documented anywhere. For example: `nondefaultversion-dot-myapp.appspot.com` (email does not work, no error logs) `myapp.appspot.com` (email works) Please confirm if others have also faced this issue.
10,958,191
Im tring to send a simple email with this code using google app engine. But nothing happens, is there something i have to configure in order to use the mail api? This runs on localhost. I am using gmail as mail host. ``` String host = "smtp.google.com"; String to = "example@yahoo.fr"; String from = "example@gmail.com"; String subject = "this is a test"; String messageText = "test"; boolean sessionDebug = false; // Create some properties and get the default Session. Properties props = System.getProperties(); props.put("mail.host", host); props.put("mail.transport.protocol", "smtp"); Session mailSession = Session.getDefaultInstance(props, null); // Set debug on the Session // Passing false will not echo debug info, and passing True will. mailSession.setDebug(sessionDebug); // Instantiate a new MimeMessage and fill it with the // required information. Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(messageText); // Hand the message to the default transport service // for delivery. Transport.send(msg); ```
2012/06/09
[ "https://Stackoverflow.com/questions/10958191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1401253/" ]
When running the AppEngine development server locally, anything sent via the Mail service will not actually be sent - it will just be logged to the console See [here](https://developers.google.com/appengine/docs/java/mail/overview#Development_Server) > > When an application running in the development server calls the Mail service to send an email message, the message is printed to the log. The Java development server does not send the email message. > > > In addition, the `from` address must be (from [here](https://developers.google.com/appengine/docs/java/mail/usingjavamail#Senders_and_Recipients)) * The email of an app administrator * The email of the currently logged in user who signed in using a Google Account * A valid email receiving address from the app
Apparently, GAE doesn't allow the use of the admin accounts any more. you need to use the service account: `project-id@appspot.gserviceaccount.com` My previous projects still work with admin accounts, but the recently created projects just don't allow me to use any of the admin accounts.
10,958,191
Im tring to send a simple email with this code using google app engine. But nothing happens, is there something i have to configure in order to use the mail api? This runs on localhost. I am using gmail as mail host. ``` String host = "smtp.google.com"; String to = "example@yahoo.fr"; String from = "example@gmail.com"; String subject = "this is a test"; String messageText = "test"; boolean sessionDebug = false; // Create some properties and get the default Session. Properties props = System.getProperties(); props.put("mail.host", host); props.put("mail.transport.protocol", "smtp"); Session mailSession = Session.getDefaultInstance(props, null); // Set debug on the Session // Passing false will not echo debug info, and passing True will. mailSession.setDebug(sessionDebug); // Instantiate a new MimeMessage and fill it with the // required information. Message msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(to) }; msg.setRecipients(Message.RecipientType.TO, address); msg.setSubject(subject); msg.setSentDate(new Date()); msg.setText(messageText); // Hand the message to the default transport service // for delivery. Transport.send(msg); ```
2012/06/09
[ "https://Stackoverflow.com/questions/10958191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1401253/" ]
Apparently, GAE doesn't allow the use of the admin accounts any more. you need to use the service account: `project-id@appspot.gserviceaccount.com` My previous projects still work with admin accounts, but the recently created projects just don't allow me to use any of the admin accounts.
Other than email not working on localhost or due to the sender email not being the authenticated one, I have experienced that email does not work even when the version is not the default one. I could not find this documented anywhere. For example: `nondefaultversion-dot-myapp.appspot.com` (email does not work, no error logs) `myapp.appspot.com` (email works) Please confirm if others have also faced this issue.
19,790,642
Is it possible to pass an hidden field value from Razor View to Controller inside or tag? As the field is **hidden**, it is really a problem to pass its value to the Controller. On the other hand I think the only way to pass this hidden field is using input field inside hyperlink. How to create a code like below? ``` <a href="/Admin/Delete?ApplicantID=44"> <img class="myclass" src="../../Content/delete.png" title="Delete" /> <input type="hidden" value= "Delete" /></a> ``` **Updates** **View:** ``` ... grid.Column("Actions", format: (item) => new HtmlString( @Html.ActionImage("../../Content/detail.png", "Detail", "icon-link", "Detail", "Admin", new { applicantId = item.ApplicantID }).ToString() + @Html.ActionImage("../../Content/edit.png", "Edit", "icon-link", "Edit", "Admin", new { applicantId = item.ApplicantID }).ToString() + @Html.ActionImage("../../Content/delete.png", "Delete", "icon-link", "Delete", "Admin", new { applicantId = item.ApplicantID }).ToString() ) ) ... ``` **Controller:** ``` [HttpPost] public ActionResult Delete(int applicantId) { Applicant deletedApplicant = repository.DeleteApplicant(applicantId); if (deletedApplicant != null) { TempData["message"] = string.Format("{0} was deleted", deletedApplicant.Name); } return RedirectToAction("Index"); } } ``` **Helper Method:** ``` public static MvcHtmlString ActionImage(this HtmlHelper html, string imagePath, string alt, string cssClass, string action, string controllerName, object routeValues) { var currentUrl = new UrlHelper(html.ViewContext.RequestContext); var imgTagBuilder = new TagBuilder("img"); imgTagBuilder.MergeAttribute("src", currentUrl.Content(imagePath)); imgTagBuilder.MergeAttribute("title", alt); imgTagBuilder.MergeAttribute("class", cssClass); string imgHtml = imgTagBuilder.ToString(TagRenderMode.SelfClosing); var anchorTagBuilder = new TagBuilder("a"); anchorTagBuilder.MergeAttribute("href", currentUrl.Action(action, controllerName, routeValues)); anchorTagBuilder.InnerHtml = imgHtml; string anchorHtml = anchorTagBuilder.ToString(TagRenderMode.Normal); return MvcHtmlString.Create(anchorHtml); } ```
2013/11/05
[ "https://Stackoverflow.com/questions/19790642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/836018/" ]
`<input>`, `<textarea>`, `<button>` and `<select>` element values are only passed during a form submission. Moreover, they are only passed on when assigned a `name` attribute. Clicking an anchor will not pass these values (unless you interject with some JavaScript and append it to the URL). The easiest method is to turn your link in to a mini form: ``` @using (Html.BeginForm("Delete", "Admin", FormMethod.POST, new { ApplicantID = @Model.ApplicantID })) { <!-- make sure to give this field a name --> <input type="hidden" name="???" value="Delete" /> <input type="image" src="@Url.Content("~/Content/delete.png")" title="Delete" /> } ``` Otherwise, use javascript and bind to the anchor's click event and inject the hidden input's value before proceeding.
Based on discussion below, try this. ``` @Ajax.ActionLink("Delete", "Delete", new { applicantid = item.applicantid }, new AjaxOptions { Confirm = "Delete?", HttpMethod = "POST", }, new { @class = "classname" }) a.classname { background: url(~/Content/delete.png) no-repeat top left; display: block; width: 150px; height: 150px; text-indent: -9999px; /* hides the link text */ } ``` NOTE: this does not need to be inside a form.
54,796,664
Hi i have a requirement to check on passwords . the password should not contain no more than 2 repetitive character. my password must contain atleast upper case, lower case, number and special characters #?!@$%^&\*- so if i have a password like for example Password123$ it is valid Passsword123$ it is invalid Passssword123$ it is invalid PPaassword123$$ valid PPaassword123$$$ it is invalid please help me thank you
2019/02/20
[ "https://Stackoverflow.com/questions/54796664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10985103/" ]
``` import { Button } from "@material-ui/core"; ``` Try this.
Install material ui with npm or yarn. This should be done from your project's main directory. ``` // with npm npm install @material-ui/core // with yarn yarn add @material-ui/core ``` Then, you can use `import Button from '@material-ui/core/Button';` at the top of your file.
54,796,664
Hi i have a requirement to check on passwords . the password should not contain no more than 2 repetitive character. my password must contain atleast upper case, lower case, number and special characters #?!@$%^&\*- so if i have a password like for example Password123$ it is valid Passsword123$ it is invalid Passssword123$ it is invalid PPaassword123$$ valid PPaassword123$$$ it is invalid please help me thank you
2019/02/20
[ "https://Stackoverflow.com/questions/54796664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10985103/" ]
``` import { Button } from "@material-ui/core"; ``` Try this.
Since this post is quite recent, I am pretty sure you followed the steps in [material-ui getting started](https://material-ui.com/getting-started/installation/). What you should do is check the version of material-ui core installed in your project. Within your package.json file, check your material-ui core version, it should look like this, ``` "dependencies": { "@babel/core": "^7.1.5", "@babel/runtime": "^7.1.5", "@date-io/moment": "0.0.2", "@material-ui/core": "^3.9.2", "@material-ui/icons": "^3.0.1", "@material-ui/lab": "^3.0.0-alpha.23", } ``` or you can just do > > npm list > > > to check all dependencies you have within your project. Find out the lastest and stable version they have on [npm material-ui/core](https://www.npmjs.com/package/@material-ui/core)
12,047,961
Suppose there is an array of intergers: ``` A[]={2, 2, 9, 8, 5, 7, 0, 6} ``` and a stencil: ``` B[]={1, 0, 0, 1, 1, 1, 0, 1} ``` My question is how could we rearrange A[] according to B[] such that if B[i]==1, B[j]==0, then A[i] will be guaranteed to precede A[j] in the new array, which should look like: ``` C[]={2, 8, 5, 7, 6, 2, 9, 0} ``` PS: I found the ["partition"](http://thrust.github.com/doc/group__partitioning.html) function was almost the answer except that it only supported predicate. Is there any workaround? Any hint is much appreciated!
2012/08/21
[ "https://Stackoverflow.com/questions/12047961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1587802/" ]
How about using **value.Address.City** and **value.Address.Street**?? The most common way to access JSON data is through dot notation. This is simply the object name followed by a period and then followed by the name/property you would like to access. <http://www.hunlock.com/blogs/Mastering_JSON_%28_JavaScript_Object_Notation_%29> For example, ``` $.each(data, function(key,value) { $('#companyDetails').append('<li>'+key+'<span class="ui-li-aside">'+ value.Address.Street + "," + value.Address.City +'</span></li>'); }); ``` For detail coding, ``` <html> <head> <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> function display(data) { $.each(data, function(key,value) { $('#companyDetails').append('<li>'+key+'<span class="ui-li-aside">'+ value.Address.Street + "," + value.Address.City +'</span></li>'); }); } $(document).ready(function() { var data = [ { "Name" : "ABC", "Company" : "AA Company", "Address" : { "Street" : "123 Main Street", "City" : "Yangon" } }, { "Name" : "DEF", "Company" : "BB Company", "Address" : { "Street" : "8941 Mandalay", "City" : "NaypiDaw" } } ]; display(data); }); </script> </head> <body> <div id="companyDetails"></div> </body> </html> ``` For you case that you do not know which data are in json file, ``` function display(data,flag) { $.each(data, function(key,value) { if ($.isPlainObject(value)) { if(flag == true) { $('#companyDetails').append('<b>' + "Company " + (key + 1) + '</b>'); } display(value,false); } else $('#companyDetails').append('<li>' + key + " : " +'<span class="ui-li-aside">'+ value +'</span></li>'); }); } ``` In calling display function, ``` var flag = true; display(data,flag); ``` Your output would be ![enter image description here](https://i.stack.imgur.com/cvuKO.png)I hope this would help.
I don't know if this is the most efficient way of doing this but I think it does what you want. Assumptions: Data is an array, with each array element being an object (hash). Tested in Chrome on Windows only. ``` <html> <head> <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> function read_record(data) { $.each(data, function(key,value) { if ($.isPlainObject(value)) read_record(value); else $('#details').append('<li>' + key + ' = ' + value + '</li>'); }); } $(document).ready(function() { var data = [ { "Name" : "John", "Company" : "Doe", "Address" : { "Street" : "123 Main Street", "City" : "San Francisco" } }, { "Name" : "Jane", "Company" : "Johnson", "Address" : { "Street" : "57 Heinz Lane", "City" : "Dallas" } } ]; read_record(data); }); </script> </head> <body> <ul id="details"></ul> </body> </html> ``` Produces: * Name = John * Company = Doe * Street = 123 Main Street * City = San Francisco * Name = Jane * Company = Johnson * Street = 57 Heinz Lane * City = Dallas
8,226
I need to completely remove the indicator, no flags, no abbr. nothing! I was able to do it in 10.04 using a gconf key that has no scheme and I heard that a proper scheme will be available in 10.10 but I can't find anything.
2010/10/19
[ "https://askubuntu.com/questions/8226", "https://askubuntu.com", "https://askubuntu.com/users/4384/" ]
Press Alt+F2 and enter [`gconf-editor`](https://askubuntu.com/questions/17249/how-do-i-use-the-gconf-editor) Now navigate to apps-->gnome\_settings\_daemon-->plugins-->keyboard and uncheck active Restart.
By the way, if you're removing it because of the big ugly (redundant) image in the 10.10 keyboard indicator, I've got a solution to that. I created a set of SVG flag images. If you install them and activate "show flags" in your g-conf editor then the text and ugly image both disappear. In their place you just have the one (much smaller) input language flag. I've posted the SVG's and full instructions here: <http://gnome-look.org/content/show.php/Language+Flags+for+Faenza+and+Elementary?content=133726>
8,226
I need to completely remove the indicator, no flags, no abbr. nothing! I was able to do it in 10.04 using a gconf key that has no scheme and I heard that a proper scheme will be available in 10.10 but I can't find anything.
2010/10/19
[ "https://askubuntu.com/questions/8226", "https://askubuntu.com", "https://askubuntu.com/users/4384/" ]
Press Alt+F2 and enter [`gconf-editor`](https://askubuntu.com/questions/17249/how-do-i-use-the-gconf-editor) Now navigate to apps-->gnome\_settings\_daemon-->plugins-->keyboard and uncheck active Restart.
I have completely same task, and i have just solve it for myself by using icons with the sizes of 1px \* 1px, this is not completely removal, but it's best solution i could found. Steps: 1) download icons (for example from [here](http://gnome-look.org/content/show.php/Language+Flags+for+Faenza+and+Elementary?content=133726)) 2)Untar (expand) the downloaded file into the folder ~/.icons/flags. If there is no "flags" sub-folder just create it. Then you need to enable the display of flags for input languages in gconf: 3) Open gconf-editor (in Ubuntu type ALT-F2 to open the "run application" dialogue and then type "gconf-editor" without the quotes and press enter). 4) Navigate the folder tree to Desktop > Gnome > Peripherals > Keyboard > Indicator 5) Activate the check-box for "showFlags" 6) Find icons for your languages in folder ~/.icons/flags, for me it was us.svg and ru.svg. Open it in image editor like Inkscape, and resize to 1\*1 px (in inkscape Shift+Ctrl+D), save it.
8,226
I need to completely remove the indicator, no flags, no abbr. nothing! I was able to do it in 10.04 using a gconf key that has no scheme and I heard that a proper scheme will be available in 10.10 but I can't find anything.
2010/10/19
[ "https://askubuntu.com/questions/8226", "https://askubuntu.com", "https://askubuntu.com/users/4384/" ]
This is a [known bug](https://bugs.launchpad.net/ubuntu/+source/gnome-settings-daemon/+bug/631989) the key I was talking about is: `gconftool-2 -s /desktop/gnome/peripherals/keyboard/general/disable_indicator -t bool true` For pre-maverick only. Thank you all for the input.
By the way, if you're removing it because of the big ugly (redundant) image in the 10.10 keyboard indicator, I've got a solution to that. I created a set of SVG flag images. If you install them and activate "show flags" in your g-conf editor then the text and ugly image both disappear. In their place you just have the one (much smaller) input language flag. I've posted the SVG's and full instructions here: <http://gnome-look.org/content/show.php/Language+Flags+for+Faenza+and+Elementary?content=133726>
8,226
I need to completely remove the indicator, no flags, no abbr. nothing! I was able to do it in 10.04 using a gconf key that has no scheme and I heard that a proper scheme will be available in 10.10 but I can't find anything.
2010/10/19
[ "https://askubuntu.com/questions/8226", "https://askubuntu.com", "https://askubuntu.com/users/4384/" ]
By the way, if you're removing it because of the big ugly (redundant) image in the 10.10 keyboard indicator, I've got a solution to that. I created a set of SVG flag images. If you install them and activate "show flags" in your g-conf editor then the text and ugly image both disappear. In their place you just have the one (much smaller) input language flag. I've posted the SVG's and full instructions here: <http://gnome-look.org/content/show.php/Language+Flags+for+Faenza+and+Elementary?content=133726>
I have completely same task, and i have just solve it for myself by using icons with the sizes of 1px \* 1px, this is not completely removal, but it's best solution i could found. Steps: 1) download icons (for example from [here](http://gnome-look.org/content/show.php/Language+Flags+for+Faenza+and+Elementary?content=133726)) 2)Untar (expand) the downloaded file into the folder ~/.icons/flags. If there is no "flags" sub-folder just create it. Then you need to enable the display of flags for input languages in gconf: 3) Open gconf-editor (in Ubuntu type ALT-F2 to open the "run application" dialogue and then type "gconf-editor" without the quotes and press enter). 4) Navigate the folder tree to Desktop > Gnome > Peripherals > Keyboard > Indicator 5) Activate the check-box for "showFlags" 6) Find icons for your languages in folder ~/.icons/flags, for me it was us.svg and ru.svg. Open it in image editor like Inkscape, and resize to 1\*1 px (in inkscape Shift+Ctrl+D), save it.
8,226
I need to completely remove the indicator, no flags, no abbr. nothing! I was able to do it in 10.04 using a gconf key that has no scheme and I heard that a proper scheme will be available in 10.10 but I can't find anything.
2010/10/19
[ "https://askubuntu.com/questions/8226", "https://askubuntu.com", "https://askubuntu.com/users/4384/" ]
This is a [known bug](https://bugs.launchpad.net/ubuntu/+source/gnome-settings-daemon/+bug/631989) the key I was talking about is: `gconftool-2 -s /desktop/gnome/peripherals/keyboard/general/disable_indicator -t bool true` For pre-maverick only. Thank you all for the input.
I have completely same task, and i have just solve it for myself by using icons with the sizes of 1px \* 1px, this is not completely removal, but it's best solution i could found. Steps: 1) download icons (for example from [here](http://gnome-look.org/content/show.php/Language+Flags+for+Faenza+and+Elementary?content=133726)) 2)Untar (expand) the downloaded file into the folder ~/.icons/flags. If there is no "flags" sub-folder just create it. Then you need to enable the display of flags for input languages in gconf: 3) Open gconf-editor (in Ubuntu type ALT-F2 to open the "run application" dialogue and then type "gconf-editor" without the quotes and press enter). 4) Navigate the folder tree to Desktop > Gnome > Peripherals > Keyboard > Indicator 5) Activate the check-box for "showFlags" 6) Find icons for your languages in folder ~/.icons/flags, for me it was us.svg and ru.svg. Open it in image editor like Inkscape, and resize to 1\*1 px (in inkscape Shift+Ctrl+D), save it.
38,917,231
For some time now I have been experiencing problems with the Excel files I work With. I am using MS Office 2016 version on Windows 10. Excel 2016 is fitted with a new functionality called usually Power Query. It's an interface for pulling the data directly from the database (SQL Server). The data from the DB are used to populate pivot tables. The pivot tables themselves take quite a lot of memory BUT it wasn't an issue in the previous versions of Excel - I have always used tones of them and never the file has been so heavy to open/close. Here is what I have tried: 1. Control Panel - Change/Uninstall - Fix 2. Close all the connections I could identify through the Excel Interface (Edit Links, Show Queries) - copied and pasted all the data sets pulled from SQL as text and removed the queries. 3. Switch off auto-calculations and auto-recovery. 4. Remove all the objects (icons, pictures, etc) from external sources. 5. Disable synchronise (One Drive for Business, Evernote, Sharepoint, etc) 6. Close all the other Office apps 7. Identify the Excel's directory within the AppData and remove all the temporary files 8. Kill excel and restart the PC (somehow opening takes a bit less time at first) 9. Copy the part of the file I want to use for a presentation and replace all the pre-calculated values with plain text - the file is still incredibly slow when saving and opening. 10. Open it on other workstations. NOTE: working with the spreadsheet once it's been opened is fine. It responds well to scrolling, filling the cells in, etc. The only thing that takes ages is opening and saving. It simply shows a blank screen ("Excel Not Responding"). Excel does not take too much memory (206MB out of 8GB) or cpu when saving. I also noticed that for some reason some of the save operations increase the size of the file (like 5MB -> 6.5MB) which may or may not be related.
2016/08/12
[ "https://Stackoverflow.com/questions/38917231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6709212/" ]
I ended up unzipping the file and checking the contents manually for anything suspicious. I found two huge files in the `xl/drawings` directory (`vmlDrawing1.vml` and `vmlDrawing2.vml` - being the exact copy of `vmlDrawing1.vml`). The files contained an XML description of 65536 **identical** objects (IDs were different). I have no idea how so many copies of the object ended up in there as I only inserted it once. I removed 65535 of them from the xml file, zipped the entire thing back and renamed to .xlsx. To my delight, excel opened it easily and saving is now instant. Note, that removing objects from within excel (find -> go to special -> objects/headers/footers -> remove) did not work, the huge files were still there, only the manual intervention helped.
If you go to Data | New Query | Query Options, and then go to Current Workbook | Data Load, is there a section about Background Data? If so, uncheck the "Allow data preview to download in the background" checkbox, save the document, and see if Excel starts up more quickly.
1,137,074
Let's say I have a text file with the content: ``` foo bar whatever something I don't know bar2 whatever ``` And, as an output from doing `grep whatever myfile.txt` (and/or `sed` and/or `awk`), I would like to have: ``` foo something I don't know ``` I've tried using option `-B 2` but that outputs both `foo` and `bar`. Cannot do `... | grep -v bar` as there are a lot of different records.
2016/10/20
[ "https://superuser.com/questions/1137074", "https://superuser.com", "https://superuser.com/users/582975/" ]
Not grep, but should work: > > awk '/grep\_string/ {print a} {a=b;b=$0}' file > > >
So here's my solution as I couldn't find any way of doing it: As I was being returned with blocks of content, say: ``` foo bar whatever -- foo2 bar2 whatever -- ``` and so on, I used grep's separator and got the very next line like so and then removed them: ``` grep -B2 whatever myfile.txt | grep -v whatever | grep -A 1 -E '\-\-' | grep -v -E '\-\-' ``` And that just outputs: ``` foo foo2 ```
275,444
Consider the following plot: ``` CDFforPoisson[u_] = x /. Solve[Exp[-x/0.01] == u, x][[1]]; DistrData = CDFforPoisson@RandomReal[{0, 1}, 10^6]; Histogram[{DistrData}, 100, "ProbabilityDensity", Frame -> True, ChartStyle -> {Opacity[.25, Red], Opacity[.25, Blue], Opacity[.25, Darker@Green]}, FrameStyle -> Directive[Black, 18], ScalingFunctions -> {"Log", "Log"}, ImageSize -> Large, PlotRange -> {{0.0001, 0.03}, All}, FrameLabel -> {"\!\(\*SubscriptBox[\(l\), \(\(displ\)\(.\)\)]\) \ [mm]", "Fraction"}, PlotLabel -> Style[Row[{"\!\(\*SubscriptBox[\(l\), \(decay\)]\) = 0.01 mm"}], 18, Black], ChartLegends -> Placed[{"Before IP"}, {0.2, 0.9}]] ``` [![enter image description here](https://i.stack.imgur.com/LyG01.png)](https://i.stack.imgur.com/LyG01.png) It has two problems: small font of legends, and a bin going out of the plot frame (on the right). Could you please tell me how to adjust the font of the legend, and how to avoid the frame problem?
2022/11/01
[ "https://mathematica.stackexchange.com/questions/275444", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/41058/" ]
1. Using `PlotRangePadding`, space can be created around the histogram. 2. Using `LegendMarkerSize` for a `SwatchLegend`, the size of the legend can be changed. You can also use `Style` as has been suggested without altering your code much. --- ``` Histogram[{DistrData}, 100, "ProbabilityDensity" , Frame -> True , ChartStyle -> { Opacity[.25, Red] , Opacity[.25, Blue] , Opacity[.25, Darker@Green] } , FrameStyle -> Directive[Black, 18] , ScalingFunctions -> {"Log", "Log"}, ImageSize -> Large , PlotRange -> {{0.0001, 0.03}, All} , PlotRangePadding -> {{2, 0.1}, {2, 0.1}} , FrameLabel -> {"\!\(\*SubscriptBox[\(l\), \(\(displ\)\(.\)\)]\) \ [mm]", "Fraction"}, PlotLabel -> Style[Row[{"\!\(\*SubscriptBox[\(l\), \(decay\)]\) = 0.01 mm"}], 18, Black], ChartLegends -> Placed[SwatchLegend[{Directive[Opacity[0.25], Red]}, {"Before IP"} , LegendMarkerSize -> 30], {0.2, 0.9}] ] ``` [![enter image description here](https://i.stack.imgur.com/9gsh0.png)](https://i.stack.imgur.com/9gsh0.png)
I'm not understanding the use of the term "CDF" in the function `CDFforPoisson` as the equation being `Solve`d is related to the probability of a zero for a Poisson distribution and it doesn't need `Solve` in that `CDFforPoisson` could be written as ``` CDFforPoisson[u_]:=-Log[u]/100 ``` If `u` has a uniform distribution, then the pdf of $-\log(u)/100$ is known and no random samples are necessary: ``` dist = TransformedDistribution[-Log[u]/100, u \[Distributed] UniformDistribution[{0, 1}]] (* ExponentialDistribution[100] *) PDF[dist, x] ``` [![PDF of exponential distribution with parameter = 100](https://i.stack.imgur.com/P14rz.png)](https://i.stack.imgur.com/P14rz.png) I'm not seeing the need to use a log scale for either horizontal or vertical axis. Also, the vertical axis represents the "probability density" which is not a "Fraction" (or a percentage) as labeled. Am I totally not understanding the question?
38,105,507
I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without "read"-ing it. i.e. ``` l = open('file','r') for line in l: pass (or code) ``` is much faster than ``` l = open('file','r') for line in l.read() / l.readlines(): pass (or code) ``` The 2nd loop will take around 1.5x as much time (I used timeit over the exact same file, and the results were 0.442 vs. 0.660), and would give the same result. So - when should I ever use the .read() or .readlines()? Since I always need to iterate over the file I'm reading, and after learning the hard way how painfully slow the .read() can be on large data - I can't seem to imagine ever using it again.
2016/06/29
[ "https://Stackoverflow.com/questions/38105507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6296435/" ]
The short answer to your question is that each of these three methods of reading bits of a file have different use cases. As noted above, `f.read()` reads the file as an individual string, and so allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution. `f.readline()` reads a single line of the file, allowing the user to parse a single line without necessarily reading the entire file. Using `f.readline()` also allows easier application of logic in reading the file than a complete line by line iteration, such as when a file changes format partway through. Using the syntax `for line in f:` allows the user to iterate over the file line by line as noted in the question. (As noted in the other answer, this documentation is a very good read): <https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects> Note: It was previously claimed that `f.readline()` could be used to skip a line during a for loop iteration. However, this doesn't work in Python 2.7, and is perhaps a questionable practice, so this claim has been removed.
Hope this helps! <https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects> > > When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory > > > Sorry for all the edits! > > For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: > > > ``` for line in f: print line, This is the first line of the file. Second line of the file ```
38,105,507
I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without "read"-ing it. i.e. ``` l = open('file','r') for line in l: pass (or code) ``` is much faster than ``` l = open('file','r') for line in l.read() / l.readlines(): pass (or code) ``` The 2nd loop will take around 1.5x as much time (I used timeit over the exact same file, and the results were 0.442 vs. 0.660), and would give the same result. So - when should I ever use the .read() or .readlines()? Since I always need to iterate over the file I'm reading, and after learning the hard way how painfully slow the .read() can be on large data - I can't seem to imagine ever using it again.
2016/06/29
[ "https://Stackoverflow.com/questions/38105507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6296435/" ]
Hope this helps! <https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects> > > When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory > > > Sorry for all the edits! > > For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: > > > ``` for line in f: print line, This is the first line of the file. Second line of the file ```
Note that `readline()` is not comparable to the case of reading all lines in for-loop since it reads line by line and there is an overhead which is pointed out by others already. I ran `timeit` on two identical snippts but one with for-loop and the other with `readlines()`. You can see my snippet below: ``` def test_read_file_1(): f = open('ml/README.md', 'r') for line in f.readlines(): print(line) def test_read_file_2(): f = open('ml/README.md', 'r') for line in f: print(line) def test_time_read_file(): from timeit import timeit duration_1 = timeit(lambda: test_read_file_1(), number=1000000) duration_2 = timeit(lambda: test_read_file_2(), number=1000000) print('duration using readlines():', duration_1) print('duration using for-loop:', duration_2) ``` And the results: ``` duration using readlines(): 78.826229238 duration using for-loop: 69.487692794 ``` The bottomline, I would say, for-loop is faster but in case of possibility of both, I'd rather `readlines()`.
38,105,507
I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without "read"-ing it. i.e. ``` l = open('file','r') for line in l: pass (or code) ``` is much faster than ``` l = open('file','r') for line in l.read() / l.readlines(): pass (or code) ``` The 2nd loop will take around 1.5x as much time (I used timeit over the exact same file, and the results were 0.442 vs. 0.660), and would give the same result. So - when should I ever use the .read() or .readlines()? Since I always need to iterate over the file I'm reading, and after learning the hard way how painfully slow the .read() can be on large data - I can't seem to imagine ever using it again.
2016/06/29
[ "https://Stackoverflow.com/questions/38105507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6296435/" ]
Hope this helps! <https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects> > > When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory > > > Sorry for all the edits! > > For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: > > > ``` for line in f: print line, This is the first line of the file. Second line of the file ```
`readlines()` is better than `for line in file` when you know that the data you are interested starts from, for example, 2nd line. You can simply write `readlines()[1:]`. Such use cases are when you have a tab/comma separated value file and the first line is a header (and you don't want to use additional module for tsv or csv files).
38,105,507
I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without "read"-ing it. i.e. ``` l = open('file','r') for line in l: pass (or code) ``` is much faster than ``` l = open('file','r') for line in l.read() / l.readlines(): pass (or code) ``` The 2nd loop will take around 1.5x as much time (I used timeit over the exact same file, and the results were 0.442 vs. 0.660), and would give the same result. So - when should I ever use the .read() or .readlines()? Since I always need to iterate over the file I'm reading, and after learning the hard way how painfully slow the .read() can be on large data - I can't seem to imagine ever using it again.
2016/06/29
[ "https://Stackoverflow.com/questions/38105507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6296435/" ]
Hope this helps! <https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects> > > When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory > > > Sorry for all the edits! > > For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code: > > > ``` for line in f: print line, This is the first line of the file. Second line of the file ```
``` #The difference between file.read(), file.readline(), file.readlines() file = open('samplefile', 'r') single_string = file.read() #Reads all the elements of the file #into a single string(\n characters might be included) line = file.readline() #Reads the current line where the cursor as a string #is positioned and moves to the next line list_strings = file.readlines()#Makes a list of strings ```
38,105,507
I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without "read"-ing it. i.e. ``` l = open('file','r') for line in l: pass (or code) ``` is much faster than ``` l = open('file','r') for line in l.read() / l.readlines(): pass (or code) ``` The 2nd loop will take around 1.5x as much time (I used timeit over the exact same file, and the results were 0.442 vs. 0.660), and would give the same result. So - when should I ever use the .read() or .readlines()? Since I always need to iterate over the file I'm reading, and after learning the hard way how painfully slow the .read() can be on large data - I can't seem to imagine ever using it again.
2016/06/29
[ "https://Stackoverflow.com/questions/38105507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6296435/" ]
The short answer to your question is that each of these three methods of reading bits of a file have different use cases. As noted above, `f.read()` reads the file as an individual string, and so allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution. `f.readline()` reads a single line of the file, allowing the user to parse a single line without necessarily reading the entire file. Using `f.readline()` also allows easier application of logic in reading the file than a complete line by line iteration, such as when a file changes format partway through. Using the syntax `for line in f:` allows the user to iterate over the file line by line as noted in the question. (As noted in the other answer, this documentation is a very good read): <https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects> Note: It was previously claimed that `f.readline()` could be used to skip a line during a for loop iteration. However, this doesn't work in Python 2.7, and is perhaps a questionable practice, so this claim has been removed.
Note that `readline()` is not comparable to the case of reading all lines in for-loop since it reads line by line and there is an overhead which is pointed out by others already. I ran `timeit` on two identical snippts but one with for-loop and the other with `readlines()`. You can see my snippet below: ``` def test_read_file_1(): f = open('ml/README.md', 'r') for line in f.readlines(): print(line) def test_read_file_2(): f = open('ml/README.md', 'r') for line in f: print(line) def test_time_read_file(): from timeit import timeit duration_1 = timeit(lambda: test_read_file_1(), number=1000000) duration_2 = timeit(lambda: test_read_file_2(), number=1000000) print('duration using readlines():', duration_1) print('duration using for-loop:', duration_2) ``` And the results: ``` duration using readlines(): 78.826229238 duration using for-loop: 69.487692794 ``` The bottomline, I would say, for-loop is faster but in case of possibility of both, I'd rather `readlines()`.
38,105,507
I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without "read"-ing it. i.e. ``` l = open('file','r') for line in l: pass (or code) ``` is much faster than ``` l = open('file','r') for line in l.read() / l.readlines(): pass (or code) ``` The 2nd loop will take around 1.5x as much time (I used timeit over the exact same file, and the results were 0.442 vs. 0.660), and would give the same result. So - when should I ever use the .read() or .readlines()? Since I always need to iterate over the file I'm reading, and after learning the hard way how painfully slow the .read() can be on large data - I can't seem to imagine ever using it again.
2016/06/29
[ "https://Stackoverflow.com/questions/38105507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6296435/" ]
The short answer to your question is that each of these three methods of reading bits of a file have different use cases. As noted above, `f.read()` reads the file as an individual string, and so allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution. `f.readline()` reads a single line of the file, allowing the user to parse a single line without necessarily reading the entire file. Using `f.readline()` also allows easier application of logic in reading the file than a complete line by line iteration, such as when a file changes format partway through. Using the syntax `for line in f:` allows the user to iterate over the file line by line as noted in the question. (As noted in the other answer, this documentation is a very good read): <https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects> Note: It was previously claimed that `f.readline()` could be used to skip a line during a for loop iteration. However, this doesn't work in Python 2.7, and is perhaps a questionable practice, so this claim has been removed.
`readlines()` is better than `for line in file` when you know that the data you are interested starts from, for example, 2nd line. You can simply write `readlines()[1:]`. Such use cases are when you have a tab/comma separated value file and the first line is a header (and you don't want to use additional module for tsv or csv files).
38,105,507
I noticed that if I iterate over a file that I opened, it is much faster to iterate over it without "read"-ing it. i.e. ``` l = open('file','r') for line in l: pass (or code) ``` is much faster than ``` l = open('file','r') for line in l.read() / l.readlines(): pass (or code) ``` The 2nd loop will take around 1.5x as much time (I used timeit over the exact same file, and the results were 0.442 vs. 0.660), and would give the same result. So - when should I ever use the .read() or .readlines()? Since I always need to iterate over the file I'm reading, and after learning the hard way how painfully slow the .read() can be on large data - I can't seem to imagine ever using it again.
2016/06/29
[ "https://Stackoverflow.com/questions/38105507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6296435/" ]
The short answer to your question is that each of these three methods of reading bits of a file have different use cases. As noted above, `f.read()` reads the file as an individual string, and so allows relatively easy file-wide manipulations, such as a file-wide regex search or substitution. `f.readline()` reads a single line of the file, allowing the user to parse a single line without necessarily reading the entire file. Using `f.readline()` also allows easier application of logic in reading the file than a complete line by line iteration, such as when a file changes format partway through. Using the syntax `for line in f:` allows the user to iterate over the file line by line as noted in the question. (As noted in the other answer, this documentation is a very good read): <https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects> Note: It was previously claimed that `f.readline()` could be used to skip a line during a for loop iteration. However, this doesn't work in Python 2.7, and is perhaps a questionable practice, so this claim has been removed.
``` #The difference between file.read(), file.readline(), file.readlines() file = open('samplefile', 'r') single_string = file.read() #Reads all the elements of the file #into a single string(\n characters might be included) line = file.readline() #Reads the current line where the cursor as a string #is positioned and moves to the next line list_strings = file.readlines()#Makes a list of strings ```
92,245
On December 22 2019, Ramanujan would have been 132 years old. In his memory here are two puzzles around 132. In the six vertices of each of these graphs place six positive integers that add up to 132, and such that two vertices are joined by an edge if, and only if, they have a common divisor greater than 1 (that is, they are not relatively prime).[![puzzle](https://i.stack.imgur.com/jGmPP.png)](https://i.stack.imgur.com/jGmPP.png)
2019/12/26
[ "https://puzzling.stackexchange.com/questions/92245", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/19026/" ]
For the first one, With A starting from the top, B and C in the second. > > A = 9, B = 15, C = 21, D = 10, E = 70, F = 7 > > > ``` A B C D E F ``` > > ![Spoiler Warning!](https://i.stack.imgur.com/o1puI.png) > > > For the second one with A, C, E in the top row > > A = 9, B = 21, C = 42, D = 35, E = 20, F = 5 > > > ``` A C E B D F ``` > > [![enter image description here](https://i.stack.imgur.com/WXsFu.png)](https://i.stack.imgur.com/WXsFu.png) > > > dot files generated and verified with [this](https://gist.github.com/sudhackar/32e61ae4add3c2ce68af14f7095377fd#file-92260-py) and the problem was solved manually based on choosing the factors that connected nodes will share.
On both figures, the numbers are shown on the vertices. [![triangles](https://i.stack.imgur.com/vDaTW.png)](https://i.stack.imgur.com/vDaTW.png)
2,634,657
I am wondering if there is a function I could use in the standard libary. Do I need another library (BTW, I am developing for unix).
2010/04/14
[ "https://Stackoverflow.com/questions/2634657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302206/" ]
See the `scanf()` function in stdio.h. It takes a format specifier like `printf()` and pointers to the variables to store the user input in
You seems quite new to C so let me add a little something to Prasoon answer, which is quite correct and complete, but maybe hard to understand for a beginner. When using scanf( const char \* format, ... ); in his exemple, Prasoon use : ``` scanf("%d",&n); ``` When using this, the "%d" indicate you're going to read an integer (See [wikipedia](http://en.wikipedia.org/wiki/Scanf) for complete format list ). The second argument (note that the ... indicates you can send any number of arguments) indicate the **address** of the variable in which you are gonna stock user entry.
2,634,657
I am wondering if there is a function I could use in the standard libary. Do I need another library (BTW, I am developing for unix).
2010/04/14
[ "https://Stackoverflow.com/questions/2634657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302206/" ]
See the `scanf()` function in stdio.h. It takes a format specifier like `printf()` and pointers to the variables to store the user input in
'Tis interesting - two answers so far both suggest `scanf()`; I wouldn't. When everything goes right, `scanf()` is OK. When things go wrong, recovery tends to be hard. I would normally use `fgets()` to read the user information for one line into a buffer (character array) first. I would then use `sscanf()` to collect information from the buffer into the target variables. The big advantage is that if the user types '12Z' when you wanted them to type two numbers, you can tell them what you saw and why it is not what you wanted much better. With `scanf()`, you can't do that.
2,634,657
I am wondering if there is a function I could use in the standard libary. Do I need another library (BTW, I am developing for unix).
2010/04/14
[ "https://Stackoverflow.com/questions/2634657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/302206/" ]
Use `scanf()` Format: `int scanf ( const char * format, ... );` `Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format tag within the format string.` Example: ``` #include <stdio.h> int main(void) { int n; printf("Enter the value to be stored in n: "); scanf("%d",&n); printf("n= %d",n); } ``` However have a look at **[this.](http://c-faq.com/stdio/scanfprobs.html)**
You seems quite new to C so let me add a little something to Prasoon answer, which is quite correct and complete, but maybe hard to understand for a beginner. When using scanf( const char \* format, ... ); in his exemple, Prasoon use : ``` scanf("%d",&n); ``` When using this, the "%d" indicate you're going to read an integer (See [wikipedia](http://en.wikipedia.org/wiki/Scanf) for complete format list ). The second argument (note that the ... indicates you can send any number of arguments) indicate the **address** of the variable in which you are gonna stock user entry.