text:
Q: .obj-Loader - output not quite right I'm working on a small 3D engine to learn more of OpenGL. I'm using Scala and lwjgl for the task.
Loading "hand-made" (all vertices, texture coordinates and indices - arrays specified by hand) models works like a charm, so I wanted to move on to loading .obj files. Turns out, it's not that easy, or, well, I'm somehow misunderstanding something.
Let's look into my parsing-method:
private def parseObj(path: String): Model =
{
    val objSource: List[String] = Source.fromFile(path).getLines.toList

    val positions: List[Vector4] = objSource.filter(_.startsWith("v ")).map(_.split(" ")).map(v => new Vector4(v(1).toFloat,v(2).toFloat,v(3).toFloat, 1.0f))
    //  val normals: List[Vector4] = objSource.filter(_.startsWith("vn ")).map(_.split(" ")).map(v => new Vector4(v(1)toFloat,v(2).toFloat, v(3).toFloat, 0.0f))
    val textureCoordinates: List[Vector2] = objSource.filter(_.startsWith("vt ")).map(_.split(" ")).map(v => new Vector2(v(1).toDouble.toFloat,v(2).toDouble.toFloat))
    val faces: List[(Int, Int, Int)] = objSource.filter(_.startsWith("f ")).map(_.split(" ")).flatten.filterNot(_ == "f").map(_.split("/")).map(a => ((a(0).toInt, a(1).toInt, a(2).toInt)))

    val indices: List[Int] = faces.map(f => f._1-1) // Wrong?

    /*
    println(positions.map{p => s"v ${p.x} ${p.y} ${p.z}"}.mkString("\n"))
    println(textureCoordinates.map {t => s"vt ${t.x} ${t.y}"}.mkString("\n"))

    println(indices)
    */
    //println(faces.length)

    val vertices: List[Vertex] =  for(face <- faces) yield(new Vertex(positions(face._1-1), textureCoordinates(face._2-1)))
    println(vertices.mkString("\n"))

    new Model(vertices.toArray, indices.toArray)
}

Now, what am I doing? An .obj-file looks like this:
v 0.000000 -1.000000 0.000000
v 0.723607 -0.447220 0.525725
v -0.276388 -0.447220 0.850649
v -0.894426 -0.447216 0.000000
v -0.276388 -0.447220 -0.850649
v 0.723607 -0.447220 -0.525725
v 0.276388 0.447220 0.850649
v -0.723607 0.447220 0.525725
v -0.723607 0.447220 -0.525725
v 0.276388 0.447220 -0.850649
v 0.894426 0.447216 0.000000
v 0.000000 1.000000 0.000000
v -0.162456 -0.850654 0.499995
v 0.425323 -0.850654 0.309011
v 0.262869 -0.525738 0.809012
v 0.850648 -0.525736 0.000000
v 0.425323 -0.850654 -0.309011
v -0.525730 -0.850652 0.000000
v -0.688189 -0.525736 0.499997
v -0.162456 -0.850654 -0.499995
v -0.688189 -0.525736 -0.499997
v 0.262869 -0.525738 -0.809012
v 0.951058 0.000000 0.309013
v 0.951058 0.000000 -0.309013
v 0.000000 0.000000 1.000000
v 0.587786 0.000000 0.809017
v -0.951058 0.000000 0.309013
v -0.587786 0.000000 0.809017
v -0.587786 0.000000 -0.809017
v -0.951058 0.000000 -0.309013
v 0.587786 0.000000 -0.809017
v 0.000000 0.000000 -1.000000
v 0.688189 0.525736 0.499997
v -0.262869 0.525738 0.809012
v -0.850648 0.525736 0.000000
v -0.262869 0.525738 -0.809012
v 0.688189 0.525736 -0.499997
v 0.162456 0.850654 0.499995
v 0.525730 0.850652 0.000000
v -0.425323 0.850654 0.309011
v -0.425323 0.850654 -0.309011
v 0.162456 0.850654 -0.499995
vt 0.534208 0.190162
vt 0.439232 0.259166
vt 0.570486 0.301814
vt 0.995860 0.190574
vt 0.999792 0.292763
vt 0.903537 0.265179
vt 0.651606 0.190162
vt 0.570486 0.078511
vt 0.439232 0.121159
vt 0.903535 0.129002
vt 0.092743 0.471488
vt 0.212444 0.449586
vt 0.158053 0.569043
vt 0.737562 0.458199
vt 0.632422 0.499661
vt 0.728679 0.579260
vt 0.408849 0.471488
vt 0.316315 0.457312
vt 0.342992 0.573818
vt 0.632005 0.463365
vt 0.528550 0.449586
vt 0.605329 0.564268
vt 0.999792 0.072423
vt 0.026885 0.573818
vt 0.847656 0.509327
vt 0.474160 0.569043
vt 0.793444 0.309553
vt 0.688302 0.255514
vt 0.784558 0.198935
vt 0.251881 0.000208
vt 0.343838 0.078511
vt 0.226439 0.078511
vt 0.028577 0.072765
vt 0.131462 0.009506
vt 0.095186 0.121159
vt 0.939981 0.570899
vt 0.847658 0.645504
vt 0.943912 0.673088
vt 0.539471 0.666598
vt 0.419770 0.688500
vt 0.517323 0.757552
vt 0.793441 0.077875
vt 0.688301 0.119336
vt 0.747790 0.000208
vt 0.307560 0.190162
vt 0.226439 0.301814
vt 0.190162 0.190162
vt 0.343838 0.301814
vt 0.251881 0.380116
vt 0.095186 0.259166
vt 0.131462 0.370818
vt 0.028577 0.307559
vt 0.000208 0.190162
vt 0.737565 0.689877
vt 0.824936 0.743021
vt 0.103663 0.688500
vt 0.223364 0.666598
vt 0.201217 0.757552
vt 0.880811 0.006181
vt 0.632005 0.680774
vt 0.316315 0.674721
vt 0.000208 0.674721
vt 0.289222 0.564268
vt 0.315898 0.680774
vt 0.943912 0.452748
vt 0.824932 0.386505
vt 0.632423 0.635839
vt 0.000208 0.457312
vt 0.315898 0.463365
vt 0.475509 0.009506
vt 0.372624 0.072765
vt 0.430997 0.380533
vt 0.687884 0.078511
vt 0.595927 0.000208
vt 0.691911 0.380533
vt 0.687884 0.301814
vt 0.595927 0.380116
vt 0.880815 0.362696
vt 0.344255 0.190162
vt 0.114890 0.380533
vt 0.475509 0.370818
vt 0.372624 0.307559
vn 0.102400 -0.943500 0.315100
vn 0.700200 -0.661700 0.268000
vn -0.268000 -0.943500 0.194700
vn -0.268000 -0.943500 -0.194700
vn 0.102400 -0.943500 -0.315100
vn 0.905000 -0.330400 0.268000
vn 0.024700 -0.330400 0.943500
vn -0.889700 -0.330400 0.315100
vn -0.574600 -0.330400 -0.748800
vn 0.534600 -0.330400 -0.777900
vn 0.802600 -0.125600 0.583100
vn -0.306600 -0.125600 0.943500
vn -0.992100 -0.125600 0.000000
vn -0.306600 -0.125600 -0.943500
vn 0.802600 -0.125600 -0.583100
vn 0.408900 0.661700 0.628400
vn -0.471300 0.661700 0.583100
vn -0.700200 0.661700 -0.268000
vn 0.038500 0.661700 -0.748800
vn 0.724000 0.661700 -0.194700
vn 0.268000 0.943500 -0.194700
vn 0.491100 0.794700 -0.356800
vn 0.408900 0.661700 -0.628400
vn -0.102400 0.943500 -0.315100
vn -0.187600 0.794700 -0.577300
vn -0.471300 0.661700 -0.583100
vn -0.331300 0.943500 0.000000
vn -0.607100 0.794700 0.000000
vn -0.700200 0.661700 0.268000
vn -0.102400 0.943500 0.315100
vn -0.187600 0.794700 0.577300
vn 0.038500 0.661700 0.748800
vn 0.268000 0.943500 0.194700
vn 0.491100 0.794700 0.356800
vn 0.724000 0.661700 0.194700
vn 0.889700 0.330400 -0.315100
vn 0.794700 0.187600 -0.577300
vn 0.574600 0.330400 -0.748800
vn -0.024700 0.330400 -0.943500
vn -0.303500 0.187600 -0.934200
vn -0.534600 0.330400 -0.777900
vn -0.905000 0.330400 -0.268000
vn -0.982200 0.187600 0.000000
vn -0.905000 0.330400 0.268000
vn -0.534600 0.330400 0.777900
vn -0.303500 0.187600 0.934200
vn -0.024700 0.330400 0.943500
vn 0.574600 0.330400 0.748800
vn 0.794700 0.187600 0.577300
vn 0.889700 0.330400 0.315100
vn 0.306600 0.125600 -0.943500
vn 0.303500 -0.187600 -0.934200
vn 0.024700 -0.330400 -0.943500
vn -0.802600 0.125600 -0.583100
vn -0.794700 -0.187600 -0.577300
vn -0.889700 -0.330400 -0.315100
vn -0.802600 0.125600 0.583100
vn -0.794700 -0.187600 0.577300
vn -0.574600 -0.330400 0.748800
vn 0.306600 0.125600 0.943500
vn 0.303500 -0.187600 0.934200
vn 0.534600 -0.330400 0.777900
vn 0.992100 0.125600 0.000000
vn 0.982200 -0.187600 0.000000
vn 0.905000 -0.330400 -0.268000
vn 0.471300 -0.661700 -0.583100
vn 0.187600 -0.794700 -0.577300
vn -0.038500 -0.661700 -0.748800
vn -0.408900 -0.661700 -0.628400
vn -0.491100 -0.794700 -0.356800
vn -0.724000 -0.661700 -0.194700
vn -0.724000 -0.661700 0.194700
vn -0.491100 -0.794700 0.356800
vn -0.408900 -0.661700 0.628400
vn 0.700200 -0.661700 -0.268000
vn 0.607100 -0.794700 0.000000
vn 0.331300 -0.943500 0.000000
vn -0.038500 -0.661700 0.748800
vn 0.187600 -0.794700 0.577300
vn 0.471300 -0.661700 0.583100
usemtl Material.001
s off
f 1/1/1 14/2/1 13/3/1
f 2/4/2 14/5/2 16/6/2
f 1/1/3 13/3/3 18/7/3
f 1/1/4 18/7/4 20/8/4
f 1/1/5 20/8/5 17/9/5
f 2/4/6 16/6/6 23/10/6
f 3/11/7 15/12/7 25/13/7
f 4/14/8 19/15/8 27/16/8
f 5/17/9 21/18/9 29/19/9
f 6/20/10 22/21/10 31/22/10
f 2/4/11 23/10/11 26/23/11
f 3/11/12 25/13/12 28/24/12
f 4/14/13 27/16/13 30/25/13
f 5/17/14 29/19/14 32/26/14
f 6/27/15 31/28/15 24/29/15
f 7/30/16 33/31/16 38/32/16
f 8/33/17 34/34/17 40/35/17
f 9/36/18 35/37/18 41/38/18
f 10/39/19 36/40/19 42/41/19
f 11/42/20 37/43/20 39/44/20
f 39/45/21 42/46/21 12/47/21
f 39/45/22 37/48/22 42/46/22
f 37/48/23 10/49/23 42/46/23
f 42/46/24 41/50/24 12/47/24
f 42/46/25 36/51/25 41/50/25
f 36/51/26 9/52/26 41/50/26
f 41/50/27 40/35/27 12/47/27
f 41/50/28 35/53/28 40/35/28
f 35/37/29 8/54/29 40/55/29
f 40/35/30 38/32/30 12/47/30
f 40/35/31 34/34/31 38/32/31
f 34/56/32 7/57/32 38/58/32
f 38/32/33 39/45/33 12/47/33
f 38/32/34 33/31/34 39/45/34
f 33/59/35 11/42/35 39/44/35
f 24/29/36 37/43/36 11/42/36
f 24/29/37 31/28/37 37/43/37
f 31/22/38 10/39/38 37/60/38
f 32/26/39 36/40/39 10/39/39
f 32/26/40 29/19/40 36/40/40
f 29/19/41 9/61/41 36/40/41
f 30/25/42 35/37/42 9/36/42
f 30/25/43 27/16/43 35/37/43
f 27/16/44 8/54/44 35/37/44
f 28/24/45 34/56/45 8/62/45
f 28/24/46 25/13/46 34/56/46
f 25/13/47 7/57/47 34/56/47
f 26/63/48 33/64/48 7/57/48
f 26/23/49 23/10/49 33/59/49
f 23/10/50 11/42/50 33/59/50
f 31/22/51 32/26/51 10/39/51
f 31/22/52 22/21/52 32/26/52
f 22/21/53 5/17/53 32/26/53
f 29/65/54 30/25/54 9/36/54
f 29/65/55 21/66/55 30/25/55
f 21/66/56 4/14/56 30/25/56
f 27/16/57 28/67/57 8/54/57
f 27/16/58 19/15/58 28/67/58
f 19/68/59 3/11/59 28/24/59
f 25/13/60 26/63/60 7/57/60
f 25/13/61 15/12/61 26/63/61
f 15/12/62 2/69/62 26/63/62
f 23/10/63 24/29/63 11/42/63
f 23/10/64 16/6/64 24/29/64
f 16/6/65 6/27/65 24/29/65
f 17/9/66 22/70/66 6/71/66
f 17/9/67 20/8/67 22/70/67
f 20/72/68 5/17/68 22/21/68
f 20/8/69 21/73/69 5/74/69
f 20/8/70 18/7/70 21/73/70
f 18/75/71 4/14/71 21/66/71
f 18/75/72 19/15/72 4/14/72
f 18/7/73 13/3/73 19/76/73
f 13/3/74 3/77/74 19/76/74
f 16/6/75 17/78/75 6/27/75
f 16/79/76 14/2/76 17/9/76
f 14/2/77 1/1/77 17/9/77
f 13/80/78 15/12/78 3/11/78
f 13/3/79 14/2/79 15/81/79
f 14/2/80 2/82/80 15/81/80
v 0.000000 -1.000000 0.000000
v 0.723607 -0.447220 0.525725
v -0.276388 -0.447220 0.850649
v -0.894426 -0.447216 0.000000
v -0.276388 -0.447220 -0.850649
v 0.723607 -0.447220 -0.525725
v 0.276388 0.447220 0.850649
v -0.723607 0.447220 0.525725
v -0.723607 0.447220 -0.525725
v 0.276388 0.447220 -0.850649
v 0.894426 0.447216 0.000000
v 0.000000 1.000000 0.000000
v -0.162456 -0.850654 0.499995
v 0.425323 -0.850654 0.309011
v 0.262869 -0.525738 0.809012
v 0.850648 -0.525736 0.000000
v 0.425323 -0.850654 -0.309011
v -0.525730 -0.850652 0.000000
v -0.688189 -0.525736 0.499997
v -0.162456 -0.850654 -0.499995
v -0.688189 -0.525736 -0.499997
v 0.262869 -0.525738 -0.809012
v 0.951058 0.000000 0.309013
v 0.951058 0.000000 -0.309013
v 0.000000 0.000000 1.000000
v 0.587786 0.000000 0.809017
v -0.951058 0.000000 0.309013
v -0.587786 0.000000 0.809017
v -0.587786 0.000000 -0.809017
v -0.951058 0.000000 -0.309013
v 0.587786 0.000000 -0.809017
v 0.000000 0.000000 -1.000000
v 0.688189 0.525736 0.499997
v -0.262869 0.525738 0.809012
v -0.850648 0.525736 0.000000
v -0.262869 0.525738 -0.809012
v 0.688189 0.525736 -0.499997
v 0.162456 0.850654 0.499995
v 0.525730 0.850652 0.000000
v -0.425323 0.850654 0.309011
v -0.425323 0.850654 -0.309011
v 0.162456 0.850654 -0.499995
vt 0.534208 0.190162
vt 0.439232 0.259166
vt 0.570486 0.301814
vt 0.995860 0.190574
vt 0.999792 0.292763
vt 0.903537 0.265179
vt 0.651606 0.190162
vt 0.570486 0.078511
vt 0.439232 0.121159
vt 0.903535 0.129002
vt 0.092743 0.471488
vt 0.212444 0.449586
vt 0.158053 0.569043
vt 0.737562 0.458199
vt 0.632422 0.499661
vt 0.728679 0.579260
vt 0.408849 0.471488
vt 0.316315 0.457312
vt 0.342992 0.573818
vt 0.632005 0.463365
vt 0.528550 0.449586
vt 0.605329 0.564268
vt 0.999792 0.072423
vt 0.026885 0.573818
vt 0.847656 0.509327
vt 0.474160 0.569043
vt 0.793444 0.309553
vt 0.688302 0.255514
vt 0.784558 0.198935
vt 0.251881 0.000208
vt 0.343838 0.078511
vt 0.226439 0.078511
vt 0.028577 0.072765
vt 0.131462 0.009506
vt 0.095186 0.121159
vt 0.939981 0.570899
vt 0.847658 0.645504
vt 0.943912 0.673088
vt 0.539471 0.666598
vt 0.419770 0.688500
vt 0.517323 0.757552
vt 0.793441 0.077875
vt 0.688301 0.119336
vt 0.747790 0.000208
vt 0.307560 0.190162
vt 0.226439 0.301814
vt 0.190162 0.190162
vt 0.343838 0.301814
vt 0.251881 0.380116
vt 0.095186 0.259166
vt 0.131462 0.370818
vt 0.028577 0.307559
vt 0.000208 0.190162
vt 0.737565 0.689877
vt 0.824936 0.743021
vt 0.103663 0.688500
vt 0.223364 0.666598
vt 0.201217 0.757552
vt 0.880811 0.006181
vt 0.632005 0.680774
vt 0.316315 0.674721
vt 0.000208 0.674721
vt 0.289222 0.564268
vt 0.315898 0.680774
vt 0.943912 0.452748
vt 0.824932 0.386505
vt 0.632423 0.635839
vt 0.000208 0.457312
vt 0.315898 0.463365
vt 0.475509 0.009506
vt 0.372624 0.072765
vt 0.430997 0.380533
vt 0.687884 0.078511
vt 0.595927 0.000208
vt 0.691911 0.380533
vt 0.687884 0.301814
vt 0.595927 0.380116
vt 0.880815 0.362696
vt 0.344255 0.190162
vt 0.114890 0.380533
vt 0.475509 0.370818
vt 0.372624 0.307559
vn 0.102400 -0.943500 0.315100
vn 0.700200 -0.661700 0.268000
vn -0.268000 -0.943500 0.194700
vn -0.268000 -0.943500 -0.194700
vn 0.102400 -0.943500 -0.315100
vn 0.905000 -0.330400 0.268000
vn 0.024700 -0.330400 0.943500
vn -0.889700 -0.330400 0.315100
vn -0.574600 -0.330400 -0.748800
vn 0.534600 -0.330400 -0.777900
vn 0.802600 -0.125600 0.583100
vn -0.306600 -0.125600 0.943500
vn -0.992100 -0.125600 0.000000
vn -0.306600 -0.125600 -0.943500
vn 0.802600 -0.125600 -0.583100
vn 0.408900 0.661700 0.628400
vn -0.471300 0.661700 0.583100
vn -0.700200 0.661700 -0.268000
vn 0.038500 0.661700 -0.748800
vn 0.724000 0.661700 -0.194700
vn 0.268000 0.943500 -0.194700
vn 0.491100 0.794700 -0.356800
vn 0.408900 0.661700 -0.628400
vn -0.102400 0.943500 -0.315100
vn -0.187600 0.794700 -0.577300
vn -0.471300 0.661700 -0.583100
vn -0.331300 0.943500 0.000000
vn -0.607100 0.794700 0.000000
vn -0.700200 0.661700 0.268000
vn -0.102400 0.943500 0.315100
vn -0.187600 0.794700 0.577300
vn 0.038500 0.661700 0.748800
vn 0.268000 0.943500 0.194700
vn 0.491100 0.794700 0.356800
vn 0.724000 0.661700 0.194700
vn 0.889700 0.330400 -0.315100
vn 0.794700 0.187600 -0.577300
vn 0.574600 0.330400 -0.748800
vn -0.024700 0.330400 -0.943500
vn -0.303500 0.187600 -0.934200
vn -0.534600 0.330400 -0.777900
vn -0.905000 0.330400 -0.268000
vn -0.982200 0.187600 0.000000
vn -0.905000 0.330400 0.268000
vn -0.534600 0.330400 0.777900
vn -0.303500 0.187600 0.934200
vn -0.024700 0.330400 0.943500
vn 0.574600 0.330400 0.748800
vn 0.794700 0.187600 0.577300
vn 0.889700 0.330400 0.315100
vn 0.306600 0.125600 -0.943500
vn 0.303500 -0.187600 -0.934200
vn 0.024700 -0.330400 -0.943500
vn -0.802600 0.125600 -0.583100
vn -0.794700 -0.187600 -0.577300
vn -0.889700 -0.330400 -0.315100
vn -0.802600 0.125600 0.583100
vn -0.794700 -0.187600 0.577300
vn -0.574600 -0.330400 0.748800
vn 0.306600 0.125600 0.943500
vn 0.303500 -0.187600 0.934200
vn 0.534600 -0.330400 0.777900
vn 0.992100 0.125600 0.000000
vn 0.982200 -0.187600 0.000000
vn 0.905000 -0.330400 -0.268000
vn 0.471300 -0.661700 -0.583100
vn 0.187600 -0.794700 -0.577300
vn -0.038500 -0.661700 -0.748800
vn -0.408900 -0.661700 -0.628400
vn -0.491100 -0.794700 -0.356800
vn -0.724000 -0.661700 -0.194700
vn -0.724000 -0.661700 0.194700
vn -0.491100 -0.794700 0.356800
vn -0.408900 -0.661700 0.628400
vn 0.700200 -0.661700 -0.268000
vn 0.607100 -0.794700 0.000000
vn 0.331300 -0.943500 0.000000
vn -0.038500 -0.661700 0.748800
vn 0.187600 -0.794700 0.577300
vn 0.471300 -0.661700 0.583100
usemtl Material.001
s off
f 1/1/1 14/2/1 13/3/1
f 2/4/2 14/5/2 16/6/2
f 1/1/3 13/3/3 18/7/3
f 1/1/4 18/7/4 20/8/4
f 1/1/5 20/8/5 17/9/5
f 2/4/6 16/6/6 23/10/6
f 3/11/7 15/12/7 25/13/7
f 4/14/8 19/15/8 27/16/8
f 5/17/9 21/18/9 29/19/9
f 6/20/10 22/21/10 31/22/10
f 2/4/11 23/10/11 26/23/11
f 3/11/12 25/13/12 28/24/12
f 4/14/13 27/16/13 30/25/13
f 5/17/14 29/19/14 32/26/14
f 6/27/15 31/28/15 24/29/15
f 7/30/16 33/31/16 38/32/16
f 8/33/17 34/34/17 40/35/17
f 9/36/18 35/37/18 41/38/18
f 10/39/19 36/40/19 42/41/19
f 11/42/20 37/43/20 39/44/20
f 39/45/21 42/46/21 12/47/21
f 39/45/22 37/48/22 42/46/22
f 37/48/23 10/49/23 42/46/23
f 42/46/24 41/50/24 12/47/24
f 42/46/25 36/51/25 41/50/25
f 36/51/26 9/52/26 41/50/26
f 41/50/27 40/35/27 12/47/27
f 41/50/28 35/53/28 40/35/28
f 35/37/29 8/54/29 40/55/29
f 40/35/30 38/32/30 12/47/30
f 40/35/31 34/34/31 38/32/31
f 34/56/32 7/57/32 38/58/32
f 38/32/33 39/45/33 12/47/33
f 38/32/34 33/31/34 39/45/34
f 33/59/35 11/42/35 39/44/35
f 24/29/36 37/43/36 11/42/36
f 24/29/37 31/28/37 37/43/37
f 31/22/38 10/39/38 37/60/38
f 32/26/39 36/40/39 10/39/39
f 32/26/40 29/19/40 36/40/40
f 29/19/41 9/61/41 36/40/41
f 30/25/42 35/37/42 9/36/42
f 30/25/43 27/16/43 35/37/43
f 27/16/44 8/54/44 35/37/44
f 28/24/45 34/56/45 8/62/45
f 28/24/46 25/13/46 34/56/46
f 25/13/47 7/57/47 34/56/47
f 26/63/48 33/64/48 7/57/48
f 26/23/49 23/10/49 33/59/49
f 23/10/50 11/42/50 33/59/50
f 31/22/51 32/26/51 10/39/51
f 31/22/52 22/21/52 32/26/52
f 22/21/53 5/17/53 32/26/53
f 29/65/54 30/25/54 9/36/54
f 29/65/55 21/66/55 30/25/55
f 21/66/56 4/14/56 30/25/56
f 27/16/57 28/67/57 8/54/57
f 27/16/58 19/15/58 28/67/58
f 19/68/59 3/11/59 28/24/59
f 25/13/60 26/63/60 7/57/60
f 25/13/61 15/12/61 26/63/61
f 15/12/62 2/69/62 26/63/62
f 23/10/63 24/29/63 11/42/63
f 23/10/64 16/6/64 24/29/64
f 16/6/65 6/27/65 24/29/65
f 17/9/66 22/70/66 6/71/66
f 17/9/67 20/8/67 22/70/67
f 20/72/68 5/17/68 22/21/68
f 20/8/69 21/73/69 5/74/69
f 20/8/70 18/7/70 21/73/70
f 18/75/71 4/14/71 21/66/71
f 18/75/72 19/15/72 4/14/72
f 18/7/73 13/3/73 19/76/73
f 13/3/74 3/77/74 19/76/74
f 16/6/75 17/78/75 6/27/75
f 16/79/76 14/2/76 17/9/76
f 14/2/77 1/1/77 17/9/77
f 13/80/78 15/12/78 3/11/78
f 13/3/79 14/2/79 15/81/79
f 14/2/80 2/82/80 15/81/80

each line starting with v defines a vertex' position in 3D-space.
So I'm reading all these in and create new Vector4 to get homogeneous coordinates.
I ignore vn for now, these would be the normals.
For vt - specifying texture coordinates - I do the same as for the positions.
Now f is prepending the really interesting lines. These are faces, triangles defined as triples of (vertexposition/texturecoordinates/normals). Each of these define which index of positions and texturecoordinates maps together.
So, for example in f 1/1/1 14/2/1 13/3/1 1/1/1 would mean that positions(1) has the texture coordinates(1) (and the last 1 in the first triple would stand for the normal in normals(1))
14/2/1 would mean that positions(14) and texturecoordinates(2) map together.
The whole line would connect these 3 vertices, like (1,14,13) would build up a triangle.
Am I understanding this correctly until here?
val faces: List[(Int, Int, Int)] = objSource.filter(_.startsWith("f ")).map(_.split(" ")).flatten.filterNot(_ == "f").map(_.split("/")).map(a => ((a(0).toInt, a(1).toInt, a(2).toInt)))
Would give me a List of these triples. For each of the entries I would then create a Vertex:
val vertices: List[Vertex] =  for(face <- faces) yield(new Vertex(positions(face._1-1), textureCoordinates(face._2-1)))
Vertex is defined like so:
case class Vertex(position: Vector4,/* normal: Vector4,*/ textureCoordinates: Vector2)

I need to do "-1" on each face to avoid off-by-one and IndexOutOfBoundsExceptions, as the index of a List starts with 0 while the indices are starting with 1.
The last thing are the indices: In OpenGL you may use an ELEMENT_ARRAY_BUFFER to specify which vertices are connected and to save (possibly a lot) of data.
As I said earlier, each face f 1/1/1 14/2/1 13/3/1 is built up like this v1/t1/n1 v2/t2/n2 v3/t3/n3 (for each line) so I only need to extract v1,v2,v3, pack it into one long List and let OpenGL do the rest.
v1/v2/v3/v4/v5/v6/.../vn would then be my indices
Am I right or is something wrong until here?
Last but not least I would create a new model:
class Model(vertices: Array[Vertex], indices: Array[Int]/*, textures: Array[Texture]*/)
{
  // Create VAO, VBO and a buffer for the indices
  val vao: Int = glGenVertexArrays
  val vbo: Int = glGenBuffers
  val ibo: Int = glGenBuffers

  setup

  private def setup(): Unit =
  {
    val interleavedBuffer: FloatBuffer = prepareVertexBuffer(vertices)
    val indicesBuffer: IntBuffer = prepareIntBuffer(indices)

    // One VAO to bind them all!
    glBindVertexArray(vao)
      glBindBuffer(GL_ARRAY_BUFFER, vbo)
      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo)

      // Fill buffers with data
      glBufferData(GL_ARRAY_BUFFER, interleavedBuffer, GL_STATIC_DRAW)
      glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesBuffer, GL_STATIC_DRAW)

      // Set vertex attribute pointers
      glVertexAttribPointer(0, 4, GL_FLOAT, false, 4*6, 0) // 0 = Position = Vector4(x,y,z,w)
      glVertexAttribPointer(1, 2, GL_FLOAT, false, 4*6, 4*4) // 1 = Texture Coordinates = Vector2(x,y) -> 2 (coordinates) * 4 (byte-size of float) => stride = 4 (position) + 2 (texture coordinates) = 6 * 4 (byte-size of float); offset = 4 (position) * 4 (byte-size of float)

      glBindBuffer(GL_ARRAY_BUFFER, 0)
    glBindVertexArray(0)
  }

  private def prepareIntBuffer(data: Array[Int]): IntBuffer =
  {
    val buffer: IntBuffer = BufferUtils.createIntBuffer(data.length)
    buffer.put(data)
    buffer.flip // Make the buffer readable

    buffer
  }

  private def prepareVertexBuffer(vertices: Array[Vertex]): FloatBuffer =
  {
    val positions: Array[Float] = vertices.map(v => v.position).map(_.toArray).flatten
    val textureCoordinates: Array[Float] = vertices.map(v => v.textureCoordinates).map(_.toArray).flatten

    // TODO remove hardcoded sizes for grouping
    val zipped: Array[Float] = (positions.grouped(4) zip textureCoordinates.grouped(2)).toArray.flatMap {case (x,y) => x ++ y}

    val buffer: FloatBuffer = BufferUtils.createFloatBuffer(zipped.size)
    buffer.put(zipped)
    buffer.flip

    buffer
  }

The problem is, the output looks like this:

While actually it should be an Ico-Sphere from Blender.
So, something is really off with my implementation or understanding of the .obj-file-format.
I assume it has to do with the indices, but no idea. I've debugged a lot, manually compared the different Lists with the actual .obj-file but to no avail. Everything looks okay, so I assume it's really my understanding.
edit: I'm not yet sure what exactly I am misunderstanding but, instead of going through the faces to create a List of Vertices (my own class) I gave the model all the positions and texture coordinates and voilà, the meshes appearance looks right (apart from wrong texturing).
So what I did:
class Model(positions: Array[Vector3], texcoords: Array[Vector2], indices: Array[Int])

private def prepareVertexBuffer(positions: Array[Vector3], texcoords: Array[Vector2]): FloatBuffer =
  {
    val pos: Array[Float] = positions.map(_.toArray).flatten
    val textureCoordinates: Array[Float] = texcoords.map(_.toArray).flatten

    // TODO remove hardcoded sizes for grouping
    val zipped: Array[Float] = (pos.grouped(3) zip textureCoordinates.grouped(2)).toArray.flatMap {case (x,y) => x ++ y}

    println(zipped.toList.grouped(5).mkString("\n"))

    val buffer: FloatBuffer = BufferUtils.createFloatBuffer(zipped.size)
    buffer.put(zipped)
    buffer.flip

    buffer
  }

(Note: I've also switched back to Vector3 instead of Vector4 for now. Thought there might be a problem with it)
val indices: List[Int] = faces.map(f => f._1-1) // Wrong?
new Model(vertices.toArray, indices.toArray)

The rest is the same. So I guess my texturing problem results from this.
I now have only 42 vertices instead of 240 (coming from the faces), so I lose a lot of combinations.
The current result:

edit
The problem boils down to the difference between .obj and opengl. OpenGL may only use one index-buffer while in .obj there is one for each attribute.
So I need to manually merge these in an appropriate way. I've found C++ functions for that and although I know C++ quite a bit, I'm not sure why it's not working on my end with Scala.
I simply do not find any duplicates...

A: What you're doing is v1-t1 v2-t2, v3-t3 etc. If you look at your original .obj file, thats probably not whats happening. It could be v1-t1, v2-t1, v3-t1. Who knows. So what you need to do is find the texcoord matching to the vertex. This will get you close to what you want, but not quite there, because in .OBJ files 1 vertex can have multiple texcoords, and right now you can't handle that yet. I have answered a similar question here:
OpenGL - texture are mapped incorrectly using glDrawElements
(Note that you don't HAVE to get rid of the index buffer, but its easier)


text:
Q: Changing background image on button click android app development I am trying to change the background image of an activity
on button click, but not being able to do so. Can you guys tell me how can I can do that?
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try
        {
            Activity activity = Selection.this;
            //Drawable db = Drawable..createFromPath(R.drawable.love1);

            // The below line gives error because setbackgroundImage
            // is supposed to take a drawable object as an argument.
            // Now what to do?
            activity.findViewById(android.R.id.content)
            .setBackground(Drawable.createFromPath("res/love1.jpg"));

            // What to do to correct the above line?

            mySong = MediaPlayer.create(Selection.this, R.raw.song1);
            mySong.start();
        }
        catch(Exception ee){
            TextView tv = (TextView) findViewById(R.id.textView1);
            tv.setText(ee.getMessage());
        }
    }
});

I tried with Color.RED using setBackgroundColor but that too is not working.
PS: I have not changed anything in the xml file for accomplishing this.

A: I think the easiest way is to use layout in your xml file for your activity.. for example:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/linearLayoutID"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/background_img1" >

and then change it from your Activity when you want e.g. after the button click:
 LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linearLayoutID);
 mLinearLayout.setBackgroundResource(R.drawable.background_img2);

A:
Change setBackground(Drawable) to setBackgroundResource(R.drawable.filename)

A: LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.LayoutID);
 mLinearLayout.setBackgroundResource(R.drawable.image_name);

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I protect my routes when signing up a new user in Vapor 4? I would like to know if I am using the best practices here as I send the user credentials in a Content-Type: application/json way, without protecting the password. I would like to know if I can protect my route with a middleware and make the user signing up in the safest way possible on my Vapor 4 application.
Can I use Authorization: Basic to sign up a user on my Vapor app ?
Is it the normal flow that I am doing here?
This is the way I sign up a user. There is my table with the UserModel, and this is the extension to handle the sign up flow.
extension UserModel {
  //  MARK: UserSignUp
  /// Values needed for a user to sign up.
  ///
  struct SignUp {

    let email: String
    let password: String
  }
}

extension UserModel.SignUp: Codable {}

extension UserModel.SignUp: Validatable {
  /// Setting up sign up rules for email and password to validate
  /// new user.
  ///
  static func validations(_ validations: inout Validations) {
    validations.add("email", as: String.self, is: .email)
    validations.add("password", as: String.self, is: .count(1...))
  }
}

The route where I would like to protect it to safely pass user credentials.
struct UsersAuthController: RouteCollection {
  func boot(routes: RoutesBuilder) throws {

    let unprotectedRoute = routes.grouped("users")
    unprotectedRoute.post("signup", use: signUp)
  }
}

And here is the way I sign up the user in the Vapor app. Is this the safest way?
extension UsersAuthController {
  func signUp(_ req: Request) throws -> EventLoopFuture<UserModel.NewSession> {

    try UserModel.SignUp.validate(content: req)
    let signUpUser = try req.content.decode(UserModel.SignUp.self)
    let user = try create(from: signUpUser)
    var token: UserTokenModel!

    return checkIfUserExists(signUpUser.email, req: req)
      .flatMapThrowing { exists -> UserModel in
        guard !exists else {
          throw Abort(.conflict)
        }
        return user }
      .flatMap { $0.save(on: req.db) }
      .flatMapThrowing { _ -> UserTokenModel in
        guard let newToken = try? user.createUserToken(source: .signUp) else {
          throw Abort(.internalServerError)
        }
        token = newToken
        return token }
      .flatMap { $0.save(on: req.db) }
      .flatMapThrowing {
        UserModel.NewSession(token: token.value,
                             user: try user.asPublic())  // Just returning a token and use id.
      }
  }

  func create(from user: UserModel.SignUp) throws -> UserModel {
    UserModel(email: user.email,
              password: try Bcrypt.hash(user.password))
  }
}

A: What are you trying to protect from? There's no real difference between sending the username and password in the JSON body or as a HTTP Basic credentials header. Otherwise things look OK, though I'd nest some of the futures to avoid having var token: UserTokenModel!


text:
Q: Parsing Facebook JSON Game Request Data I am currently using facebook and I have a callback method that returns a JSON result as a string.
The result has the following format:
{
"request": "420211088059698",
"to": [
    "100002669403922",
    "100000048490273"
]
}

How would I go about parsing the "to" into a list of some sort? This way I can use this list to verify that the user actually did indeed send a request to a friend to play the game.
Thanks guys

A: You need to convert it to a class array. That can be done with Unity's built in JsonUtility API.
JsonUtility.ToJson to convert a class to Json.
JsonUtility.FromJson to convert Json back to class.
Visit here Json array example.
EDIT:
You asked for an example:
class FacebookInfo
{
    public string request;
    public string[] to;
}

void Start()
{
    FacebookInfo fbInfo = new FacebookInfo();
    string fbJson = "{\"request\": \"420211088059698\",\"to\": [\"100002669403922\",\"100000048490273\"]}";
    fbInfo = JsonUtility.FromJson<FacebookInfo>(fbJson);

    //Show request
    Debug.Log("Request: " + fbInfo.request);

    //Show to arrays
    for (int i = 0; i < fbInfo.to.Length; i++)
    {
        Debug.Log("To : " + fbInfo.to[i]);
    }
}

Tested with Unity 5.4.0.13B and it looks like Unity now support Json array without writing extra code. Just make sure you have this version I mentioned.

A: You can use JSON.Net for deserializing to a class of below structure:
Class Test{
public string request {get;set;}
public List<string> to {get;set;}
}

then just call deserialize method on the JSON string to get the object.
Test obj = JsonConvert.DeserializeObject<Test>(jsonstring);

A: just use SimpleJson http://wiki.unity3d.com/index.php/SimpleJSON , no extra work needed , look at the example , all you need to do is use JSON.Parse and  you an array  and can use it like data["request"] to get the values, hope this helps.


text:
Q: Is the following proof correct for $n(n+1)(n+5) = 3X$ The objective is to prove that $n(n+1)(n+5)$ is a multiple of 3.
I took the following simplistic route $$n(n+1)(n+5) = 3X$$
$$n(n+1)(n+5)\frac{n+2}{n}\frac{n+6}{n+5} = 3X*\frac{n+2}{n}\frac{n+6}{n+5}$$
Now, since $(n+1)(n+2)(n+6) = 3X*Y$, n+1 should be divisible by 3 as long as n is divisible by 3 (Proof by induction).
Obviously i don't feel that is the right answer, it feels like cheating. I can't see how this method is illegal however.

A: Hint: $n(n+1)(n+5) = n(n+1)(n+2 + 3)$
$= n(n+1)(n+2)+3n(n+1)$
So just prove the product of 3 consecutive numbers is a multiple of 3.
Now as Anurag mentioned, $n$ can be of the form $3k$ or $3k+1$ or $3k+2$. In all cases, show that $n(n+1)(n+2)$ is divisible by 3.

A: hint
For any integer $n$ there are three possibilities: either $n=3k$ or $n=3k+1$ or $n=3k+2$. For each such possibility show that one of the terms in the product is a multiple of $3$.

For proceeding with induction: assume it holds for the $n$ case, i.e assume that
$$n(n+1)(n+5)=\color{blue}{n^3+6n^2+5n}=3k$$
Now consider
\begin{align*}
(n+1)(n+2)(n+6)&=n^3+9n^2+20n+12\\
&=\color{blue}{(n^3+6n^2+5n)}+3n^2+15n+12\\
&=3k+3(n^2+5n+4).
\end{align*}
Thus the left hand side is a multiple of $3$.

A: Your proof is not correct
because
$\frac{n+2}{n}\frac{n+6}{n+5}
$
is never an integer.
Just looking at it,
$\frac{n+2}{n}\frac{n+6}{n+5}
=\frac{n^2+8n+12}{n^2+5n}
=\frac{n^2+5n+3n+12}{n^2+5n}
=1+\frac{3n+12}{n^2+5n}
$,
and
$n^2+5n > 3n+12$
when
$n^2+2n>12$
or
$(n+1)^2 > 13$
which is true for $n \ge 3$.
A proof by induction
could go like this:
Base case:
For $n=1$,
$n(n+1)(n+5)
=1\cdot 2 \cdot 6
=12
$
is divisible by 3.
Induction step:
The difference between
the expression for
$n+1$ and $n$ is
$\begin{array}\\
(n+1)(n+2)(n+6)-n(n+1)(n+5)
&=(n^3+9 n^2+20 n+12)-(n^3+6n^2+5n)\\
&=3n^2+15n+12\\
&=3(n^2+5n+4)
\end{array}
$
and this is obviously divisible by 3.
Therefore,
if
$n(n+1)(n+5)$
is divisible by 3,
so is
$(n+1)(n+2)(n+6)$.
Since
$n(n+1)(n+5)$
is divisible by 3
for $n=1$,
it is divisible by 3
for all $n$.

A: The proof by induction is !!CUTE!!!
Base: step.  If $n = 1$ then $n(n+1)(n+5) = 1*2*6 = 12$ is divisible by 3.
Induction: Assume that for some $m$ we know that $m(m+1)(m+5)$ is divisible by 3, we want to prove that $(m+1)(m + 1 + 1)(m + 1 + 5)$ is divisible by 3.
Proof:
Let $m(m+1)(m+5) = 3X$.
$(m+1)(m+1+1)(m + 1 + 5) = $(m+1)(m+2)(m+6)$
$=(m+1)(m + 2 + 3)(m+6) - 3[(m+1)(m+6)]$
$= (m+1)(m + 5)m + 6[(m+1)(m+5)] - 3[(m+1)(m+6)]$
$= 3X + 6[(m+1)(m+5)] - 3[(m+1)(m+6)]$
$= 3[X + 2[(m+1)(m+5)] -[(m+1)(m+6)]$ is divisible by 3.
So we are done.
By induction we not the proposition is true for n = 1.  we know if it is true for n it is true for n+1, so inductively it must be true for all natural numbers.

A: If you're looking for a proof by induction, start by labeling $f(n)=n(n+1)(n+5)$. Then, you can show that $f(n+1)-f(n)=3(n+1)(n+4)$, which is a multiple of $3$. So:

*

*$f(0)=0$ is a multiple of $3$

*If $f(n)$ is a multiple of $3$, then $f(n+1)=[f(n)]+[f(n+1)-f(n)]$ is a sum of two multiples of $3$, and is hence a multiple of $3$ itself.

Induction does the rest of the work for us from here.
Perhaps interesting to note that $f(n)$ is always a multiple of $6$ - this takes slightly more work, but can be adapted readily by showing that $3(n+1)(n+4)$ is always a multiple of $6$.


text:
Q: Remove duplicate array elements in C
Possible Duplicate:
remove duplicate elements in an array in O(n) in C/C++

How can I remove duplicate elements from an array?
Before
array [ ] = {1,2,3,4,5,1,2,4,9,0,0}

After
array [ ] = {0,1,2,3,4,5,9}

A: *

*Sort the array using your favorite sorting algorithm.

*Walk through the array and eliminate duplicates - if a value is the same one as the previous one, keep going forward until you get a new value and then copy it back.

A: Use hash table and store each element into hash table. This way you will remove duplicates. This will give you O(n) complexity but you will have to add hash table support.

A: Given that you have an array of integers, and that you know their exact bounds, you can create a lookup table with a single pass over the input (use a bit vector if you have to constrict space) and then generate the array of unique entries with a single pass over the lookup table.
This would be a VERY SPECIFIC solution for a VERY SPECIFIC problem, but it does what you ask for.

A: memset(index,0,sizeof(index));
for (int i=0; i<len(array); ++i)
   index[array[i]] = 1;
memset(array,0,sizeof(array));
for (int i=0,int j=0; i<len(index); ++i)
   if (index[i]) array[j++] = i;


text:
Q: Form validation in thymeleaf by Springboot I am new to the Springboot and Thymeleaf, I am creating a web where i am using form validation where I am trying to validate fields from an entity class to validate non empty fields.
import javax.validation.constraints.NotBlank;

public class Student {

@NotBlank(message = "Name required")
public String name;
@NotBlank(message = "email required")
public String email;
@NotBlank(message = "address required")
public String address;
@NotBlank(message = "username required")
public String username;
@NotBlank(message = "password required")
public String password;

'''
constructor
getter and setter
'''
}

It is not showing error in my html file, showing error on server.
If any one has any idea please help me.

A: In order this to work add @valid annotation next to @ModelAttribute("student").
    public String addUser(@Valid @ModelAttribute("student") Student student, BindingResult result, Model model){

And also try adding @NotEmpty above the field of Student entity. @NotEmpty will check if the object has empty strings.

A: Try this,
public String addUser(@Valid @ModelAttribute("student") Student student, Model model){
...
}

Also, add @NotNull on entity attributes and check once.

A: Try out this:
    public String addUser(@Valid @ModelAttribute("student") Student student, BindingResult result, Model model){

Also, add @NotNull on entity attributes and check once.


text:
Q: left string function in C# What's the best way to return the first word of a string in C#?
Basically if the string is "hello world", I need to get "hello".
Thanks

A: One way is to look for a space in the string, and use the position of the space to get the first word:
int index = s.IndexOf(' ');
if (index != -1) {
  s = s.Substring(0, index);
}

Another way is to use a regular expression to look for a word boundary:
s = Regex.Match(s, @"(.+?)\b").Groups[1].Value;

A: You can try:
string s = "Hello World";
string firstWord = s.Split(' ').First();

Ohad Schneider's comment is right, so you can simply ask for the First() element as there will always be at least one element.
For further info on whether to use First() or FirstOrDefault() you can learn more here

A: The answer of Jamiec is the most efficient if you want to split only on spaces. But, just for the sake of variety, here's another version:
var  FirstWord = "Hello World".Split(null, StringSplitOptions.RemoveEmptyEntries)[0];

As a bonus this will also recognize all kinds of exotic whitespace characters and will ignore multiple consecutive whitespace characters (in effect it will trim the leading/trailing whitespace from the result).
Note that it will count symbols as letters too, so if your string is Hello, world!, it will return Hello,. If you don't need that, then pass an array of delimiter characters in the first parameter.
But if you want it to be 100% foolproof in every language of the world, then it's going to get tough...

A: You can use a combination of Substring and IndexOf.
var s = "Hello World";
var firstWord = s.Substring(0,s.IndexOf(" "));

However, this will not give the expected word if the input string only has one word, so a special case is needed.
var s = "Hello";
var firstWord = s.IndexOf(" ") > -1
                  ? s.Substring(0,s.IndexOf(" "))
                  : s;

A: Shamelessly stolen from the msdn site (http://msdn.microsoft.com/en-us/library/b873y76a.aspx)
string words = "This is a list of words, with: a bit of punctuation" +
    "\tand a tab character.";

string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

if( split.Length > 0 )
{
    return split[0];
}

A: Handles the various different whitespace characters, empty string and string of single word.
private static string FirstWord(string text)
{
    if (text == null) throw new ArgumentNullException("text");

    var builder = new StringBuilder();

    for (int index = 0; index < text.Length; index += 1)
    {
        char ch = text[index];
        if (Char.IsWhiteSpace(ch)) break;

        builder.Append(ch);
    }

    return builder.ToString();
}

A: Instead of doing Split for all the string, Limit your Split to count of 2. Use the overload which takes count as parameter as well. Use String.Split Method (Char[], Int32)
string str = "hello world";
string firstWord = str.Split(new[]{' '} , 2).First();

Split will always return an array with at least one element so either .[0] or First is enough.

A: string words = "hello world";
string [] split = words.Split(new Char [] {' '});
if(split.Length >0){
 string first = split[0];
}

A: I used this function in my code. It provides an option to either uppercase the first word or every single word.
        public static string FirstCharToUpper(string text, bool firstWordOnly = true)
    {
        try
        {
            if (string.IsNullOrEmpty(text))
            {
                return text;
            }
            else
            {
                if (firstWordOnly)
                {
                    string[] words = text.Split(' ');
                    string firstWord = words.First();
                    firstWord = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(firstWord.ToLower());
                    words[0] = firstWord;
                    return string.Join(" ", words);
                }
                else
                {
                    return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text.ToLower());
                }
            }
        } catch (Exception ex)
        {
            Log.Exc(ex);
            return text;
        }
    }


text:
Q: node doesnt run in intergreted terminal in vs code I installed node js . it works in Powershell , cmd but not in vs code .
node : The term 'node' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ node -v
+ ~~~~
    + CategoryInfo          : ObjectNotFound: (node:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

A: I had a similar issue when I installed node while vscode was already running.
Try reloading vscode. This issue on github gave me more clarity:
https://github.com/Microsoft/vscode/issues/13671#issuecomment-255778379


text:
Q: Weblogic Session Timeout Redirect to Login Page My App is a HTML and JS Based. I'm using form based auth j_security_check.
The Login and Logout works are expected.
But upon session timeout, If I request a JS file, the Login Page comes in the Content area and upon success login the JS code is displayed in the UI.
I've a filter in place but even when the session is timed out
if (session != null && !session.isNew())

returns
true

1) How do I do a proper redirect to login page ?
2) If filter is the answer, why is my session still present? Is it due to JSESSIONID ? How do I satisfy my session check and do a req dispatch to login page?
Filter Code
if (session != null && !session.isNew()){
    chain.doFilter(request, response);
}else{
    req.getRequestDispatcher("/login.html?sTimedOut=true").forward(request, response);
}

A: The only option I see is,
Have a session timeout logic in Javascript and keep checking every sec for if event for mouse click else key press, if not redirect to login page.


text:
Q: Different Prettier rules for different file types? Does Prettier have a way to specify different rules for different file types?
For example, I want a greater maximum line length in our template files (.tsx) because it's more common for markup to be more deeply nested than application code. But for all other files I would like to enforce the standard 80 char width.

A: You can add overrides like this:
{
    "printWidth": 80,
    "overrides": [
        {
            "files": "**/*.tsx",
            "options": {
                "printWidth": 120
            }
        }
    ]
}

In that, printWidth option will be set to 80 for everything except files matching **/*.tsx, for which the printWidth will be 120.


text:
Q: Java Applet not working when another web app with applet is active I have active web app that uses applet to accessing computer COM ports (printing without prompting user). Everything is working fine until there is another web app that uses applet is active. I don't have access to another apps source code.
The problem is I am very noobish in Java Applet-s and I don't even know what might be the problem. Has anyone encountered this issue, or can anyone at least point me in the right direction, where and what should I be looking at, and/or how this problem can be avoided.
Thx in advance

A: Maybe the life-cycle. There are four methods relating to the life-cylce:

*

*init

*start - page is loaded

*stop - page is unloaded

*destroy

Do all initialisation in start, destruction in stop and everything should be more encapsulated.
Also do not use static objects, and I am even as paranoid to set fields to null when feasible (destroy, stop).


text:
Q: mongoimport ignore _id key (E11000 duplicate key error index) Let's say I have the following two JSONs, and I'd like to import them to the same collection without merging or updating the existing documents. Is there a way, to ignore the existing _id keys during import and end up with a single collection containing all the 6 documents of the example below?
The old _id properties have no relevance whatsoever. I could rename/remove them from the source files, I'm just curious if there is a way to do this during import.
coll1.json:
{"_id":1,"a":1}
{"_id":2,"a":2}
{"_id":3,"a":3}

and
coll2.json:
{"_id":1,"a":4}
{"_id":2,"a":5}
{"_id":3,"a":6}

If I simply import them, with mongoimport --db imp --collection imp --file coll2.json I'm getting E11000 duplicate key error.

A: If you want to overwrite the document import by using following command
mongoimport --db imp --collection imp  --mode upsert --file coll2.json

In mongodb _id field is by default unique so you cant have _id with same value like you had in your case
coll1.json:
{"_id":1,"a":1} // _id is same as document below
{"_id":2,"a":2}
{"_id":3,"a":3}

coll2.json:
{"_id":1,"a":4} // {"_id":1,"a":1}
{"_id":2,"a":5}
{"_id":3,"a":6}

What you can do in this case is Change the name of key from _id to id which will allow you to have more then one document with same value of id.
coll1.json:
    {"idField":1,"a":1}
    {"idField":2,"a":2}
    {"idField":3,"a":3}

    coll2.json:
    {"idField":1,"a":4}
    {"idField":2,"a":5}
    {"idField":3,"a":6}


text:
Q: Why does a Sallen-Key low-pass filter improve ripple in my PWM to DC voltage converter circuit? The original low pass filter converts PWM to DC voltage.
You can see the nasty ripple on the ouptut in the oscillscope:

Sallen-Key improvement:

What exactly is happening with the Sallen-Key that makes it have less ripple?
Try to explain it by identifing the effect that causes the  basic low pass filter to have a downward ripple on the falling edge of the PWM signal. Is it due to a capacitor C1 discharging?? If it is due to C1 where is the current going when the PWM is on a falling edge/ 0 volts?

A: *

*The RC filter in your first diagram has a "1st order response".

*The Sallen Key op-amp filter has a "2nd order response".
This means, that for the same cut-off frequency (3 dB point), the 2nd order filter has a significantly better ability to attenuate high frequencies in the "stop-band": -

Image from here.
The red trace is a first order filter and the blue trace is a 2nd order filter and, at any arbitrary point in the spectrum above the 3 dB point, the 2nd order filter produces a much higher attenuation of unwanted AC signals such as your PWM waveform.

What exactly is happening with the Sallen-key that makes it have less
ripple??

It's still there but to a much lesser extent.
For the 1st order circuit it is the capacitor charging and discharging via the input resistor. But, for the 2nd order filter there an identical cascaded RC filter that both significantly attenuates the ripple seen in the first order circuit and reshapes it to be more sinusoidal so, if you homed in on the 2nd order output waveform you would see a small sinewave type ripple voltage.


text:
Q: Airflow DBT Run - BigQury operation timeout error I'm running DBT-Airflow for BigQuery orchestration, but I'm getting this BigQuery operation timeout error:
[2022-09-29, 07:44:33 UTC] {subprocess.py:89} INFO - 07:44:33  Runtime Error in model model_1 (models/analytics/model_1.sql)
[2022-09-29, 07:44:33 UTC] {subprocess.py:89} INFO - 07:44:33   Operation did not complete within the designated timeout.
We tried increasing job_execution_timeout_seconds parameter in the profiles.yml file but no results. Any help will be really appreciated.


text:
Q: After I increased spark.executor.memory for pyspark, it crashed at where it used to pass. How can I get through this? To cut it short, I used to run a piece of pyspark code in pyspark shell with default settings(driver 1g, executor 1g).
The code crashed some where because of some unknown memory leak after several loops.(I've already tried some tricks to cut the data lineage, so, the leak is still unknown)
To better inspect the source of the memory leak, I have to increase the executor memory to make it crash after more loops. And I'll take some heap dump for analyzation.
However, when I increased the executor memory to 2g, the application crashed before it start the first loop.(it used to crash at the 3rd loop). It look like this:
2019-09-25 10:16:29,833 WARN execution.CacheManager: Asked to cache already cached data.
Sampling success
iteration #0
2019-09-25 10:16:30,005 WARN util.Utils: Truncated the string representation of a plan since it was too large. This behavior can be adjusted by setting 'spark.debug.maxToStringFields' in SparkEnv.conf.
/usr/lib64/python2.7/site-packages/pyarrow/__init__.py:157: UserWarning: pyarrow.open_stream is deprecated, please use pyarrow.ipc.open_stream
  warnings.warn("pyarrow.open_stream is deprecated, please use "
iteration 0 loss 13387.430943

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "bpr_spark2.py", line 458, in test
    bpr.build(train_data, ss, k = number_of_factors, num_iterations=80000)
  File "bpr_spark2.py", line 253, in build
    self.train(ss)
  File "bpr_spark2.py", line 353, in train
    samples = self.draw(ss).withColumn('id', functions.row_number().over(Window.orderBy('u'))).repartition(self.partitionNum)
  File "bpr_spark2.py", line 302, in draw
    while(lastSamples is None or lastSamples.count() < batchSize):
  File "/opt/spark/python/pyspark/sql/dataframe.py", line 522, in count
    return int(self._jdf.count())
  File "/opt/spark/python/lib/py4j-0.10.7-src.zip/py4j/java_gateway.py", line 1257, in __call__

  File "/opt/spark/python/pyspark/sql/utils.py", line 63, in deco
    return f(*a, **kw)
  File "/opt/spark/python/lib/py4j-0.10.7-src.zip/py4j/protocol.py", line 328, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o1688.count.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task serialization failed: java.lang.StackOverflowError
java.lang.StackOverflowError
    at java.lang.reflect.InvocationTargetException.<init>(InvocationTargetException.java:72)
    at sun.reflect.GeneratedMethodAccessor49.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1140)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)

You may expect an extremely long call stack here. Looks like some dumping operation.
The phenomenon disappeared when I set the driver memory to 2g.
So, what is it about?
For the environment I've been using is the hadoop 3.1.2 + spark 2.4.3.
With PyArrow installed and enabled for spark.
The source code to reproduce the problem is very long, with an established database, I'll upload the py code, the database used can be found on github/moviegeek.
I'll also try to make an upload of the execution environment, it's inside the docker. But it would be costly and don't expect it would come out in days?
So, can any one tell me why the driver memory must keep in the same with executor memory?
Hers is the link to the code:
https://github.com/Heermosi/moviegeek-spark/blob/master/bpr_calculator_spark.py
I cannot find out the leak point. Configure the database and run test() to replicate the error. Any one can help?
Updated 2019/09/26:
I tried hard to print out the rdd data lineage and found out the data lineage is not really cut short!
Which means the function does not work correctly, the method posted on website promised to cut short without write files is a joke!
I'll search for other ways to make the data lineage cut.
As for now, hmmm, write to files would be a good choice.


text:
Q: Why li with 50% width and float left don't show dots on the left I've try to create 2 colums list so I use:
ul {
   overflow: hidden;
}
ul li {
   float: left;
   width: 50%;
}

but when I have 2 items that one on the right have list bullet and the one on the left don't. Why is that?
PS: is there a way to have 2 columns list without using :before with content: "•"

A: The left ones are still having a bullets but you can't see it because of the float: left;. I think if you remove it, the problem will dissapear, specially if before that you have a reset margin: 0; padding: 0; for all the elements in the current html page.

A: I had the same problem and neither overflow:hidden nor display: inline-block worked for me.
So I cheated using the unicode number for 'bullet' before all items in my list: •
It's far from elegant, but does the trick in desperate situations.


text:
Q: Dynamically created class rows not iterating through jQuery .each()? I have a several tables like this:

<input tabindex="-1" id="checkbox-delete-all" type="checkbox" />
        <spring:message code="createOrder.label.lineNumber.text"/>
        <spring:message code="createOrder.label.original.text"/>
        <spring:message code="createOrder.label.quantity.text"/>
        <spring:message code="createOrder.label.description.text"/>
        <spring:message code="createOrder.label.abc6.text"/>
        <spring:message code="createOrder.label.abc8.text"/>
        <spring:message code="createOrder.label.upc.text"/>
        <spring:message code="createOrder.label.ndc.text"/>

        <input tabindex="-1" class="checkbox-delete-row" type="checkbox" />
        10
        <input class="id-target row-product-id" name="lineItem[0].originalInput" type="text" />
        <input class="qty-target row-qty" name="lineItem[0].quantity" type="text" value="1" />

        <input readonly tabindex="-1" class="abc8-target row-abc8" name="lineItem[0].abc8" type="text" />

        <input id="button-delete-items" type="button" title="<spring:message code="createOrder.btn.deleteItems.title"/>" />
        <input id="button-cancel-order" type="button" title="<spring:message code="createOrder.btn.cancel.title"/>" />

        <input id="button-submit-order" type="submit" title="<spring:message code="createOrder.btn.submit.title"/>" />

Another function is generating dynamic lines which are added to the table based on the data returned from an AJAX call.  They have the same structure and class names as the first static row.
And some jQuery/JavaScript like this:
$(document).ready(function() {

// Event Listeners Section

    $(document).on("click", "#button-delete-items", ajaxDeleteLine);
    $(document).on("focusout", ".id-target", ajaxGetData);

    function ajaxDeleteLine() {

        var i = 0;

        $(".checkbox-delete-row:checked").each(function() {
            i++;
            console.log(i);
        });

        $.ajax({
            type: "post",
            url: contextPath + "/deletesLineItem.do",
            data: {
                lineIds: 1
            }
        })
        .fail(function(data) {
            alert("Error: Failed to delete lines!");
        })
        .done(function(data) {
            //alert(data);
        });
    }
});

When I click #button-delete-items it's only iterating the first element in the log, not the dynamically created ones. What am I doing wrong?

A: Isn't there problem in
 data: {
            lineIds: 1
        }

Which always sends 1, not the row ids?

A: I'm not really sure what you want here, but my guess is that you want to grab each selected checkbox and delete the row it's on?? If so, you'll need something like this:
HTML

        <input type="checkbox" class='checkbox-delete-row' name="vehicle1"/>
        Jill
        Smith
        50

        <input type="checkbox" class='checkbox-delete-row' name="vehicle1"/>
        Eve
        Jackson
        94

        <input type="checkbox" class='checkbox-delete-row' name="vehicle1"/>
        John
        Doe
        80

        <input type="checkbox" class='checkbox-delete-row' name="vehicle1"/>
        Adam
        Johnson
        67

<button id='button-delete-items'>button</button>
<button class='clone'>clone</button>

JS
(function(){

    $(document.body).on('click', '#button-delete-items', doDelete);
    $(document.body).on('click', '.clone', clone);

    // dynamically create checkboxes
    function clone(){
        $('.checkbox-delete-row:checked').each(function(){
            $('table').append($(this).attr('checked', false).parents('tr').clone());
        });
    }

    function doDelete(){
        $('.checkbox-delete-row:checked').each(function(idx, value){
            //idx is its index
            console.log(idx);
            $(this).parents('tr').remove();
        });
    }

}());

JSFFIDLE

A: You can try to write it differently - something like
$('.checkbox-delete-row').each(function(index,element){

if($(element).is(':checked') console.log(index);

})

But are you really really sure (tripple check it) that rows returned by AJAX have the same classes?
Are the rows properly attached to the table/table body? (I mean weirdest stuff i've ever met was based on wrong markup, that browsers tried to translate on their own)

A: Ok. After I wracked my brain on this for several days I finally sat down with my coworkers (fellow programmers) and I figured out what the problem was.
It was hard to demostrait in the context of SO because of the limited scope of what can be posted here.
I forgot to pass the jquery selector data into the second function call which was being called from the first. Essentially the data I needed was out of scope.
The reason I didn't think I needed to do this was because I was using jquery on and assumed that it would bind any subsequent events to the same event handler. I was wrong.
By setting var checkeditems = $(".checkbox-delete-row:checked") and then passing checkeditems as a param in the function call inside the first function call I got it working. But This led me to realize I have another problem.
I don't want to iterate trough the DOM to gather meta-attached HTML5 data if I need to serialized it and send it over ajax. Instead what I want to do is create hidden named inputs and use a jquery selector to find the checked ones and then serielize() them.
Thanks to everyone who tried I to help with this.  Sorry for all the trouble.


text:
Q: How does wireless mobile charging work in BMW 7 series car? I've seen a video in which the presenter just keeps the phone in some small chamber and closes it for automatic charging of smartphone.

A: QI standard wireless charging. Must have a QI compatible phone or adapter (sticker, case, wired adapter which defeats part of the purpose). Any Samsung higher end phone for the last two years has had QI charging coils on the battery. Newer S7 models have fast - wireless charging as well. As with most wireless charging the distance is inches/mm at best. They are intended to sit flay against the charging pad.


text:
Q: Attempted git merge aborts without any error C:\Users\danie01\fox (fox-45481 -> origin)
λ git merge feature/master-stg
error: The following untracked working tree files would be overwritten by merge:
        blah/blah/blahblah.cpp
        ... (many files)
        common/wizard/wizpa
Aborting

C:\Users\danie01\fox (fox-45481 -> origin)
λ

It's been a very long time since I previously merged. Further, the last commit in this branch was a merge.
Interestingly, the final file in this list is cut off (it doesn't have the file extension or complete the file name even) - could this be an issue with my buffer?
I have just recently checked this out from a remote branch; I do not have permissions to merge into a remote branch and need to create a merge request. Could it be the case that git is trying to merge directly into the remote branch?
What can be done here? I am at a loss.

A:
Could it be the case that git is trying to merge directly into the remote branch?

No.  That's not how Git performs merges.
(Incidentally, your subject line is wrong, as the merge aborts with an error, telling you that certain untracked files would be overwritten.)

Interestingly, the final file in this list is cut off (it doesn't have the file extension or complete the file name even) - could this be an issue with my buffer?

I'm not sure what you mean by that, but certainly the file names in the output should not be truncated.
Note that when you ask Git to do a merge, it must juggle several different items.  All commits are frozen (read-only) and essentially permanent,1 so they are not a problem.  But there are two things that are not frozen and therefore may be overwritten:

*

*Your current index content.  Your index holds one—or sometimes (during an incomplete merge) more than one—entry for each tracked file in the work-tree.  In fact, that's what a tracked file is: it's a file that is in the work-tree right now that is also in the index right now.2

*Your current work-tree content.  Git doesn't use this directly—it's there for you to use—but various operations will, of course, overwrite files in the work-tree.  For instance, git checkout of some other branch is obviously going to have to overwrite at least a few files, if the other branch has different file contents.
Between these two things, it's easy for you to create untracked files.  An untracked file is simply a file that exists in your work-tree right now, but that is not in your index right now.  Each such file can be either ignored or not ignored, but either way, it's untracked.  If it's not ignored, git status will complain about it.
Before you start a merge, it's a good idea to make sure of two things: first, that you're not already in the middle of some other operation, and second, that your HEAD commit, index, and work-tree all match in terms of all your tracked files.  The git merge command does most of this automatically but it's never a bad idea to run git status first and make sure that it says nothing to commit, working tree clean.
It's OK if this also complains about various untracked files, as we get a chance to deal with them in a moment.  Now that you are sure that there is no in-progress work that might be lost, you issue your merge command:
λ git merge feature/master-stg

What Git does now is:

*

*Look up the hash ID of the current commit (git rev-parse HEAD).

*Look up the hash ID of the specified commit (git rev-parse feature/master-stg).

*Use git merge-base --all to find the merge base(s) of these two commits.  The merge base is a commit, or sometimes more than one commit, that is on both branches, and is the best such commit.

Ideally, there's only one merge base commit.  You can verify whether this is the case by running:
git merge-base --all HEAD feature/master-stg

If it prints out just one hash ID, that's the (single) merge base commit.  Getting multiple merge bases here is rare, and if it happens, this requires more discussion, but since it is rare (and probably not happening here) we can just assume there's only the one merge base.
In some cases, there's just the one merge base and it's the same hash ID as the current (HEAD) commit.  These cases are generally very easy to handle and Git defaults to doing a fast-forward operation instead of a merge.  Probably yours is not such a case (but it could be—there's no evidence here one way or the other).  I'll assume that Git is doing a real merge, since the problem is going to be the same either way, and the solution is going to be the same.

1Files inside a commit are definitely frozen, but they exist in that form because the commit exists.  If you manage to get Git to forget about that commit, the commit itself will eventually vanish.  It's very hard to do this, so commits are mostly permanent.  They are completely read-only, though: nothing in any commit, as identified by its hash ID, can ever change.
2Technically, you can remove the work-tree copy while leaving the index copy in place.  That would still be a "tracked file", I think, although the nomenclature gets a little shaky.  (How can a file be tracked if that file doesn't exist?)

How Git performs a real merge
Now that Git knows the three inputs to the merge—the base commit, the --ours or HEAD commit, and the other or --theirs commit, from feature/master-stg, Git will, in effect, run two git diff commands:
git diff --find-renames <hash-of-base> HEAD                # what we changed
git diff --find-renames <hash-of-base> feature/master-stg  # what they changed

The job of the merge is now pretty simple and pretty obvious.  This is what it will have to do:

*

*Start with all the files that were in the merge base commit.

*Then, if we changed or created or removed (and/or renamed) a file, and they didn't touch the file, use our change.

*If they changed or created or removed (and/or renamed) a file, and we didn't touch the file, use their change.

*If we and they both changed or created or removed (and/or renamed) the same file, combine these two separate sets of changes.

In simple cases, doing all of this is pretty simple.  For instance, perhaps we both touched README.md, but on different lines; we changed a/main.py and they didn't; and they changed b/prog.cc and we didn't.  The result of the merge, then, will be all the base files, except for README.md, which has the combined changes, our a/main.py, and their b/prog.cc.
If all goes well, Git commits the resulting files, putting them into your index and work-tree along the way.  The new commit updates the current branch, so that whatever branch HEAD names, now names the new commit.  The new commit's first parent is the previous tip of the current branch, and the new commit's second parent is the other commit (the one still identified by feature/master-stg, in this case).  Since the new commit has two parents, it is a merge commit.
In complicated cases, something goes wrong, and the merge either stops in the middle—which is the messiest case—or never starts.  You have the latter case: the merge never starts.
You have untracked files that they have in their commit
What's going wrong here is that in their commit—the one named by feature/master-stg—they have some files committed, that:

*

*are not in the merge base commit, and

*are not in your HEAD commit either.

Git has printed out the complete list of these files:

blah/blah/blahblah.cpp
... (many files)
common/wizard/wizpa

In the git diff --find-renames <hash of merge base> feature/master-sta output, they have added these files.  You can confirm this by running that same git diff yourself, perhaps with --name-status so that it's shorter and more readable.
You don't have those files in your HEAD commit, but you do have these very same files in your work-tree right now.
For Git to do the merge and get the final result in place, Git will have to overwrite your work-tree files.  Since they're not in your index and not in your commit, Git cannot be sure that it's OK to destroy the only copy of them, sitting in the work-tree.  Git therefore aborts the merge, never starting it at all.
The solution is to do just what Git said, or should have said (maybe it's lost in the "blahblahblah" part):

Please move or remove them before you merge.

Essentially, Git feels the need to overwrite these files.  If it does so, whatever contents you have in them will be irretrievable—or at least, Git won't be able to get it back.  So you must save the contents elsewhere, if they are valuable.

A: I think that git is trying to tell you that by running the merge, some files that, on your current working tree are, they not being tracked, on the other branch they are tracked and so they would be overwritten if you merge. I guess you could just delete them from your working tree so that the merge goes through.


text:
Q: Is there a proper technical term for (physical) sections in a card file? Imagine having a card-box that contains, for example, vocabulary. It's organized alphabetically and for every letter there's a larger card acting as a separator for words beginning with that letter.
Is there a clear, unambigous word that describes the bundle of cards behind this larger index-card? I'm thinking of section, but am unsure if it's really the best word. And maybe the professionals in that field are using a special word for this...

A: Tab Section, Section, or just Tab, the last in the sense of contents of a tab section.
Use Case
Loletrazina Church, How to Use a Rolodex (bizfluent):

Arrange the cards alphabetically in your file. For example, place … the cards of people and businesses that start with the letter "A" in "A" section of the Rolodex.


text:
Q: Regression analysis with time series data I'm completely stuck. I'm making a regression analysis in Python :
my dependent variable - share price of company,
independent variables - price of steel, price of coal and changing in local currency.
According theory I can't use this time series depended and independent variables due to autocorrelation.
Can I solve this problem by taking percent changing day-to-day of share price and percent changing day-to-day independed variable ? I have check this data for stationarity with Dickey Fuller test and get appropriate results, but I think that isn't right way.
or
What are the ways to build such a model ?
P.S I'm recently read that for time series data ARMA model is the good choice, but I don't understand how take in account independent variable, not predict on dependent variables on itself.
Thank you in advance!

A: Conventional wisdom suggests that you should use ARCH (GARCH) models rather than OLS or ARIMA models, for the modeling of returns (percent change in prices). The literature of those models is very vast, but basically the starting model should be a GARCH(1,1).


text:
Q: How to fix firefox stop javascript when not responding I'm currently create a javascript that run a loop forever. However, after a few hours my script stop working, it asks me to continue or stop script. Is there anyway to fix this or use some automation tools to restart firefox and run the javascript again. Because most of time I away from keyboard

A: To prevent the long running javascript prompt, you need to occasionally let javascript process other events.   The classic way to do this is like this is using setTimeout().
function doNextChunkOfWork() {

    // do some work here

    if (moreWorkToDo) {
        setTimeout(doNextChunkofWork, 1);
    }
}

Using the setTimeout() lets the javascript engine get back to its event queue and process other events and thus prevents the long running script warning.

If you explained what you're really trying to do, we might be able to suggest even better options.  If you're doing some sort of infinite loop, javascript in a browser is meant to be an event-driven environment where the usual mechanism is to create event handlers and let events trigger code to run.  It is not meant for infinite loops polling for something.

A: id strongly recommend not using any kind of infinite loop - doing so would be just asking for trouble. instead you want to look into using javascript's setTimeout() and/or setInterval() functions... allowing you to specify a block of code to run every X milliseconds
you can find the docs here
setTimeout()
setInterval()


text:
Q: Modifying a class instance from inside the class suppose i had a serializeable class such as
[Serializable]
    public class DatabaseViewModel:MVVM.ObservableObject
    {
        //fields
        //properties

        public DatabaseViewModel()
        {
           //if a serialization file exists then deseralize and make this instance equal to it
           //else initialize fields
        }
    }

is it possible to do such thing from inside the class and not the calling scope?
in the calling scope i would just do
var dbvm = new DatabaseViewModel();

and then i want the constructor to decide if it should create a new object or load a serialized object.
inside my class i tried this
this = //my serialized object

if i wanted to do it from the calling scope i would just do
DatabaseViewModel dbvm = null;
if(File.Exists(".../DatabaseViewModel.bin")
dbvm = //deserialize .../DatabaseViewModel.bin
else
dbvm = new DatabaseViewModel();

A: No you can't replace the this reference of an object. You can use a Factory/Builder, as was suggested.
However, a recently deserialized object has one difference to any other object: noone else has a reference to it. So while this isn't possible:
class MyClass
{
    public MyClass(MyClass arg)
    {
       this = arg;
    }
}

This is possible
class MyClass
{
   public MyClass(MyClass arg)
   {
      this.CopyFrom(arg);
   }

   void CopyFrom(MyClass m)
   {
      // Assign fields from m.
   }
}

Now if you replace the argument object to be copied, with what you need to find the deserialized data and deserialize internally:
class MyClass
{
   public MyClass(int id)
   {
      if (FileExistsOnDisk(id))
      {
         MyClass m = DeserializeFromFile(id);
         CopyFrom(m);
      }
      else
      {
          // Normal construction.
      }
   }
}

However, you don't want to keep the persistence logic and IO in a constructor anyway so you will get a much better design by simply making the choice between creation or deserialization of the object the responsibility of some other object, e.g. a factory/builder.
public class MyClassFactory
{
   public MyClass GetObj(int id)
   {
      if (FileExistsOnDisk(id))
         return DeserializeFromFile(id);
      else
         return new MyClass(id);
   }
}

"if i wanted to do it from the calling scope i would just do"

And you do.

A: You might want to look into factories: http://www.dotnetperls.com/factory. You cannot do this from constructor, as far as I know.
Also, check out this related post: Using this() in C# Constructors.


text:
Q: extjs: Loading screen icon not spinnig after some time I have applied the loading icon in my application, It works fine on some places. But when there is huge data which is loading in grid that time loading icon appears ani spinning for some time after some duration the spinning stops and icon gets hang, but the record is fetching.
Grid refresh after some time.
How to fix the issue, so that the spinning continues till the data loads completely.

A: Problem is not in ExtJS library. Problem is in browser.
When browser process huge data it requires a lot of system resources. So browser decreases priority given to GIF image animation render and raises priority for data process.
You can see such behaviour in ExtJS DOCS. Just try to open > 10 tabs inside docs. Traversing across the docs tabs displays LoadMask GIF image and it stops spinning sometimes. (tried in Mozilla Firefox).


text:
Q: Is it possible attach a widget to the Android background? I was wondering if is it possible attach a widget to the main Android background/wallpaper/desktop?
I want develop something like a clock, actually It's a very simple widget that have three buttons. This is quite different from another desktop-widgets-like, all the widgets that I've seen are like a customization of the Android wallpaper, or a customization of the Android unlocker, but this is rather different.
If it is possible, do you know some sample code source?

A: Not sure what "background/wallpaper/desktop" really means, as "background" is too wide term, "wallpaper" may be either static bitmap or live wallpaper, "desktop" means nothing on Android (did you mean Launcher by any odd chance?). If you meant live wallpaper, then you cannot have full functionality in Live Wallpaper you have on Launcher, but if "three buttons" means you want to allow user to tap certain area and react on this, then it should be not a big problem - you can use onTouchEvent() to receive taps from user and act accordingly. If you meant Launcher then well, "yes". For any other options "no" or "most likely no"


text:
Q: Write Excel Cell Comment using Python on Linux? I am using Python in a Linux (Ubuntu) environment.
How do I go about writing a  comment into a cell in an Excel file (say,MyFile.xls)?
I know that it is possible to write values. Yet, how do I go about writing a comment?

A: On Windows (with Excel installed) you could use COM from Python: this class wraps it nicely for you.
But on Linux, you'll need to use xlwt.

A: I'm looking into this myself and found https://bitbucket.org/ericgazoni/openpyxl/wiki/Home .
It is a new library that allows editing xlsx files.
I'm not sure if it allows editing comments though.


text:
Q: how to use linq in struct When i use LINQ in my struct in the silverlight project, this error comes. please help out why?

Anonymous methods, lambda expressions, and query expressions inside
  structs cannot access instance members of 'this'. Consider copying
  'this' to a local variable outside the anonymous method, lambda
  expression or query expression and using the local instead.

A: I also faced the same problem while trying to use LINQ in struct. struct is value type so it LINQ cannot be used in it. Instead of this, make a separate class, create functions there with LINQ based stuff of yours, and access those functions using the object of that class.


text:
Q: Creating Directories and Files through PHP and Permissions Issues I have a php application that creates directories and files from user input.  Is it a problem to have php create the directories/files and then use the php chmod function to set the permissions to 755/644?
When I do that, it looks like the only way to delete those files is through php.  So if I want to delete them via FTP, it won't work because apache/php owns them.
Mainly, though I'm trying to figure out if I would need to do anything else besides chmod to 755/644 for the directories/files to make things as secure as possible.

A: Just chmod them to 777 via php. Then youll able to delete files from ftp. 755 still allows writing only for php..

A: If you use php to create directories and files from user input you should consider disallowing execution of php (and other) scripts from location where it stored. This can be done in .htaccess if you are using apache web-server.

AddType text/html .php .cgi .pl .fcgi .fpl .phtml .shtml .php2 .php3 .php4 .php5 .asp .jsp


text:
Q: Javascript append tags to selected area I've got the following javascript, which allows me to append certain text to a textarea. However, this only appends to the end of the textarea.
If i have existing text in the textarea and then I click on a certain position in that area, when i click the button i would like the tag to appear where my cursor was placed.
any ideas how I can achieve this?
Thanks
<script type="text/javascript">
function formatText(tag) {
   var Field = document.getElementById('mytextarea');
   var val = Field.value;
   var selected_txt = val.substring(Field.selectionStart, Field.selectionEnd);
   var before_txt = val.substring(0, Field.selectionStart);
   var after_txt = val.substring(Field.selectionEnd, val.length);
   Field.value += '[' + tag + ']' + '[/' + tag + ']';
}
</script>

<form name="my_form">
    <textarea id="mytextarea" style="width:600px;height:200px;"></textarea><br />

    <input type="button" value="Bold" onclick="formatText ('B');" />
    <input type="button" value="Italic" onclick="formatText ('I');" />
    <input type="button" value="Underline" onclick="formatText ('U');" />

</form>

A: You have to concat all the parts
   Field.value =  before_txt + '[' + tag + ']' + selected_txt + '[/' + tag + ']' + after_txt;


text:
Q: How do I translate a list of rendered items with vue-i18n? I'm new to vue.js & vue-i18n and would like to know how to translate a rendered list of items with v-for.
This is for a CakePHP project using vue.js. I've tried referencing the locale inside the data function but this breaks the view.
JS
new Vue({
  i18n,
  el: '#my-form',
  data: {
    myList: [
      {key: 1, title: 'Option 01'},
      {key: 2, title: 'Option 02'},
      {key: 3, title: 'Option 03'}
    ]
  }
})

  {{ $t('label.options') }}

    <button v-for="option in myList">{{ title }}</button>

I need to translate each option listed and replicate for other selects and lists. Any help is much appreciated as I'm unsure how to proceed.

A: Make your myList into a computed property instead and you can utilize the options defined in i18n there by doing title: this.$t(options.1).
https://codepen.io/Hiws/pen/xxKRpJR?editors=1011


text:
Q: What is the physical meaning of multiplication of two wavefunctions? In the amount of quantum mechanics I'vs learnt I understand what wave functions are, how do we extract information from them and so on, and that addition of two wavefunctions on renormalization gives a superposition of the corresponding quantum states.
I was learning the completeness of hermitian operators when I came up with the question as to what does the multiplication of 2 wavefunctions mean physically, if anything at all??
Please note while answering that I still don't completely understand what completeness really means and what is it's significance is although our professor did tell us it will be really useful later .
The equations are as follows :
$\int(\phi_{i}^*) (\phi_j) dx= \delta_{ij}$
$\delta_{ij}=1$ for i=j  ,  $0$  otherwise

A: It looks like you're using asterisks for multiplication, which is not a good idea when writing equations for other humans. In this context, it also creates confusion because it looks like the notation $z^*$ (with a superscripted asterisk) for the complex conjugate of a complex number. In fact, that's particularly relevant here because your equation as written is incorrect. One of the $\phi$'s has to have its complex conjugate taken.
The integral $\int \phi_i^* \phi_j dx$ is called the inner product of the two wavefunctions. It has the interpretation that it measures how similar they are in terms of overlap. For example, if one of the wavefunctions is the wavefunction of an electron that's totally localized within an atom in my house, and another one is for an electron that's totally localized within an atom on the moon, then this integral will be zero because there's no overlap. This tells us that the two states are completely different, and they can be 100% distinguished in a one-shot measurement.
As a geometrical analogy, this is all closely analogous to the vector dot product.

A: It doesn't really mean anything physically (as far as I know.)  Rather, it's a mathematical trick that allows us to explicitly figure out how to write any wavefunction $\psi$ as a superposition of some set of eigenstates $\phi_n$.
Specifically, the property of completeness says that any wavefunction $\psi$ can be written as some superposition of the eigenstates:
$$
\psi = \sum_j a_j \phi_j
$$
for some set of complex coefficients $a_j$.  The orthogonality property is then
$$
\int \phi_i^* \phi_j \, dx = \delta_{ij}
$$
(note the complex conjugate, though if the wavefunctions are real you can ignore it.)
These two properties allow us to extract the coefficients $a_i$ for an arbitrary wavefunction $\psi$, as follows:
\begin{align*}
\int \phi_i^* \psi \, dx &=\int \phi_i^* \left[ \sum_j a_j \phi_j \right] \, dx \\
&= \sum_j a_j \left[ \int \phi_i^* \phi_j \, dx \right] \\
&= \sum_j a_j \delta_{ij} \\
&= a_i.
\end{align*}
So if you tell me that the wavefunction at some time is $\psi$, then I can figure out exactly what superposition of the eigenfunctions it is by doing a bunch of integrals.   Knowing the coefficients $a_i$ then allows me to figure out the probabilities and expectation values of measurements, or (if the eigenstates are energy eigenstates) to use the time-independent Schrödinger equation to find how the state $\psi$ evolves in time.


text:
Q: How to remove event listeners while destroying CKEditor I have a ckeditor plugin like this:
CKEDITOR.plugins.add('testplugin', {
        init: function (editor) {
               editor.on('contentDom', function (e) {
                    var body = editor.document.getBody();
                    body.on('mouseup', function (e) {
                       alert('run!!!!');
                     });
                  });
        });
});

It work perfect in CKEDITOR version 3 (iframe base)
But when i upgrade to CKEDITOR version 4 (lastest - contenteditable base),
all event fire multiple times when i destroy then re-init ckeditor.
(using CKEDITOR.instants.testEditor.destroy() and CKEDITOR.replace('testEditor',options);)
i use: removeAllListeners( ) to remove all event listeners to body but no change.
How can i complete destroy CKEDITOR 4 + All event listeners on it?

A: It seems that you use an inline instance, so editor.document is CKEDITOR.document. It means that every single instance shares the same var body = editor.document.getBody();.
To avoid duplicated events as a leftover of attached by "dead editors", you should either listen on editor#destroy and call event#removeListener on every single one, or use editable#attachListener which automates that job for you (jsFiddle):
editor.on( 'contentDom', function() {
    var body = editor.document.getBody();

    // This listener will be deactivated once editor dies.
    editor.editable().attachListener( body, 'mouseup', function() {
        console.log( 'run!!!!' );
    } );
} );


text:
Q: uln2003a: Switching ground of device works, however, optional USB function of device doesn't work correctly I use the uln2003a to switch a device (with use of a MCU) that is capable doing several things, like fm-radio, bluetooth, playing MP3's etc. It also provides an USB function when it is connected to a computer, it provides an usb soundcard and a SD-card interface. The function is only enabled/started when selected on the device.
The switch works okay, however, when connected to a computer the device is recognized but the computer is unable to communicate with the devices. In Windows there is an exclamation mark present with the comment "Device doesn't start, code 10".
When I bypass the uln2003a switch with a wire, connect ground directly so the uln2003a has no function, all of the devices operates just fine. I tried the following experiment:

*

*Start the device,

*Connect point A and B with a wire (see schematic below) to bypass switch,

*Select USB mode and working fine.

As soon as I disconnect this wire (ground still connected via uln2003a), devices starts to malfunction in Windows.

Question:
The uln2003a switch the same ground and I don't understand why USB is not working. Can somebody explain what's going on?

Simple schematic to give some idea what's going on:

ULN2003A datasheet:
http://www.ti.com/lit/ds/symlink/uln2003a.pdf

A: Take a look at the graph "6.14 Typical Characteristics" in the ULN2003 datasheet.
Even with only a small amount of current the output is still at least 0.7V above ground.
That means that your device's USB signalling is all going to be (at best) shifted 0.7V higher than it's supposed to be (could be even worse) - making the USB host in your PC very unhappy.

A: The ULN2003 datasheet says Vce(sat) can be as high as 1.6V which is pretty high for a "low" output. When you shorted the connection with the wire you got 0V which is why it worked. The ULN2003 isn't really useful for this application because it can never pull the output low enough.
What you are doing is "low side switching" -- for USB I would recommend high side switching and put a Texas Instruments TPS2051B power switch between +5V from USB and your device's +5V input. Then connect the device to ground like normal.
http://www.ti.com/product/TPS2051B
The TPS2051 has a simple interface; there's an enable pin and a fault status indicator. It's easy to use and can handle up to 500mA for your device you are switching.

A: Good answers here already, but I feel it important to add ground side switching of devices is generally a bad idea.
We spend a lot of time ensuring the integrity of the grounding system to minimize noise in systems, ensure proper return current management, and to maintain as close to a constant reference voltage across the circuit/system as we can achieve. (The latter being the issue that stopped you!)
Adding a switch in the ground side negates all that and adds all kinds of hard to debug issues. As such, it should be avoided wherever possible.
Furthermore, when you switch the ground side you leave the device hot.
Internally it is still connected to whatever rail it is attached to. That means the output pins will tend to pull or drive whatever they are attached to up to the rail. Even input pins can do some strange and unpredicted things with the ground disconnected.
Having the device not directly connected to a power source is safer.
Of course, having a device in circuit with Vcc disconnected can also be problematic. The device can actually take power from the input pins via the protection devices if whatever is connected to them can supply enough current.
As such, depowering devices takes some careful design and is often not a trivial matter.

A: When you have a Darlington output stage you can expect significant volt drops: -

To turn on Q2 you need about 0.7 volts applied to its base with respect to the emitter. Given that the base voltage is supplied via Q1 and Q1 sources this voltage from Q2's collector you cannot realistically have the output falling below 0.7 volts unless you have a very light load on the output.


text:
Q: Protractor: Two drop down menus on the same page, can only successfully select element from one dropdown menu I'm using Protractor to run an automated script, on one of the pages there are two drop down menus that are located below/above each other. The two of them seem identical only that they have different ng-model names etc. I can sucessfully select an element from one of the drop down menus but I can't for the other. It's kind of wrecking my head as to why one works and the other doesn't. Here is the code for the drop down menu where I can select an element

<select class="form-control ng-pristine ng-invalid ng-invalid-required" ng-model="user.sourceOfFunds" required="" ng-class="{submitted:invalid}">
                <option value="">Select</option>
                <option value="Savings">Deposit</option>
                <option value="Inherited">Current</option>
                <option value="Other">Savings</option>
                        </select>

element(by.model('user.sourceOfFunds')).sendKeys('Savings');

My other dropdown menu is as follows:

<select class="form-control ng-pristine ng-invalid ng-invalid-required" ng-model="user.investFigure" required="" ng-class="{submitted:invalid}">
                         <option value="">Select</option>
                         <option value="<20">Less than 20K</option>
                         <option value="20-50">20K-50K</option>
                         <option value="50-100">50K-100K</option>
                         </select>

element(by.model('user.investFigure')).sendKeys('Less than 20K');
or
element(by.model('user.investFigure')).sendKeys('20');

I get "element not found" when I try to select an item from the second drop down menu. I'm at a bit of a loss as to why this is happening

A: Using sendKeys to select a dropdown option seems odd to me, even if it works. Given @alecxe's fine suggestions, perhaps the issue is visibility, but try another way and see if sendKeys is your issue.
I use this code on tests with multiple selects every day without issue. Maybe it'll work for you...
var selectOptionByText = function(text) {
    return element(by.cssContainingText('option', text)).click();
};

Call thusly...
selectOptionByText('Less than 20');
selectOptionByText('20');


text:
Q: xAuth Objective-C implementation on Foursquare nHi,
I am trying to create an iPhone app that uses xAuth to connect to Foursquare. Does anybody have any examples they can direct me to?
I know there are a lot of twitter implementations of xAuth out there, but I'm having trouble adapting them to foursquare.
If you have an OAuth implementation, instead, that would be great too.
Thank you.

A: Found a good example: https://github.com/anka/bw_examples/tree/master/FoursquareIntegration