问:
can chisel translates firrtl to verilog in parallel/multi cpu?
I designed in chisel a mesh-array of registers, say 32x32 Bytes of D-flipflop, to take a try to implement such parrallel hardware arch in chisel. The firrtl file is like 100k lines, looks like a netlist. Then the time costed by the translation from firrtl to verilog is like many hours. During this period of time the processing is just arranged on a single CPU.
Could you enlight me how to make it running parallel on CPUs?

The key codes:

```<code>val reg_vec = (0 to 31).map(i=>
                (0 to 31).map(j=>
                  Module(new MyNodeOfReg(8))
  )
)
</code>```

The scala compiler and code runner version 2.11.8

I made a run batch like this, do ./run then wait for ./target/Bench.v:

```<code>mkdir target
cp /opt/eda_tool/RISCV/top.cpp target
scalac -d target -cp $CP Top.scala Test.scala
scala  -cp $CP org.scalatest.run Test
</code>```

in which scalac/scala is auto-generated after scala installation
in which My Test.scala is :

```<code>import chisel3._
import chisel3.util._
import chisel3.testers._
import org.scalatest._
import org.scalacheck._
import org.scalatest.prop._
import scala.sys.process._

class Bench() extends BasicTester {
  val dut = Module(new Top())
  val t = Reg(UInt(width=32),init=0.U)
  t := t+1.U

  when(t<=1.U) {
  }.elsewhen(t===100.U) {
    stop()
  }
}

class Test extends PropSpec with PropertyChecks {

  property("elaborate") {
    Driver.elaborate (() => { new Top() })
  }

  property("should return the correct result") {
    TesterDriver.execute(() => { new Bench() })
  }

}
</code>```

The Top.scala is:

import chisel3._
import chisel3.util._

object ce_pm{
  val div = 4
  val e = 1
  val ec= 1
  val p = 10 // 16/div
  val s = p*p
  val w = s*e

  val ext = 64
  val extw= ext*e

  val irp = 20 // 40/div  // InREG parameter
  val irn = irp*irp // InREG reg number
}

class Mux4(n: Int) extends Module {
  val io = IO(new Bundle{
    val i = Input(Vec(4,UInt(n.W)))
    val s = Input(UInt(2.W))
    val o = Output(UInt(n.W))
  })
  val mux00 = Wire(UInt(n.W))
  val mux01 = Wire(UInt(n.W))
  mux00 := Mux(io.s(0)===1.U,io.i(1),io.i(0))
  mux01 := Mux(io.s(0)===1.U,io.i(3),io.i(2))
  io.o  := Mux(io.s(1)===1.U,mux01,mux00)
}

class CEIO_TwoD_Torus extends Bundle {
  val n = Input(UInt(ce_pm.e.W))
  val s = Input(UInt(ce_pm.e.W))
  val w = Input(UInt(ce_pm.e.W))
  val e = Input(UInt(ce_pm.e.W))
}

class TwoD_TorusReg extends Module {
  val io = IO(new Bundle{
    val i = new CEIO_TwoD_Torus()
    val o = new CEIO_TwoD_Torus().flip
    val d = Input(UInt(ce_pm.e.W))
    val c = Input(Vec(4,UInt(1.W)))
  })
  val r = Reg(UInt(ce_pm.e.W),init=0.U)
  val u_mux4 = Module(new Mux4(ce_pm.e))
  u_mux4.io.i(0) := io.i.e
  u_mux4.io.i(1) := io.i.s
  u_mux4.io.i(2) := io.i.w
  u_mux4.io.i(3) := io.i.n
  u_mux4.io.s    := Cat(io.c(2),io.c(1))
  when (io.c(0) === 1.U) {
    when (io.c(3) === 0.U) {
      r := u_mux4.io.o
    } .otherwise {
      r := io.d
    }
  }
  io.o.e := r
  io.o.s := r
  io.o.w := r
  io.o.n := r
}

class Top extends Module {
  val io = IO(new Bundle{
    val i = Input (UInt(ce_pm.extw.W))
    val o = Output(Vec(ce_pm.p,Vec(ce_pm.p,UInt(ce_pm.e.W))))
    val c = Input (UInt(7.W))
  })
  val n  = ce_pm.irp
  val r_vec = (0 to n-1).map ( i=>
                (0 to n-1).map ( j=>
                  Module(new TwoD_TorusReg)
                )
              )
  for (i <- 0 to n-1) {
    for (j <- 0 to n-1) {
      r_vec(i)(j).io.c(0) := io.c(1)
      r_vec(i)(j).io.c(3) := io.c(0)
      r_vec(i)(j).io.c(2) := io.c(2)
      r_vec(i)(j).io.c(1) := io.c(3)
    }
  }
  // out
  val m = ce_pm.p
  for (i <- 0 to m-1) {
    for (j <- 0 to m-1) {
      io.o(i)(j) := r_vec(i)(j).io.o.e
    }
  }
  //2-D-Torus interconnection
  for (i <- 1 to n-1) {
    for (j <- 1 to n-1) {
      r_vec(i)(j).io.i.w := r_vec(i)(j-1).io.o.e
      r_vec(i)(j).io.i.n := r_vec(i-1)(j).io.o.s
    }
  }
  for (i <- 0 to n-2) {
    for (j <- 0 to n-2) {
      r_vec(i)(j).io.i.e := r_vec(i)(j+1).io.o.w
      r_vec(i)(j).io.i.s := r_vec(i+1)(j).io.o.n
    }
  }
  for (i <- 0 to n-1) {
    r_vec(i)(0).io.i.w := r_vec(i)(n-1).io.o.e
    r_vec(0)(i).io.i.n := r_vec(n-1)(i).io.o.s
  }
}
```

答:
@jkoenig by your suggestion, I found something new.

First, as I had got the Bench.fir, so I direct run firrtl

firrtl -i Bench.fir -o my.v -X verilog

Then the verilog generated in seconds, as fast as you said. Wow~

Second, then I add this code in Top.scala

```<code>package mytest
object GenVlgTop extends App {
  chisel3.Driver.execute(args, () => new Top)
}
</code>```

update run

```<code>scalac -d target -cp $CP Top.scala
scala  -cp $CP mytest.GenVlgTop
</code>```

Then the time ./run to generate firrtl is very long as it was as before

```<code>[info] [0.002] Elaborating design...
[info] [1.290] Done elaborating.
</code>```

the log stops and waits here while firrtl is not generated.

So far a solution is like this:

```<code>1. do the original ./run, when it's waiting,
2. C-c to interrupt the processing
3. firrtl the generated *.fir
</code>```

Body:
I designed in chisel a mesh-array of registers, say 32x32 Bytes of D-flipflop, to take a try to implement such parrallel hardware arch in chisel. The firrtl file is like 100k lines, looks like a netlist. Then the time costed by the translation from firrtl to verilog is like many hours. During this period of time the processing is just arranged on a single CPU.
Could you enlight me how to make it running parallel on CPUs?

The key codes:

val reg_vec = (0 to 31).map(i=>
                (0 to 31).map(j=>
                  Module(new MyNodeOfReg(8))
  )
)

The scala compiler and code runner version 2.11.8

I made a run batch like this, do ./run then wait for ./target/Bench.v:

mkdir target
cp /opt/eda_tool/RISCV/top.cpp target
scalac -d target -cp $CP Top.scala Test.scala
scala  -cp $CP org.scalatest.run Test

in which scalac/scala is auto-generated after scala installation
in which My Test.scala is :

import chisel3._
import chisel3.util._
import chisel3.testers._
import org.scalatest._
import org.scalacheck._
import org.scalatest.prop._
import scala.sys.process._

class Bench() extends BasicTester {
  val dut = Module(new Top())
  val t = Reg(UInt(width=32),init=0.U)
  t := t+1.U

  when(t<=1.U) {
  }.elsewhen(t===100.U) {
    stop()
  }
}

class Test extends PropSpec with PropertyChecks {

  property("elaborate") {
    Driver.elaborate (() => { new Top() })
  }

  property("should return the correct result") {
    TesterDriver.execute(() => { new Bench() })
  }

}

The Top.scala is:

import chisel3._
import chisel3.util._

object ce_pm{
  val div = 4
  val e = 1
  val ec= 1
  val p = 10 // 16/div
  val s = p*p
  val w = s*e

  val ext = 64
  val extw= ext*e

  val irp = 20 // 40/div  // InREG parameter
  val irn = irp*irp // InREG reg number
}

class Mux4(n: Int) extends Module {
  val io = IO(new Bundle{
    val i = Input(Vec(4,UInt(n.W)))
    val s = Input(UInt(2.W))
    val o = Output(UInt(n.W))
  })
  val mux00 = Wire(UInt(n.W))
  val mux01 = Wire(UInt(n.W))
  mux00 := Mux(io.s(0)===1.U,io.i(1),io.i(0))
  mux01 := Mux(io.s(0)===1.U,io.i(3),io.i(2))
  io.o  := Mux(io.s(1)===1.U,mux01,mux00)
}

class CEIO_TwoD_Torus extends Bundle {
  val n = Input(UInt(ce_pm.e.W))
  val s = Input(UInt(ce_pm.e.W))
  val w = Input(UInt(ce_pm.e.W))
  val e = Input(UInt(ce_pm.e.W))
}

class TwoD_TorusReg extends Module {
  val io = IO(new Bundle{
    val i = new CEIO_TwoD_Torus()
    val o = new CEIO_TwoD_Torus().flip
    val d = Input(UInt(ce_pm.e.W))
    val c = Input(Vec(4,UInt(1.W)))
  })
  val r = Reg(UInt(ce_pm.e.W),init=0.U)
  val u_mux4 = Module(new Mux4(ce_pm.e))
  u_mux4.io.i(0) := io.i.e
  u_mux4.io.i(1) := io.i.s
  u_mux4.io.i(2) := io.i.w
  u_mux4.io.i(3) := io.i.n
  u_mux4.io.s    := Cat(io.c(2),io.c(1))
  when (io.c(0) === 1.U) {
    when (io.c(3) === 0.U) {
      r := u_mux4.io.o
    } .otherwise {
      r := io.d
    }
  }
  io.o.e := r
  io.o.s := r
  io.o.w := r
  io.o.n := r
}

class Top extends Module {
  val io = IO(new Bundle{
    val i = Input (UInt(ce_pm.extw.W))
    val o = Output(Vec(ce_pm.p,Vec(ce_pm.p,UInt(ce_pm.e.W))))
    val c = Input (UInt(7.W))
  })
  val n  = ce_pm.irp
  val r_vec = (0 to n-1).map ( i=>
                (0 to n-1).map ( j=>
                  Module(new TwoD_TorusReg)
                )
              )
  for (i <- 0 to n-1) {
    for (j <- 0 to n-1) {
      r_vec(i)(j).io.c(0) := io.c(1)
      r_vec(i)(j).io.c(3) := io.c(0)
      r_vec(i)(j).io.c(2) := io.c(2)
      r_vec(i)(j).io.c(1) := io.c(3)
    }
  }
  // out
  val m = ce_pm.p
  for (i <- 0 to m-1) {
    for (j <- 0 to m-1) {
      io.o(i)(j) := r_vec(i)(j).io.o.e
    }
  }
  //2-D-Torus interconnection
  for (i <- 1 to n-1) {
    for (j <- 1 to n-1) {
      r_vec(i)(j).io.i.w := r_vec(i)(j-1).io.o.e
      r_vec(i)(j).io.i.n := r_vec(i-1)(j).io.o.s
    }
  }
  for (i <- 0 to n-2) {
    for (j <- 0 to n-2) {
      r_vec(i)(j).io.i.e := r_vec(i)(j+1).io.o.w
      r_vec(i)(j).io.i.s := r_vec(i+1)(j).io.o.n
    }
  }
  for (i <- 0 to n-1) {
    r_vec(i)(0).io.i.w := r_vec(i)(n-1).io.o.e
    r_vec(0)(i).io.i.n := r_vec(n-1)(i).io.o.s
  }
}

Body:
@jkoenig by your suggestion, I found something new.

First, as I had got the Bench.fir, so I direct run firrtl

firrtl -i Bench.fir -o my.v -X verilog

Then the verilog generated in seconds, as fast as you said. Wow~

Second, then I add this code in Top.scala

package mytest
object GenVlgTop extends App {
  chisel3.Driver.execute(args, () => new Top)
}

update run

scalac -d target -cp $CP Top.scala
scala  -cp $CP mytest.GenVlgTop

Then the time ./run to generate firrtl is very long as it was as before

[info] [0.002] Elaborating design...
[info] [1.290] Done elaborating.

the log stops and waits here while firrtl is not generated.

So far a solution is like this:

1. do the original ./run, when it's waiting,
2. C-c to interrupt the processing
3. firrtl the generated *.fir


来源: stackexchange

问:
how get current text size in css
I'm tring to write a css that for all string that I can put on increase these strings about 3px. I don't know how can I do this, I think something like this:

```<code>.increaseSize {
getSize()+3px;
}
</code>```

Anyone can help me?

答:
I would seek a different and much simpler approach.

p.myText {
  font-size: 16px;
}

.increaseSize {
  font-size: 1.5em
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p class="myText">This is some standard text and <span class="increaseSize">this is a bigger font size text</span></p></code>```

This would make any .increaseSize element font size 50% bigger than its parent.

You can use calc() but maybe browser compatibility is a problem. This is a safer solution.

Does this help you?

ContentLicense: CC BY-SA 3.0

Title: how get current text size in css

Body:
I'm tring to write a css that for all string that I can put on increase these strings about 3px. I don't know how can I do this, I think something like this:

.increaseSize {
getSize()+3px;
}

Anyone can help me?

Body:
I would seek a different and much simpler approach.

p.myText {
  font-size: 16px;
}

.increaseSize {
  font-size: 1.5em
}

<p class="myText">This is some standard text and <span class="increaseSize">this is a bigger font size text</span></p>

This would make any .increaseSize element font size 50% bigger than its parent.

You can use calc() but maybe browser compatibility is a problem. This is a safer solution.

Does this help you?


问:
How can I add user input to a checklist, but then place it in a label?
I would like to add user input to a list, which contains a label, which contains an input of type "checkbox"?

I have seen other questions, and used their code, but they don't work. Nothing happens when I click "Add".

Here is the JavaScript I found on W3Schools and in a similar question to my own, as well as the W3Schools link:

https://www.w3schools.com/jsref/met_node_insertbefore.asp

```<code>function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);
}
</code>```

I think I understand that using this code I am not going to be able to place the user input inside of the input tag, followed by the label, so I would like to know if there is a way to do that.

Here is my JavaScript if you would like to see it:

```<code>function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);

    var list = document.getElementById("cntr_List");
    list.insertBefore(li, list.childNodes[0]);
}
</code>```

Here is the list itself (HTML of course) along with the input for text:

```<code><div class="center" id="cntr">
    <div class="header">
        <h2>Add an item</h2>
        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            <span onclick="addToList()" style="cursor: pointer;" id="addBtn" >Add</span>
        </div>
        <ol style="list-style-type:none" id="cntr_list">
            <li><label onclick="openNav()"><input type="checkbox" value="ON" class="test" /> Item 1</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 2</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 3</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 4</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 5</label></li>
        </ol>
</div>
</code>```

If what I am doing is not feasible or bad HTML/JavaScript, please forgive me, for I am still learning. I am more than open to any suggestions you have that will give me the same or similar results. If there's no way to accomplish what I am attempting to achieve, feel free to say so, and tell me why.

答:
Are you really using jQuery ? try this, just for testing purpose :

$("#cntr_list").append('
<input type="checkbox" value="ON" /> test
');

just tested it, it works : https://jsfiddle.net/ng1unsoh/

Body:
I would like to add user input to a list, which contains a label, which contains an input of type "checkbox"?

I have seen other questions, and used their code, but they don't work. Nothing happens when I click "Add".

Here is the JavaScript I found on W3Schools and in a similar question to my own, as well as the W3Schools link:

https://www.w3schools.com/jsref/met_node_insertbefore.asp

function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);
}

I think I understand that using this code I am not going to be able to place the user input inside of the input tag, followed by the label, so I would like to know if there is a way to do that.

Here is my JavaScript if you would like to see it:

function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);

    var list = document.getElementById("cntr_List");
    list.insertBefore(li, list.childNodes[0]);
}

Here is the list itself (HTML of course) along with the input for text:

Add an item

        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            Add

<input type="checkbox" value="ON" class="test" /> Item 1

<input type="checkbox" value="ON" class="test" /> Item 2

<input type="checkbox" value="ON" class="test" /> Item 3

<input type="checkbox" value="ON" class="test" /> Item 4

<input type="checkbox" value="ON" class="test" /> Item 5

If what I am doing is not feasible or bad HTML/JavaScript, please forgive me, for I am still learning. I am more than open to any suggestions you have that will give me the same or similar results. If there's no way to accomplish what I am attempting to achieve, feel free to say so, and tell me why.

Body:
Are you really using jQuery ? try this, just for testing purpose :

$("#cntr_list").append('<li><label><input type="checkbox" value="ON" /> test </label></li>');

just tested it, it works : https://jsfiddle.net/ng1unsoh/


问:
Error: Module not found AngularJS+NodeJs
I'm trying to "import" a module instaled by npm. The module is "syncfusion-javascript" and it's downloaded and saved in the package.json correctly but when I try to use it with the require command it fails and shows me the next error : ' Error Cannot resolve module 'syncfusion-javascript' in App.js.

Can anyone tell me what I'm doing wrong or what I'm missing ?? Thanks.

答: Kindly try require('syncfusion-javascript/Scripts/ej/web/ej.grid.min.js'); instead of require('syncfusion-javascript'); to overcome the reported issue.</p>


问:
Kubernetes does not delete pods within a deleted deployment
We run a kubernetes cluster on AWS.

When I attemp to delete a Deployment - the replica set gets deleted as well - but the pod is remaining and gets not deleted.

When I redeploy I get a new Deployment, new replica set and a new pod (so there are now 2 available...)

```<code>apiVersion: v1
kind: Service
metadata:
  name: helloworld
  labels:
    app: helloworld
spec:
  ports:
    -
      port: 80
      targetPort: 10000
  selector:
    service: helloworld
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: helloworld
spec:
  replicas: 1
  revisionHistoryLimit: 0
  selector:
    matchLabels:
      service: helloworld
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      labels:
        service: helloworld
    spec:
      containers:
      -
        name: helloworld
        image: 'my.service.io/service/helloworld:latest'
        imagePullPolicy: Always
        ports:
        - containerPort: 10000
        command:
        - node
        args:
        - "app.js"
      imagePullSecrets:
      - name: my-screts
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
</code>```

Why isn't the pod deleted when deployment and replica sets are deleted?

答: Could it be that the pod was not deployed within the Deployment object? Did you, by any chance, manually deployed this Pod? If that is the case, it will not be removed when deleting the Deployment. Could you try to manually delete the Pod and see if the issue persists?</p>

Body:
We run a kubernetes cluster on AWS.

When I attemp to delete a Deployment - the replica set gets deleted as well - but the pod is remaining and gets not deleted.

When I redeploy I get a new Deployment, new replica set and a new pod (so there are now 2 available...)

apiVersion: v1
kind: Service
metadata:
  name: helloworld
  labels:
    app: helloworld
spec:
  ports:
    -
      port: 80
      targetPort: 10000
  selector:
    service: helloworld
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: helloworld
spec:
  replicas: 1
  revisionHistoryLimit: 0
  selector:
    matchLabels:
      service: helloworld
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      labels:
        service: helloworld
    spec:
      containers:
      -
        name: helloworld
        image: 'my.service.io/service/helloworld:latest'
        imagePullPolicy: Always
        ports:
        - containerPort: 10000
        command:
        - node
        args:
        - "app.js"
      imagePullSecrets:
      - name: my-screts
      restartPolicy: Always
      terminationGracePeriodSeconds: 30

Why isn't the pod deleted when deployment and replica sets are deleted?


问:
What is the cost/overhead of defining a type?
Is there any runtime cost or overhead for having defined too many types in C++? For example, is there any difference at all between these two piece of code:

```<code>int main()
{
    int x, y;
    double fx, fy;

    return 0;
}
</code>```

And:

```<code>template<typename T>
struct Point
{
    T x, y;
};

int main()
{
    Point<int> p;
    Point<double> fp;

    return 0;
}
</code>```

Imagine a code which has many templated types, so that at compile time it generates even more concrete types: is it going to have any impact at runtime? My main concern is about static memory consumption.

答:
Simple usually have no cost at all. As mentioned before, there are some that might incur some runtime costa, like vtables or RTTI, but this is not guaranteed when the optimisation kicks in. Such questions are best resolved by actually testing the problem at hand.

Here you can see that your example generates identical code in both cases, even without optimisation.

Body:
Is there any runtime cost or overhead for having defined too many types in C++? For example, is there any difference at all between these two piece of code:

int main()
{
    int x, y;
    double fx, fy;

    return 0;
}

And:

template<typename T>
struct Point
{
    T x, y;
};

int main()
{
    Point<int> p;
    Point<double> fp;

    return 0;
}

Imagine a code which has many templated types, so that at compile time it generates even more concrete types: is it going to have any impact at runtime? My main concern is about static memory consumption.


答: You are trying to select null element on var list = document.getElementById("cntr_List"); cause that should be var list = document.getElementById("cntr_list");

Title: How can I add user input to a checklist, but then place it in a label?


问:
insert at cursor in react
I need to insert text at caret (current cursor position) in the React-controlled textarea (like autocomplete).

For vanilla textarea I used this code:

```<code>insertAtCursor: function (myField, myValue) {
    // IE
    if (document.selection) {
        myField.focus();
        var sel = document.selection.createRange();
        sel.text = myValue;
    }
    // FF
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;  var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
        + myValue + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}
</code>```

but it does not work in React. How can I do it?

答:
In React 15.6.1 best option is something like that:

class CursorForm extends Component {

  constructor(props) {
    super(props);
    this.state = {value: ''};
  }

  handleChange = event => {
    // Custom set cursor on zero text position in input text field
    event.target.selectionStart = 0
    event.target.selectionEnd = 0

    this.setState({value: event.target.value})
  }

  render () {
    return (
      <form>
        <input type="text" value={this.state.value} onChange={this.handleChange} />
      </form>
    )
  }

}
```

You can get full control of cursor position by event.target.selectionStart and event.target.selectionEnd values without any access to real DOM tree.

Title: insert at cursor in react

Body:
I need to insert text at caret (current cursor position) in the React-controlled textarea (like autocomplete).

For vanilla textarea I used this code:

insertAtCursor: function (myField, myValue) {
    // IE
    if (document.selection) {
        myField.focus();
        var sel = document.selection.createRange();
        sel.text = myValue;
    }
    // FF
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;  var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
        + myValue + myField.value.substring(endPos, myField.value.length);
    } else {
        myField.value += myValue;
    }
}

but it does not work in React. How can I do it?

Body:
In React 15.6.1 best option is something like that:

class CursorForm extends Component {

  constructor(props) {
    super(props);
    this.state = {value: ''};
  }

  handleChange = event => {
    // Custom set cursor on zero text position in input text field
    event.target.selectionStart = 0
    event.target.selectionEnd = 0

    this.setState({value: event.target.value})
  }

  render () {
    return (
      <form>
        <input type="text" value={this.state.value} onChange={this.handleChange} />
      </form>
    )
  }

}

You can get full control of cursor position by event.target.selectionStart and event.target.selectionEnd values without any access to real DOM tree.


问:
vue.js How to call a function inside a for loop and pass the current item?
Using vue.js 2, inside a for loop, I need to render a row only if the current iterated item passes some test.

The test is complex so a simple v-if="item.value == x" wont do.

I've written a function named testIssue that accepts the item and returns true or false and tried to use that is av-if like this:

```<code><template v-for="issue in search_results.issues">
  <tr v-if="testIssue(issue)">
     ....
  </tr>
</template>

var releaseApp = new Vue({
  el: '#release-app',
  methods: {
    testIssue: function(issue) {
      console.log(issue);
      console.log('test');
    },
  },
  mounted: function() {},
  data: {
    search_results: {
      issues: []
    },
  }
});
</code>```

However, testIssue is never called.

If I change the line to
, the function is called but then I dont have the issue variable that I need to test.

I also tried

How can I call a function in a v-if declaration inside a for loop and pass the current item?

答:
First of all you can't do v-for on a <template> tag as you can have only one element per template.

You can add a v-if on the same element as v-for, and it just won't render the element that doesn't pass the v-if. If it's a spearate component per row then it's better to do v-for in parent component and pass the issue by props to child component.

Parent:

```<code><child-comp v-for="issue in search_results.issues" v-if="testIssue(issue)">
</child-comp>
</code>```

Child:

```<code><template>
  <tr>
    {{issue}}
  </tr>
</template>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using vue.js 2, inside a for loop, I need to render a row only if the current iterated item passes some test.

The test is complex so a simple v-if="item.value == x" wont do.

I've written a function named testIssue that accepts the item and returns true or false and tried to use that is av-if like this:

<template v-for="issue in search_results.issues">

     ....

</template>

var releaseApp = new Vue({
  el: '#release-app',
  methods: {
    testIssue: function(issue) {
      console.log(issue);
      console.log('test');
    },
  },
  mounted: function() {},
  data: {
    search_results: {
      issues: []
    },
  }
});

However, testIssue is never called.

If I change the line to
, the function is called but then I dont have the issue variable that I need to test.

I also tried

How can I call a function in a v-if declaration inside a for loop and pass the current item?

Body:
First of all you can't do v-for on a <template> tag as you can have only one element per template.

You can add a v-if on the same element as v-for, and it just won't render the element that doesn't pass the v-if. If it's a spearate component per row then it's better to do v-for in parent component and pass the issue by props to child component.

Parent:

<child-comp v-for="issue in search_results.issues" v-if="testIssue(issue)">
</child-comp>

Child:

<template>
  <tr>
    {{issue}}
  </tr>
</template>


问:
Unable to post using weibo Website statuses/share
So I am able to make a post on weibo account using statuses/upload but I am unable to make a post on weibo account using statuses/share.

Both takes access_token, status,pic as mandatory parameter with multipart / form-data.

And I am getting the following error

{"error":"text not find domain!","error_code":10017,"request":"/2/statuses/share.json"}

Now, I narrowed down the source of the exception to status field but I still couldn't solve it:

status field for statuses/share says 用户分享到微博的文本内容，必须做URLencode，内容不超过140个汉字，文本中不能包含“#话题词#”，同时文本中必须包含至少一个第三方分享到微博的网页URL，且该URL只能是该第三方（调用方）绑定域下的URL链接，绑定域在“我的应用 － 应用信息 － 基本应用信息编辑 － 安全域名”里设置。

In english : Users to share text content microblogging, must do URLencode, the content is not more than 140 characters, the text can not contain "# # topic word," while the text must contain at least one third-party web page URL to share micro-blog, and the URL is only URL links under the third party (the caller) binding domain, a binding domain in the "my Apps - application information - basic information editing application - security domain" in the settings.

status field for statuses/upload says 要发布的微博文本内容，必须做URLencode，内容不超过140个汉字。

In English: To publish microblogging text content, must do URLencode, the content is not more than 140 characters.

So, status in statuses/share expects URL, but even though

I am URLencoding it

I have added a domain in security domain secion

I am passing the domain URL in it status.

it still gives me the above error.

So I am assuming status field is looking for some format which I missed. Anyone encountered and fixed such exception?

答:
Update:

I'm now sure that the share API won't work if the domain of the shared URL in the status is not exactly the one set in your App settings.

What's worse, for PC App, you can only set one domain for your App. So if you set it to your "main" domain then you can't share URLs from your subdomain.

However the workaround solution is simple: just share a URL from your "main" domain and redirect it to your subdomain. Say you shared http://subdomain/abc before, then you may share http://maindomain/share/abc, and then redirect the latter to the former. It involves minor changes in your HTTP config. Take apache for example, you can add this line to your "main" server's config:

Redirect "/share" "http://subdomain"

That's it!

I have the same problem. I doubt this is because the URL in your status points to a domain other than the one set in your application settings - it doesn't work even when pointing to a subdomain of your binding domain. I'm communicating with support of Weibo for this and will update the answer when I get feedback, though their support is always slow.

BTW, it seems like Stackoverflow doesn't support pure Chinese answer. Damn it!


问:
Table-like data structure in python
Is there a data-structure in Python that approximate the behavior of a database table?

My data looks like the following:

id | name | description

1  |  test |  this is a test

The closest I can get is to have a list of dictionaries, but I was wondering if there exists a specific data-structure for that purpose (that, for example, supports sorting or add).

答:
Pandas is a python framework, which works with dataframes for data analysis.
Look here:

http://pandas.pydata.org/

Example:

```<code># Import libraries
import pandas as pd
import sys
data = {[name:"test", ...], description:["this is a test", ...]}

df = pd.DataFrame(data)
df
</code>```

Should give this:

```<code>  name description
0 test this is a test
</code>```

Title: Table-like data structure in python

Body:
Pandas is a python framework, which works with dataframes for data analysis.
Look here:

http://pandas.pydata.org/

Example:

# Import libraries
import pandas as pd
import sys
data = {[name:"test", ...], description:["this is a test", ...]}

df = pd.DataFrame(data)
df

Should give this:

  name description
0 test this is a test


问:
Oracle- SQL: combine LEFT and INNER JOIN
I do not know, how to explain better:

I need a view (in a very normalized matter) that expands the IDs to the corresponding names, so that I need to combine f.e. left joins with inner joins in the following matter (see example)

Tables:

```<code>TCUSTOMER
ID|     NAME|   ANIMAL| CAR|    PROFESSION
 1|  Sheldon|         |    |    1
 2|  Leonard|         |   1|    1
 3| Howard  |         |   2|    2
 4| Radshesh|        1|    |    1
 5| Penny   |         |   3|

TANIMAL
ID|     NAME|   TYPE
 1| CINNAMON|   1

TANIMALTYPE
ID| NAME
 1| DOG

ID|     NAME|   TYPE
 1| CAL-0123|   1
 2| CAL-2345|   1
 3| CAL-4567|   2

TCARTYPE
ID| NAME
 1| FORD
 2| BMW

TPROFESSION
1|  PHYSICIAN
2|  ENGINEER
</code>```

and I need a view with the following result:

```<code>VCUSTOMER
ID|    NAME|ANIMALNAME| ANIMALTYPE| CARNAME|CARTYPE|    PROFESSIONNAME
 1| Sheldon|          |           |        |       |    PHYSICIAN
 2| Leonard|          |           |CAL-0123|   FORD|    PHYSICIAN
 3|  Howard|          |           |CAL-2345|   FORD|    ENGINEER
 4|Radshesh|  CINNAMON|        DOG|        |       |    PHYSICIAN
 5|   Penny|          |           |CAL-4567|    BMW|
</code>```

I think I need something like

```<code>SELECT
    C.ID, C.NAME,
    A.NAME, AT.NAME,
    CAR.NAME, CART.NAME,
    P.NAME
FROM TCUSTOMER C
LEFT (JOIN TANIMAL A INNER JOIN TANIMALTYPE AT ON A.TYPE = AT.ID) ON A.ID = C.ANIMAL
LEFT (JOIN TCAR CAR INNER JOIN TCARTYPE CART ON CAR.TYPE = CARTT.ID) ON CAR.ID = C.CAR
LEFT JOIN TPROFESSION P ON P.ID = C.PROFESSION
</code>```

How to do this or what do I need to search for? "oracle nested joins" did not work

Thanks in advance

答:
You're almost doing it right - it's just multiple joins.

Place the JOIN keyword out of brackets:

```<code>SELECT
    C.ID, C.NAME,
    A.NAME, AT.NAME,
    CAR.NAME, CART.NAME,
    P.NAME
FROM TCUSTOMER C
LEFT JOIN (TANIMAL A INNER JOIN TANIMALTYPE AT ON A.TYPE = AT.ID) ON A.ID = C.ANIMAL
LEFT JOIN (TCAR CAR INNER JOIN TCARTYPE CART ON CAR.TYPE = CART.ID) ON CAR.ID = C.CAR
LEFT JOIN TPROFESSION P ON P.ID = C.PROFESSION
</code>```

Note that JOINs are executed from left to right (but brackets before). Therefore is your case, the order of joins will be:

```<code>{[C -> (A <-> AT)] -> (CAR <-> CART)} -> P
</code>```

Where <-> (inner join) means a symmetric relationships (the values will appear only if exist on both of the sides) and -> (left join) means that all of the values from left will appear, while from right - only the matching.

Body:
I do not know, how to explain better:

I need a view (in a very normalized matter) that expands the IDs to the corresponding names, so that I need to combine f.e. left joins with inner joins in the following matter (see example)

Tables:

TCUSTOMER
ID|     NAME|   ANIMAL| CAR|    PROFESSION
 1|  Sheldon|         |    |    1
 2|  Leonard|         |   1|    1
 3| Howard  |         |   2|    2
 4| Radshesh|        1|    |    1
 5| Penny   |         |   3|

TANIMAL
ID|     NAME|   TYPE
 1| CINNAMON|   1

TANIMALTYPE
ID| NAME
 1| DOG

ID|     NAME|   TYPE
 1| CAL-0123|   1
 2| CAL-2345|   1
 3| CAL-4567|   2

TCARTYPE
ID| NAME
 1| FORD
 2| BMW

TPROFESSION
1|  PHYSICIAN
2|  ENGINEER

and I need a view with the following result:

VCUSTOMER
ID|    NAME|ANIMALNAME| ANIMALTYPE| CARNAME|CARTYPE|    PROFESSIONNAME
 1| Sheldon|          |           |        |       |    PHYSICIAN
 2| Leonard|          |           |CAL-0123|   FORD|    PHYSICIAN
 3|  Howard|          |           |CAL-2345|   FORD|    ENGINEER
 4|Radshesh|  CINNAMON|        DOG|        |       |    PHYSICIAN
 5|   Penny|          |           |CAL-4567|    BMW|

I think I need something like

SELECT
    C.ID, C.NAME,
    A.NAME, AT.NAME,
    CAR.NAME, CART.NAME,
    P.NAME
FROM TCUSTOMER C
LEFT (JOIN TANIMAL A INNER JOIN TANIMALTYPE AT ON A.TYPE = AT.ID) ON A.ID = C.ANIMAL
LEFT (JOIN TCAR CAR INNER JOIN TCARTYPE CART ON CAR.TYPE = CARTT.ID) ON CAR.ID = C.CAR
LEFT JOIN TPROFESSION P ON P.ID = C.PROFESSION

How to do this or what do I need to search for? "oracle nested joins" did not work

Thanks in advance

Body:
You're almost doing it right - it's just multiple joins.

Place the JOIN keyword out of brackets:

SELECT
    C.ID, C.NAME,
    A.NAME, AT.NAME,
    CAR.NAME, CART.NAME,
    P.NAME
FROM TCUSTOMER C
LEFT JOIN (TANIMAL A INNER JOIN TANIMALTYPE AT ON A.TYPE = AT.ID) ON A.ID = C.ANIMAL
LEFT JOIN (TCAR CAR INNER JOIN TCARTYPE CART ON CAR.TYPE = CART.ID) ON CAR.ID = C.CAR
LEFT JOIN TPROFESSION P ON P.ID = C.PROFESSION

Note that JOINs are executed from left to right (but brackets before). Therefore is your case, the order of joins will be:

{[C -> (A <-> AT)] -> (CAR <-> CART)} -> P

Where <-> (inner join) means a symmetric relationships (the values will appear only if exist on both of the sides) and -> (left join) means that all of the values from left will appear, while from right - only the matching.


问:
PHP twig conditional filter
Let's say I have something like this:

what I want to do is apply imagine_filter('watermarked') only if article.isWatermarked() equals to true.

Is there any slicke way of doing this? Or I'm stuck with

```<code>{% set src = asset(article.image.path) %}
{% if article.isWatermarked() %}
{% set src = asset(article.image.path) | imagine_filter('watermarked') %}
{% endif %}
<img src='{{ src }}' />
</code>```

答:
This should work

```<code><img src='{{ article.isWatermarked() ? asset(article.image.path) | imagine_filter('watermarked') : asset(article.image.path) }}' />
</code>```

See ternary operator in doc: https://twig.sensiolabs.org/doc/2.x/templates.html#other-operators

Title: PHP twig conditional filter

Body:
Let's say I have something like this:

what I want to do is apply imagine_filter('watermarked') only if article.isWatermarked() equals to true.

Is there any slicke way of doing this? Or I'm stuck with

{% set src = asset(article.image.path) %}
{% if article.isWatermarked() %}
{% set src = asset(article.image.path) | imagine_filter('watermarked') %}
{% endif %}

Body:
This should work

<img src='{{ article.isWatermarked() ? asset(article.image.path) | imagine_filter('watermarked') : asset(article.image.path) }}' />

See ternary operator in doc: https://twig.sensiolabs.org/doc/2.x/templates.html#other-operators


问:
CSS Grid with table like layout?
I'm having a problem with making
 and
 to behave properly when text line breaks within.

I saw some answer here on stackoverflow that you could set display: table on the ul/ol, table-row on the li and table-cell on the li::before element. That works like I want but limits me so I can't set a margin-bottom on the li.

Setting text-indent and negative margin wont work either because the width of the ::before element will differ. E.g if the counter goes to double digits instead of single.

So my question is if it's possible to solve this using the new grid layout? Been tinkering a bit but I haven't been able to keep all the ::before elements the same width without setting a fixed width.

Anyone got any ideas how to solve this?

Edit:
The content is generated from a CMS so I'm limited with using their markup. Which is a regular ul/ol with li tags.

Update

I want the text to align like this which my current code handles well with unordered lists

But when handling ordered lists it gets more complicated because the ::before element that is my bullet and number can differ in with. Eg

Single digits handle okay but when going double digits the number will eventually overflow the text. So I want all the ::before element to have the same width, so the text still aligns correctly. In this case the width should be equal to the largest ::before element (number 10)

Example code

```<code>ol {
  counter-reset: list;

  & li {
    position: relative;
    counter-increment: list;
    padding-left: 18px;

    &::before {
      position: absolute;
      top: 0;
      left: 0;
      margin-right: 8px;
      content: counter(list);
    }
  }
}
</code>```

答:
Is this what you need? If so, you need to transfer to LESS since that doesn't run very well here.

ol {
  counter-reset: list;
  list-style: none;
}
li {
    position: relative;
    counter-increment: list;
    padding-left: 18px;
}
li:before {
      position: absolute;
      top: 0;
      left: -1.5em;
      margin-right: 8px;
      content: counter(list);
      width: 2em;
      text-align: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
</ol></code>```

Title: CSS Grid with table like layout?

Body:
I'm having a problem with making
 and
 to behave properly when text line breaks within.

I saw some answer here on stackoverflow that you could set display: table on the ul/ol, table-row on the li and table-cell on the li::before element. That works like I want but limits me so I can't set a margin-bottom on the li.

Setting text-indent and negative margin wont work either because the width of the ::before element will differ. E.g if the counter goes to double digits instead of single.

So my question is if it's possible to solve this using the new grid layout? Been tinkering a bit but I haven't been able to keep all the ::before elements the same width without setting a fixed width.

Anyone got any ideas how to solve this?

Edit:
The content is generated from a CMS so I'm limited with using their markup. Which is a regular ul/ol with li tags.

Update

I want the text to align like this which my current code handles well with unordered lists

But when handling ordered lists it gets more complicated because the ::before element that is my bullet and number can differ in with. Eg

Single digits handle okay but when going double digits the number will eventually overflow the text. So I want all the ::before element to have the same width, so the text still aligns correctly. In this case the width should be equal to the largest ::before element (number 10)

Example code

ol {
  counter-reset: list;

  & li {
    position: relative;
    counter-increment: list;
    padding-left: 18px;

    &::before {
      position: absolute;
      top: 0;
      left: 0;
      margin-right: 8px;
      content: counter(list);
    }
  }
}

Body:
Is this what you need? If so, you need to transfer to LESS since that doesn't run very well here.

ol {
  counter-reset: list;
  list-style: none;
}
li {
    position: relative;
    counter-increment: list;
    padding-left: 18px;
}
li:before {
      position: absolute;
      top: 0;
      left: -1.5em;
      margin-right: 8px;
      content: counter(list);
      width: 2em;
      text-align: right;
}

<ol>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
<li>Lorem</li>
<li>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec quis condimentum massa.</li>
</ol>


答:
In dictionary you can sort by names and you can also create lists inside dictionaries which can do all the operations you are looking for!! There is also something like Ordered Dictionary which can help you!!
https://docs.python.org/2/library/collections.html</p>

Title: Table-like data structure in python

Body:
Is there a data-structure in Python that approximate the behavior of a database table?

My data looks like the following:

id | name | description

1  |  test |  this is a test

The closest I can get is to have a list of dictionaries, but I was wondering if there exists a specific data-structure for that purpose (that, for example, supports sorting or add).


问:
Google VR Unity Divider, Settings and Back button hiding in v0.9
Does anyone know how to disable the Divider, settings and back button in the latest google vr sdk for unity?

I've tried setting NativeUILayerSupported to false and putting a return in the legacy DrawUILayer but it still shows.

It appears that the older ways of doing it are now fully deprecated.

答:
My Scenario :

Gvr-Ar App with Gvr for just The Gyroscope (Gvr Eyes aint Rendering a thing, using own Cameras)

Commented the Whole Post Renderer Class ( wich also means i dont have lens disortion calculated, and can use the full screen without the lens shape on the cameras)

What worked for me ( using gvr 1.3 ) :

go into the AndroidDevice.cs Script and comment the Following Lines marked with some ###

```<code>// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if UNITY_ANDROID && !UNITY_HAS_GOOGLEVR

using UnityEngine;

/// @cond
namespace Gvr.Internal {
  public class AndroidDevice : GvrDevice {
  //  private const string ActivityListenerClass =                    ######
  //      "com.google.vr.platform.unity.UnityVrActivityListener";     ######

    private static AndroidJavaObject activityListener;

    public override void Init() {
      SetApplicationState();
      base.Init();
      ConnectToActivity();
    }

    protected override void ConnectToActivity() {
      base.ConnectToActivity();
      if (androidActivity != null && activityListener == null) {
  //      activityListener = Create(ActivityListenerClass);            #####
      }
    }

    public override void SetVRModeEnabled(bool enabled) {
      CallObjectMethod(activityListener, "setVRModeEnabled", enabled);
    }

    public override void ShowSettingsDialog() {
   //   CallObjectMethod(activityListener, "launchConfigureActivity"); #####
    }

    public override void OnPause(bool pause) {
      base.OnPause(pause);
      CallObjectMethod(activityListener, "onPause", pause);
    }

    private void SetApplicationState() {
      if (activityListener == null) {
     //   using (var listenerClass = GetClass(ActivityListenerClass)) {  ###
    //      CallStaticMethod(listenerClass, "setUnityApplicationState"); ###
   //     }                                                            #####
      }
    }
  }
}
/// @endcond

#endif  // UNITY_ANDROID && !UNITY_HAS_GOOGLEVR
</code>```

I have a wierd Scenario, so if you have the vr mode enabled and this does not work you could try also commenting the body of the SetVRModeEnabled() Function

Body:
My Scenario :

Gvr-Ar App with Gvr for just The Gyroscope (Gvr Eyes aint Rendering a thing, using own Cameras)

Commented the Whole Post Renderer Class ( wich also means i dont have lens disortion calculated, and can use the full screen without the lens shape on the cameras)

What worked for me ( using gvr 1.3 ) :

go into the AndroidDevice.cs Script and comment the Following Lines marked with some ###

// Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if UNITY_ANDROID && !UNITY_HAS_GOOGLEVR

using UnityEngine;

/// @cond
namespace Gvr.Internal {
  public class AndroidDevice : GvrDevice {
  //  private const string ActivityListenerClass =                    ######
  //      "com.google.vr.platform.unity.UnityVrActivityListener";     ######

    private static AndroidJavaObject activityListener;

    public override void Init() {
      SetApplicationState();
      base.Init();
      ConnectToActivity();
    }

    protected override void ConnectToActivity() {
      base.ConnectToActivity();
      if (androidActivity != null && activityListener == null) {
  //      activityListener = Create(ActivityListenerClass);            #####
      }
    }

    public override void SetVRModeEnabled(bool enabled) {
      CallObjectMethod(activityListener, "setVRModeEnabled", enabled);
    }

    public override void ShowSettingsDialog() {
   //   CallObjectMethod(activityListener, "launchConfigureActivity"); #####
    }

    public override void OnPause(bool pause) {
      base.OnPause(pause);
      CallObjectMethod(activityListener, "onPause", pause);
    }

    private void SetApplicationState() {
      if (activityListener == null) {
     //   using (var listenerClass = GetClass(ActivityListenerClass)) {  ###
    //      CallStaticMethod(listenerClass, "setUnityApplicationState"); ###
   //     }                                                            #####
      }
    }
  }
}
/// @endcond

#endif  // UNITY_ANDROID && !UNITY_HAS_GOOGLEVR

I have a wierd Scenario, so if you have the vr mode enabled and this does not work you could try also commenting the body of the SetVRModeEnabled() Function


答:
You can use Jquery. This is simple way to achieve.Try this one:

$(function(){
$('#addBtn').on('click',function(){
$("#cntr_list").prepend('
<input type="checkbox" value="ON" class="test" />'+$('#userInput').val()+'
');
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="center" id="cntr">
    <div class="header">
        <h2>Add an item</h2>
        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            <span style="cursor: pointer;" id="addBtn" >Add</span>
        </div>
        <ol style="list-style-type:none" id="cntr_list">
            <li><label><input type="checkbox" value="ON" class="test" /> Item 1</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 2</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 3</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 4</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 5</label></li>
        </ol>
</div></code>```

Body:
I would like to add user input to a list, which contains a label, which contains an input of type "checkbox"?

I have seen other questions, and used their code, but they don't work. Nothing happens when I click "Add".

Here is the JavaScript I found on W3Schools and in a similar question to my own, as well as the W3Schools link:

https://www.w3schools.com/jsref/met_node_insertbefore.asp

function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);
}

I think I understand that using this code I am not going to be able to place the user input inside of the input tag, followed by the label, so I would like to know if there is a way to do that.

Here is my JavaScript if you would like to see it:

function addToList() {
    var li = document.createElement("LI");
    var userInput = document.getElementById("userInput").value;
    var text = document.createTextNode(userInput);
    li.appendChild(text);

    var list = document.getElementById("cntr_List");
    list.insertBefore(li, list.childNodes[0]);
}

Here is the list itself (HTML of course) along with the input for text:

Add an item

        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            Add

<input type="checkbox" value="ON" class="test" /> Item 1

<input type="checkbox" value="ON" class="test" /> Item 2

<input type="checkbox" value="ON" class="test" /> Item 3

<input type="checkbox" value="ON" class="test" /> Item 4

<input type="checkbox" value="ON" class="test" /> Item 5

If what I am doing is not feasible or bad HTML/JavaScript, please forgive me, for I am still learning. I am more than open to any suggestions you have that will give me the same or similar results. If there's no way to accomplish what I am attempting to achieve, feel free to say so, and tell me why.

Body:
You can use Jquery. This is simple way to achieve.Try this one:

$(function(){
$('#addBtn').on('click',function(){
$("#cntr_list").prepend('<li><label><input type="checkbox" value="ON" class="test" />'+$('#userInput').val()+'</label></li>');
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="center" id="cntr">
    <div class="header">
        <h2>Add an item</h2>
        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            <span style="cursor: pointer;" id="addBtn" >Add</span>
        </div>
        <ol style="list-style-type:none" id="cntr_list">
            <li><label><input type="checkbox" value="ON" class="test" /> Item 1</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 2</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 3</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 4</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 5</label></li>
        </ol>
</div>


问:
DataContract serializer doesn't work for similar types
I have an application where I need to use the data contract serializer for different, but similar types:

Generic Lists

Generic Collections

Arrays

On request from Scrobi, here's a full model example:

```<code>[DataContract]
public class Model
{
    public Model()
    {
        List = new List<int>(new[] {1, 2, 3});
        Collection = new Collection<int>(new[] {4, 5, 6});
        Array = new[] {7, 8, 9};
    }

    [DataMember]
    public object List { get; set; }

    [DataMember]
    public object Collection { get; set; }

    [DataMember]
    public object Array { get; set; }

    public string SerializeMe()
    {
        var serializer = new DataContractSerializer(typeof(Model), GetKnownTypes());

        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, this); // exception

            return Encoding.UTF8.GetString(stream.GetBuffer());
        }
    }

    public static Type[] GetKnownTypes()
    {
        return new[]
        {
            typeof(List<int>),
            typeof(Collection<int>), // error
            typeof(int[]) // error
        };
    }
}
</code>```

The problem is: I can't add the generic List, Collection and the array at the same time, because all of them use the same data contract.

When I only use one of the collection types, I am unable to serialize the other ones, because they are unknown (the data contract is present, but for the other type). And yes, the fields must be objects to make this work for my case (and in the real application, I cannot add attributes to them).

It is very impractical in the application I write to only use one of the types, as it is a kind of development environment and the developer can choose the type freely.

Is there any workaround against this limitation of the data contract serializer?

Thanks,

答:
I have a partial answer but for some reason when testing the Collection<int> throws an error when deserialising. Maybe you can work with this to find a full solution.

I created a DataContractResolver allowing you to override the xsi:type
There is some documentation here

```<code>public class MyResolver : DataContractResolver
{
    public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
    {
        string name = string.Empty;
        bool isFound = false;
        if (type.Name == "Int32[]")
        {
            name = "IntArray";
            isFound = true;
        }
        if (type.Name.Contains("List") && type.FullName.Contains("Int")) //find List<int>
        {
            name = "IntList";
            isFound = true;
        }
        if (type.Name.Contains("Collection") && type.FullName.Contains("Int")) //find Collection<int>
        {
            name = "IntCollection";
            isFound = true;
        }

        if (isFound)
        {
            XmlDictionary dictionary = new XmlDictionary();
            typeName = dictionary.Add(name);
            typeNamespace = dictionary.Add("http://tempuri.com");
            return true;
        }

        return knownTypeResolver.TryResolveType(type, declaredType, knownTypeResolver, out typeName, out typeNamespace);
    }

    public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
    {
        if (typeName == "IntArray" )
        {
            return typeof(int[]);
        }
        if (typeName == "IntList")
        {
            return typeof(List<int>);
        }
        if (typeName == "IntCollection")
        {
            return typeof(Collection<int>);
        }

        return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null);
    }
}
</code>```

You then don't need your GetKnownTypes() and create the DataContractSerializer like this:

```<code>var serializer = new DataContractSerializer(typeof(Model),null, int.MaxValue, false, false,null, new MyResolver());
</code>```

Hope this somewhat helps.

Body:
I have an application where I need to use the data contract serializer for different, but similar types:

Generic Lists

Generic Collections

Arrays

On request from Scrobi, here's a full model example:

[DataContract]
public class Model
{
    public Model()
    {
        List = new List<int>(new[] {1, 2, 3});
        Collection = new Collection<int>(new[] {4, 5, 6});
        Array = new[] {7, 8, 9};
    }

    [DataMember]
    public object List { get; set; }

    [DataMember]
    public object Collection { get; set; }

    [DataMember]
    public object Array { get; set; }

    public string SerializeMe()
    {
        var serializer = new DataContractSerializer(typeof(Model), GetKnownTypes());

        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, this); // exception

            return Encoding.UTF8.GetString(stream.GetBuffer());
        }
    }

    public static Type[] GetKnownTypes()
    {
        return new[]
        {
            typeof(List<int>),
            typeof(Collection<int>), // error
            typeof(int[]) // error
        };
    }
}

The problem is: I can't add the generic List, Collection and the array at the same time, because all of them use the same data contract.

When I only use one of the collection types, I am unable to serialize the other ones, because they are unknown (the data contract is present, but for the other type). And yes, the fields must be objects to make this work for my case (and in the real application, I cannot add attributes to them).

It is very impractical in the application I write to only use one of the types, as it is a kind of development environment and the developer can choose the type freely.

Is there any workaround against this limitation of the data contract serializer?

Thanks,

Body:
I have a partial answer but for some reason when testing the Collection<int> throws an error when deserialising. Maybe you can work with this to find a full solution.

I created a DataContractResolver allowing you to override the xsi:type
There is some documentation here

public class MyResolver : DataContractResolver
{
    public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace)
    {
        string name = string.Empty;
        bool isFound = false;
        if (type.Name == "Int32[]")
        {
            name = "IntArray";
            isFound = true;
        }
        if (type.Name.Contains("List") && type.FullName.Contains("Int")) //find List<int>
        {
            name = "IntList";
            isFound = true;
        }
        if (type.Name.Contains("Collection") && type.FullName.Contains("Int")) //find Collection<int>
        {
            name = "IntCollection";
            isFound = true;
        }

        if (isFound)
        {
            XmlDictionary dictionary = new XmlDictionary();
            typeName = dictionary.Add(name);
            typeNamespace = dictionary.Add("http://tempuri.com");
            return true;
        }

        return knownTypeResolver.TryResolveType(type, declaredType, knownTypeResolver, out typeName, out typeNamespace);
    }

    public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver)
    {
        if (typeName == "IntArray" )
        {
            return typeof(int[]);
        }
        if (typeName == "IntList")
        {
            return typeof(List<int>);
        }
        if (typeName == "IntCollection")
        {
            return typeof(Collection<int>);
        }

        return knownTypeResolver.ResolveName(typeName, typeNamespace, declaredType, null);
    }
}

You then don't need your GetKnownTypes() and create the DataContractSerializer like this:

var serializer = new DataContractSerializer(typeof(Model),null, int.MaxValue, false, false,null, new MyResolver());

Hope this somewhat helps.


答:
Just a slight modification in your code. You can do this with JS

function addToList() {
    var userInput = document.getElementById("userInput").value;
    var li = document.createElement("LI");
    var textnode = document.createTextNode(userInput);
    var x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    x.setAttribute("value", "ON");
     li.appendChild(x);
    li.appendChild(textnode);

    var list = document.getElementById("cntr_list");
    list.insertBefore(li, list.childNodes[0]);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="center" id="cntr">
    <div class="header">
        <h2>Add an item</h2>
        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            <span onclick="addToList()" style="cursor: pointer;" id="addBtn" >Add</span>
        </div>
        <ol style="list-style-type:none" id="cntr_list">
            <li><label onclick="openNav()"><input type="checkbox" value="ON" class="test" /> Item 1</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 2</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 3</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 4</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 5</label></li>
        </ol>
</div></code>```

Hope this helps

Body:
Just a slight modification in your code. You can do this with JS

function addToList() {
    var userInput = document.getElementById("userInput").value;
    var li = document.createElement("LI");
    var textnode = document.createTextNode(userInput);
    var x = document.createElement("INPUT");
    x.setAttribute("type", "checkbox");
    x.setAttribute("value", "ON");
     li.appendChild(x);
    li.appendChild(textnode);

    var list = document.getElementById("cntr_list");
    list.insertBefore(li, list.childNodes[0]);

}

<div class="center" id="cntr">
    <div class="header">
        <h2>Add an item</h2>
        <input type="text" id="userInput" style="width: 100%;" placeholder = "Add new task...">
            <span onclick="addToList()" style="cursor: pointer;" id="addBtn" >Add</span>
        </div>
        <ol style="list-style-type:none" id="cntr_list">
            <li><label onclick="openNav()"><input type="checkbox" value="ON" class="test" /> Item 1</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 2</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 3</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 4</label></li>
            <li><label><input type="checkbox" value="ON" class="test" /> Item 5</label></li>
        </ol>
</div>

Hope this helps


问:
kotlin lambda expressions as optional parameter
How can I pass lambda expression as optional parameter in Kotlin language

```<code>val max = { a: Int, b: Int ->
  if (a > b)
      a
  else
      b
}
</code>```

I have to pass above thing is like optional parameter

答:
You can use your max function as default

```<code>fun someDefault(f: (a: Int, b: Int) -> Int = max) {
    f(1, 7)
    // do something
}
</code>```

or you can also define a method with lambda as parameter which is optional

```<code>fun someOptional(f: ((a: Int, b: Int) -> Int)? = null) {
    f?.invoke(1, 7)
}
</code>```

In both cases (default and optional) you can specify a lambda for the call or you can just omit it

```<code>fun call() {
    someDefault()
    someDefault { a, b -> a * b}

    someOptional()
    someOptional { a, b -> a * b}
}
</code>```

Body:
How can I pass lambda expression as optional parameter in Kotlin language

val max = { a: Int, b: Int ->
  if (a > b)
      a
  else
      b
}

I have to pass above thing is like optional parameter

Body:
You can use your max function as default

fun someDefault(f: (a: Int, b: Int) -> Int = max) {
    f(1, 7)
    // do something
}

or you can also define a method with lambda as parameter which is optional

fun someOptional(f: ((a: Int, b: Int) -> Int)? = null) {
    f?.invoke(1, 7)
}

In both cases (default and optional) you can specify a lambda for the call or you can just omit it

fun call() {
    someDefault()
    someDefault { a, b -> a * b}

    someOptional()
    someOptional { a, b -> a * b}
}


问:
Custom part of speech tagging with fallback to nltk internal pos
In my business domain the combination of these 2 words: "doorman building" should always be tagged as (doorman: "JJ") (building: "NN").
nltk internal tagger tags it as:

```<code>nltk.pos_tag(["doorman", "building"]) -> [('doorman', 'NN'), ('building', 'NN')]
</code>```

My approach was to create a BigramTagger and to train it with this sentence:

```<code>train_sents = [
    [('doorman', 'JJ'), ('building', 'NN')]
]
</code>```

and to backoff it with nltk internal tagger for all other cases.

```<code>default_tagger = nltk.data.load("../nltk_data/taggers/maxent_treebank_pos_tagger/english.pickle")
bigram_tagger = nltk.BigramTagger(train_sents, backoff=default_tagger)
</code>```

However, when i try to use it like this:

```<code>bigram_tagger.tag(nltk.word_tokenize("Elegant doorman building with gym"))`
</code>```

seems like the BigramTaager was not applied, i get:

```<code>[('Elegant', 'NNP'), ('doorman', 'NN'), ('building', 'NN'), ('with', 'IN'), ('gym', 'NN')]
</code>```

But this does seem to work:

```<code>bigram_tagger.tag(nltk.word_tokenize("doorman building")) -> [('doorman', 'JJ'), ('building', 'NN')]
</code>```

obviously i'm missing something in the way i should use theses components,
what would be a good strategy to have the nltk internal pos tagger but also to "override" it in some specific cases related to a specific business domain?

答:
First of all, grammatically the nltk tagger is correct: "doorman building" is a noun-noun compound. But to answer the technical question, the BigramTagger tags one word at a time, based on prior context. Your custom tagger cannot tag "doorman" when it follows "elegant", so it delegates to the default and you end up with ("doorman", "JJ") before you've gotten to "building".

If you're sure you want to go this route (and my guess is it could do more harm than good), I recommend applying your corrections by post-processing, after the tagger has done its job. Examples like the one you give don't need a full tagger, you can just match the sequence of words and apply substitutions to the tagged version.

Body:
In my business domain the combination of these 2 words: "doorman building" should always be tagged as (doorman: "JJ") (building: "NN").
nltk internal tagger tags it as:

nltk.pos_tag(["doorman", "building"]) -> [('doorman', 'NN'), ('building', 'NN')]

My approach was to create a BigramTagger and to train it with this sentence:

train_sents = [
    [('doorman', 'JJ'), ('building', 'NN')]
]

and to backoff it with nltk internal tagger for all other cases.

default_tagger = nltk.data.load("../nltk_data/taggers/maxent_treebank_pos_tagger/english.pickle")
bigram_tagger = nltk.BigramTagger(train_sents, backoff=default_tagger)

However, when i try to use it like this:

bigram_tagger.tag(nltk.word_tokenize("Elegant doorman building with gym"))`

seems like the BigramTaager was not applied, i get:

[('Elegant', 'NNP'), ('doorman', 'NN'), ('building', 'NN'), ('with', 'IN'), ('gym', 'NN')]

But this does seem to work:

bigram_tagger.tag(nltk.word_tokenize("doorman building")) -> [('doorman', 'JJ'), ('building', 'NN')]

obviously i'm missing something in the way i should use theses components,
what would be a good strategy to have the nltk internal pos tagger but also to "override" it in some specific cases related to a specific business domain?


问:
Computer Vision: Simple Question - what are 'side lobes'?
This is a very trivial question!!

In some computer vision literature, side-lobes are mentioned.. what are they?.... Can't seem to find anywhere that actually says what they are :S.

Thanks :).

答:
Did a quick google search

Byt it seams like the wiki page mentioned i also relevant along with

http://en.wikipedia.org/wiki/Spectral_leakage

I assume its a way of finding noice.

ContentLicense: CC BY-SA 2.5


问:
Convert GENCODE IDs to Ensembl - Ranged SummarizedExperiment
I have an expression set matrix with the rownames being what I think is a GENCODE ID in the format for example
"ENSG00000000003.14"
"ENSG00000000457.13"
"ENSG00000000005.5" and so on.
I would like to convert these to gene_symbol but I am not sure of the best way to do so, especially because of the ".14" or ".13" which I believe is the version. Should I first trim all IDs for what is after the dot and then use biomaRt to convert? if so, what is the most efficient way of doing it? Is there a better way to get to the gene_symbol?

Many thanks for you help

答:
Thanks for the help. My problem was to get rid of the version .XX at the end of each ensembl gene id. I thought there would be a more straight forward way of going from an ensembl gene id that has the version number (gencode basic annotation) to a gene symbol. In the end I did the following and seem to be working:</p>

```<code>df$ensembl_gene_id <- gsub('\\..+$', '', df$ensembl_gene_id)

library(biomaRt)
mart <- useDataset("hsapiens_gene_ensembl", useMart("ensembl"))
genes <- df$ensembl_gene_id
symbol <- getBM(filters = "ensembl_gene_id",
                attributes = c("ensembl_gene_id","hgnc_symbol"),
                values = genes,
                mart = mart)
df <- merge(x = symbol,
              y = df,
              by.x="ensembl_gene_id",
              by.y="ensembl_gene_id")
</code>```

Body:
Thanks for the help. My problem was to get rid of the version .XX at the end of each ensembl gene id. I thought there would be a more straight forward way of going from an ensembl gene id that has the version number (gencode basic annotation) to a gene symbol. In the end I did the following and seem to be working:

df$ensembl_gene_id <- gsub('\\..+$', '', df$ensembl_gene_id)

library(biomaRt)
mart <- useDataset("hsapiens_gene_ensembl", useMart("ensembl"))
genes <- df$ensembl_gene_id
symbol <- getBM(filters = "ensembl_gene_id",
                attributes = c("ensembl_gene_id","hgnc_symbol"),
                values = genes,
                mart = mart)
df <- merge(x = symbol,
              y = df,
              by.x="ensembl_gene_id",
              by.y="ensembl_gene_id")


问:
URL rewriting with htaccess file
I have a URL that looks like:

```<code>domain.com/home/login.php?ref=501201
</code>```

I want to re-write it as

```<code>domain.com/ref/501201
</code>```

Please tell me the .htaccess syntax

```<code>RewriteRule ^ref/([0-9]+)$ /home/login.php?id=$1
</code>```

because this doesn't work

答:
This One is try it.

```<code>RewriteEngine on
RewriteRule ^/?ref/([0-9]+)$ /home/login.php?id=$1
</code>```

It's not tested. i hope is working

Title: URL rewriting with htaccess file

Body:
I have a URL that looks like:

domain.com/home/login.php?ref=501201

I want to re-write it as

domain.com/ref/501201

Please tell me the .htaccess syntax

RewriteRule ^ref/([0-9]+)$ /home/login.php?id=$1

because this doesn't work

Body:
This One is try it.

RewriteEngine on
RewriteRule ^/?ref/([0-9]+)$ /home/login.php?id=$1

It's not tested. i hope is working


问:
how to open a webpage using Jmeter
How to resolve the below error in jmeter
1.) Request to open Google.com

2.)

P.S: I have just started learning jmeter.
Which is the best way to learn it, please advice.

答:
The easiest way of creating a JMeter test is just recording it. JMeter comes with HTTP(S) Test Script Recorder which can be used for building a test plan skeleton via capturing browser requests, check out Apache JMeter proxy Step-by-step for more information.

I would recommend attending JMeter Academy, this way you will be able to quickly ramp-up in JMeter in particular and performance testing in general. Performance Testing Guidance for Web Applications book is also very useful
 for performance testing greenhorns.

In regards to the possible error, I cannot see the details, just a blind shot: are you behind a corporate proxy/firewall? If yes, you will need to "tell" JMeter the details of this proxy so it could access the Internet (same applies to "recording" approach of tests creation), see Using JMeter behind a proxy chapter for the relevant JMeter configuration.

Title: how to open a webpage using Jmeter


问:
deleting multiple numbered folders in the terminal
I have directories numbered from 0-1000, for example. I want to delete the directories within the range 400-699, for example, and all their contents on the terminal. Is there a way to do this without me having to do rm -rf XXX where XXX is the directory number?

I have seen this post link but the numbering system we have is a bit different.

答:
Another solution using Python:

```<code>rm -rf $(python -c "print ' '.join(str(_) for _ in range(400, 700))")
</code>```

Be careful with rm -rf, before executing, verify the command.

```<code>echo $(python -c "print ' '.join(str(_) for _ in range(400, 700))")
</code>```

Body:
Another solution using Python:

rm -rf $(python -c "print ' '.join(str(_) for _ in range(400, 700))")

Be careful with rm -rf, before executing, verify the command.

echo $(python -c "print ' '.join(str(_) for _ in range(400, 700))")


问:
how get current text size in css
I'm tring to write a css that for all string that I can put on increase these strings about 3px. I don't know how can I do this, I think something like this:

```<code>.increaseSize {
getSize()+3px;
}
</code>```

Anyone can help me?

答:
As recomended by W3C

Set Font Size With Em
  To allow users to resize the text (in the browser menu), many developers use em instead of pixels.

The em size unit is recommended by the W3C.

1em is equal to the current font size. The default text size in browsers is > 16px. So, the default size of 1em is 16px.

The size can be calculated from pixels to em using this formula: pixels/16=em

Here are some examples

```<code>h1 {
font-size: 2.5em; /* 40px/16=2.5em */
}

h2 {
font-size: 1.875em; /* 30px/16=1.875em */
}

p {
font-size: 0.875em; /* 14px/16=0.875em */
}
</code>```

Title: how get current text size in css

Body:
I'm tring to write a css that for all string that I can put on increase these strings about 3px. I don't know how can I do this, I think something like this:

.increaseSize {
getSize()+3px;
}

Anyone can help me?

Body:
As recomended by W3C

Set Font Size With Em
  To allow users to resize the text (in the browser menu), many developers use em instead of pixels.

The em size unit is recommended by the W3C.

1em is equal to the current font size. The default text size in browsers is > 16px. So, the default size of 1em is 16px.

The size can be calculated from pixels to em using this formula: pixels/16=em

Here are some examples

h1 {
font-size: 2.5em; /* 40px/16=2.5em */
}

h2 {
font-size: 1.875em; /* 30px/16=1.875em */
}

p {
font-size: 0.875em; /* 14px/16=0.875em */
}


问:
lazy loading nested module and routing
I got problem with routing inside lazy loaded modules.

Here is my "root" routes:

```<code>const routes: Routes = [
  {path: '', redirectTo: 'admin', pathMatch: 'full' },
    {path: 'admin', loadChildren: 'app/admin.module#AdminModule'}
];

@NgModule({
  imports: [
      RouterModule.forRoot(routes)
  ],
  exports: [
      RouterModule
  ]
})
export class MainRoutingModule {}
</code>```

So what I expect from my app, is to redirect empty path to /admin - this works fine, module is loaded.

in AdminModule I got another redirect:

```<code>const routes: Routes = [
    {path: '', component: AdminComponent, children: [
        {path: '', redirectTo: 'app', pathMatch: 'full' },
        {path: 'app', loadChildren: './app/app.module#AppModule', canActivate: [ AuthGuard ] },
        {path: 'login', component: LoginComponent}
    ]},
];

@NgModule({
    imports: [
        RouterModule.forChild(routes),
        AppModule
    ],
    exports: [
        RouterModule
    ]
})
export class AdminRoutingModule {}
</code>```

Here I got two scenarios:

if user is authenticated redirect to app - so the whole path would be /admin/app

otherwise redirect to login - so the whole path should be /admin/login

and finally routing in admin application:

```<code>const routes: Routes = [
  { path: '', component: AppComponent, children: [
    { path: '',  redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent},
  ]}
];
</code>```

And now problems starts. If I will enter my side with url localhost:3000/admin/app/(*) everything works as expected, AuthGuard is invoked, url is ok, in case that user is unauthenticated he gets redirect to login page.

But!: If I will enter localhost:3000 app redirects me to localhost:3000/admin/home (app is missing) and AuthGuard is not invoked. It looks like Angular is ommiting the admin-routing.module and goes directly to the last one.

What is the reason? How can I fix that?

答:
in AdminModule You add canActivate in the default route .</p>

```<code>const routes: Routes = [
    {path: '', component: AdminComponent, children: [
        {path: '', redirectTo: 'app', pathMatch: 'full'  canActivate: [ AuthGuard ]},
        {path: 'app', loadChildren: './app/app.module#AppModule', canActivate: [ AuthGuard ] },
        {path: 'login', component: LoginComponent}
    ]},
];
</code>```

Title: lazy loading nested module and routing

Body:
I got problem with routing inside lazy loaded modules.

Here is my "root" routes:

const routes: Routes = [
  {path: '', redirectTo: 'admin', pathMatch: 'full' },
    {path: 'admin', loadChildren: 'app/admin.module#AdminModule'}
];

@NgModule({
  imports: [
      RouterModule.forRoot(routes)
  ],
  exports: [
      RouterModule
  ]
})
export class MainRoutingModule {}

So what I expect from my app, is to redirect empty path to /admin - this works fine, module is loaded.

in AdminModule I got another redirect:

const routes: Routes = [
    {path: '', component: AdminComponent, children: [
        {path: '', redirectTo: 'app', pathMatch: 'full' },
        {path: 'app', loadChildren: './app/app.module#AppModule', canActivate: [ AuthGuard ] },
        {path: 'login', component: LoginComponent}
    ]},
];

@NgModule({
    imports: [
        RouterModule.forChild(routes),
        AppModule
    ],
    exports: [
        RouterModule
    ]
})
export class AdminRoutingModule {}

Here I got two scenarios:

if user is authenticated redirect to app - so the whole path would be /admin/app

otherwise redirect to login - so the whole path should be /admin/login

and finally routing in admin application:

const routes: Routes = [
  { path: '', component: AppComponent, children: [
    { path: '',  redirectTo: 'home', pathMatch: 'full' },
    { path: 'home', component: HomeComponent},
  ]}
];

And now problems starts. If I will enter my side with url localhost:3000/admin/app/(*) everything works as expected, AuthGuard is invoked, url is ok, in case that user is unauthenticated he gets redirect to login page.

But!: If I will enter localhost:3000 app redirects me to localhost:3000/admin/home (app is missing) and AuthGuard is not invoked. It looks like Angular is ommiting the admin-routing.module and goes directly to the last one.

What is the reason? How can I fix that?

Body:
in AdminModule You add canActivate in the default route .

const routes: Routes = [
    {path: '', component: AdminComponent, children: [
        {path: '', redirectTo: 'app', pathMatch: 'full'  canActivate: [ AuthGuard ]},
        {path: 'app', loadChildren: './app/app.module#AppModule', canActivate: [ AuthGuard ] },
        {path: 'login', component: LoginComponent}
    ]},
];


问:
sockettimeOutexception when app goes in background
I have set an Alarm when app goes background which working fine, but inside the service I have api which is calling every 5 minutes interval for sending location to server, after app goes in background, service works continue but due network my api is not called and getting socckettimeOutException though network is available.</p>

答:
We can handle it by defining a socket timeout(make more timeouts) and later handle it by using a try catch block..</p>

```<code>    serverSocket.setSoTimeout(10000); //set the socket timeout in milliseconds
</code>```

Body:
We can handle it by defining a socket timeout(make more timeouts) and later handle it by using a try catch block..

    serverSocket.setSoTimeout(10000); //set the socket timeout in milliseconds


问:
Date difference in days and compare the result in Python
I want to calculate binary field churn_flag if user churn the game or he/she is still playing.

I have calculated data max date

```<code>max_time = data['time'].max()
</code>```

Result:

```<code>Timestamp('2017-07-12 01:18:50') (future date)
</code>```

I have calculated each user max date:

```<code>data_max_time = pd.DataFrame(data.groupby(['id'])['time'].max()).reset_index()
data_max_time.columns = ['id','user_max_time']
</code>```

Result:

```<code>2017-07-11 10:33:11 dtype:datetime64[ns]
</code>```

I should check if the difference between these two dates longer or shorter than 2 days. I tried to solve it with:

```<code>(np.datetime64(final_data['max_time'],'D')-np.datetime64(final_data['user_max_time'],'D'))< (np.timedelta64(2,'D'))
</code>```

Result:

```<code>ValueError: Could not convert object to NumPy datetime
</code>```

How could I calculate True/False (1/0) field for each user?

Body:
I want to calculate binary field churn_flag if user churn the game or he/she is still playing.

I have calculated data max date

max_time = data['time'].max()

Result:

Timestamp('2017-07-12 01:18:50') (future date)

I have calculated each user max date:

data_max_time = pd.DataFrame(data.groupby(['id'])['time'].max()).reset_index()
data_max_time.columns = ['id','user_max_time']

Result:

2017-07-11 10:33:11 dtype:datetime64[ns]

I should check if the difference between these two dates longer or shorter than 2 days. I tried to solve it with:

(np.datetime64(final_data['max_time'],'D')-np.datetime64(final_data['user_max_time'],'D'))< (np.timedelta64(2,'D'))

Result:

ValueError: Could not convert object to NumPy datetime

How could I calculate True/False (1/0) field for each user?

Body:
I believe is not necessary converting, use pandas only:

rng = pd.date_range('2017-04-03 15:00:07', periods=10, freq='28.5H')
data = pd.DataFrame({'time': rng, 'id': [1,1,2,2,2,5,5,5,1,2]})
print (data)
   id                time
0   1 2017-04-03 15:00:07
1   1 2017-04-04 19:30:07
2   2 2017-04-06 00:00:07
3   2 2017-04-07 04:30:07
4   2 2017-04-08 09:00:07
5   5 2017-04-09 13:30:07
6   5 2017-04-10 18:00:07
7   5 2017-04-11 22:30:07
8   1 2017-04-13 03:00:07
9   2 2017-04-14 07:30:07

max_time = data['time'].max()

data_max_time = data.groupby('id')['time'].max()
#data_max_time.columns = ['id','user_max_time']
print (data_max_time)
id
1   2017-04-13 03:00:07
2   2017-04-14 07:30:07
5   2017-04-11 22:30:07
Name: time, dtype: datetime64[ns]

print (max_time - data_max_time)
id
1   1 days 04:30:00
2   0 days 00:00:00
5   2 days 09:00:00
Name: time, dtype: timedelta64[ns]

df = (max_time - data_max_time < pd.Timedelta(2, unit='D')).reset_index(name='a')
print (df)
   id      a
0   1   True
1   2   True
2   5  False


问:
How to filter multiple data using keywords in VBA?
I want to filter out the unnecessary data with these 3 keywords: Proton, Hyundai, Perodua. But I am getting the "Named argument not found" error after I run this code.

```<code>''Filtering return reason for Sheet1
Rows("1:1").Select
Selection.AutoFilter

Dim rng As Range

Set rng = ActiveSheet.Range("A1:L2671")
FilterField = WorksheetFunction.Match("Car", rng.Rows(1), 0)

'Turn on filter if not already turned on
If ActiveSheet.AutoFilterMode = False Then rng.AutoFilter

'Filter Specific Countries
rng.AutoFilter Field:=FilterField, Criteria1:="=*Proton*" _
    , Operator:=xlOr, Criteria2:="=*Hyundai*" _
    , Operator:=xlOr, Criteria3:="=*Perodua*"
</code>```

The Criteria3 was highlighted after I ran this code. Why can't I insert the 3 criteria onto the filter filed?

Here's the example of my data:

答:
The problem occurs because of using Wildcards. In those cases you can not use more than 2 filter values at the same time.

This doesn't work:

```<code>rng.AutoFilter Field:=FilterField, _
    Criteria1:=Array("*Hyundai*","*Proton*","*Perodua*"), _
    Operator:=xlFilterValues
</code>```

However, you could use pattern matching by first getting your range to be filtered in an array and dynamically create the values to be filtered array.

Good sample code is in this answer

Body:
I want to filter out the unnecessary data with these 3 keywords: Proton, Hyundai, Perodua. But I am getting the "Named argument not found" error after I run this code.

''Filtering return reason for Sheet1
Rows("1:1").Select
Selection.AutoFilter

Dim rng As Range

Set rng = ActiveSheet.Range("A1:L2671")
FilterField = WorksheetFunction.Match("Car", rng.Rows(1), 0)

'Turn on filter if not already turned on
If ActiveSheet.AutoFilterMode = False Then rng.AutoFilter

'Filter Specific Countries
rng.AutoFilter Field:=FilterField, Criteria1:="=*Proton*" _
    , Operator:=xlOr, Criteria2:="=*Hyundai*" _
    , Operator:=xlOr, Criteria3:="=*Perodua*"

The Criteria3 was highlighted after I ran this code. Why can't I insert the 3 criteria onto the filter filed?

Here's the example of my data:

Body:
The problem occurs because of using Wildcards. In those cases you can not use more than 2 filter values at the same time.

This doesn't work:

rng.AutoFilter Field:=FilterField, _
    Criteria1:=Array("*Hyundai*","*Proton*","*Perodua*"), _
    Operator:=xlFilterValues

However, you could use pattern matching by first getting your range to be filtered in an array and dynamically create the values to be filtered array.

Good sample code is in this answer


问:
Table-like data structure in python
Is there a data-structure in Python that approximate the behavior of a database table?

My data looks like the following:

id | name | description

1  |  test |  this is a test

The closest I can get is to have a list of dictionaries, but I was wondering if there exists a specific data-structure for that purpose (that, for example, supports sorting or add).

答:
I have worked on an ordered Python dictionnary. It seems like that's what you're looking for. You can find it here.

It supports :

```<code>get(key)
del(key)
set(key, value)
sort()
contains(key)
reverse()
add(another_dictionary)
</code>```

Title: Table-like data structure in python

Body:
I have worked on an ordered Python dictionnary. It seems like that's what you're looking for. You can find it here.

It supports :

get(key)
del(key)
set(key, value)
sort()
contains(key)
reverse()
add(another_dictionary)


问:
Entity Framework tables not created (Code first)
I tried to use code first for the first time after always having used DBfirst but for some reason it does not create my tables when I run my project and I am clueless what I am missing even after reading many stackoverflow posts.

I have the following code:

Class.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdulySoft.Models
{
    public partial class Class
    {
        public int Id { get; set; }
        public int ClassRoomId { get; set; }
        public string ClassName { get; set; }
        public int MaxStudents { get; set; }

        public virtual Classroom classrooms { get; set; }
    }
}
</code>```

classroom.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdulySoft.Models
{
    public partial class Classroom
    {
        public Classroom()
        {
            this.classes = new HashSet<Class>();
        }
        public int Id { get; set; }
        public string ClassRoomName { get; set; }

        public ICollection<Class> classes { get; set; }
    }
}
</code>```

SchoolContext

```<code>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdulySoft.Models
{
    public class schoolContext : DbContext
    {

        public schoolContext() : base()
        {
        }

        public DbSet<Class> Classes { get; set; }
        public DbSet<Classroom> Classrooms { get; set; }
    }
}
</code>```

Program.cs

```<code>using EdulySoft.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdulySoft
{
    class Program
    {
        static void Main(string[] args)
        {

            using (var ctx = new schoolContext())
            {
                Class stud = new Class() { Id = 1, ClassName = "Loquat", MaxStudents = 12, ClassRoomId = 1 };

                ctx.Classes.Add(stud);
                ctx.SaveChanges();
            }
        }
    }
}
</code>```

App.config

```<code>  <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="EdulySoft.Properties.Settings.schoolContext"
      connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Eduly;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
</code>```

I used an empty console app to start with. Any help will be much appreciated. Cheer!

答:
Check if you are looking at the correct data source in SQL Management Studio. In the connection string it is:

(localdb)\MSSQLLocalDB

.

Body:
I tried to use code first for the first time after always having used DBfirst but for some reason it does not create my tables when I run my project and I am clueless what I am missing even after reading many stackoverflow posts.

I have the following code:

Class.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdulySoft.Models
{
    public partial class Class
    {
        public int Id { get; set; }
        public int ClassRoomId { get; set; }
        public string ClassName { get; set; }
        public int MaxStudents { get; set; }

        public virtual Classroom classrooms { get; set; }
    }
}

classroom.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdulySoft.Models
{
    public partial class Classroom
    {
        public Classroom()
        {
            this.classes = new HashSet<Class>();
        }
        public int Id { get; set; }
        public string ClassRoomName { get; set; }

        public ICollection<Class> classes { get; set; }
    }
}

SchoolContext

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdulySoft.Models
{
    public class schoolContext : DbContext
    {

        public schoolContext() : base()
        {
        }

        public DbSet<Class> Classes { get; set; }
        public DbSet<Classroom> Classrooms { get; set; }
    }
}

Program.cs

using EdulySoft.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EdulySoft
{
    class Program
    {
        static void Main(string[] args)
        {

            using (var ctx = new schoolContext())
            {
                Class stud = new Class() { Id = 1, ClassName = "Loquat", MaxStudents = 12, ClassRoomId = 1 };

                ctx.Classes.Add(stud);
                ctx.SaveChanges();
            }
        }
    }
}

App.config

  <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>

  </configSections>
  <connectionStrings>
    <add name="EdulySoft.Properties.Settings.schoolContext"
      connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Eduly;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

I used an empty console app to start with. Any help will be much appreciated. Cheer!


问:
OpenCV HOG Algorithm in Real Time on Raspberry Pi
I would like to know if it is possible to run the OpenCV HOG Detector using a Raspberry Pi in real time using the Raspberry Pi camera.</p>

答:
I've had openCV running on a PI, using a USB video grabber, as I am using a CCTV camera. I use Python.

It runs fine (for what I want to do), but you need to limit the resolution.

It's slower than a PC (2ghz dual core) but still works.