问:
Split a column into separate columns using regex
I have got a single column that includes the information as follows:

```<code>1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid
</code>```

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

```<code>     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid
</code>```

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

答:
For the updated example and desired result:

library(tidyverse)

df <- data_frame(x = c("x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo",
                       "x=oljhh88999\ty=lop9876666",
                       "x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid"))

df_tidy <- df %>%
    mutate(row = row_number()) %>%
    separate_rows(x, sep = '\t') %>%
    separate(x, c('var', 'val'), sep = '=') %>%
    group_by(row, var) %>%
    mutate(n = row_number()) %>%
    unite(var, var, n, sep = '') %>%
    spread(var, val)

df_tidy
#> # A tibble: 3 x 6
#> # Groups:   row [3]
#>     row         x1         y1         y2                       z1
#> * <int>      <chr>      <chr>      <chr>                    <chr>
#> 1     1 abc1000000 pqr2000000       <NA> olk78fgzu_zuii8999_ikooo
#> 2     2 oljhh88999 lop9876666       <NA>                     <NA>
#> 3     3 frdt876544 ztr6u76532 uzrt899963 wertttts_765342_ioooosww
#> # ... with 1 more variables: z2 <chr>
```

<hr>

<p>For the original example, if you want to capture all your data in a tidy form,</p>

<pre class="lang-r prettyprint-override"><code>library(tidyverse)

df <- data_frame(x = c("xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo",
                       "xid4=oljhh88999\tyid5=lop9876666",
                       "xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid"))

df_tidy <- df %>%
    mutate(row_id = row_number()) %>%
    separate_rows(x, sep = '\t') %>%
    separate(x, c('id', 'value'), extra = 'merge')

df_tidy
#> # A tibble: 9 x 3
#>   row_id    id                                    value
#> *  <int> <chr>                                    <chr>
#> 1      1  xid1                               abc1000000
#> 2      1  yid2                               pqr2000000
#> 3      1  zid3                 olk78fgzu_zuii8999_ikooo
#> 4      2  xid4                               oljhh88999
#> 5      2  yid5                               lop9876666
#> 6      3  xid6                               frdt876544
#> 7      3  yid7                               ztr6u76532
#> 8      3  yid8 uzrt899963tzid8=wertttts_765342_ioooosww
#> 9      3  zid9                tzuuuee_66554422_88uuiiid
</code>```

Add more separate_rows calls if it makes sense to split further by = or _.

Body:
I have got a single column that includes the information as follows:

1 x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo
2 x=oljhh88999\ty=lop9876666
3 x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid

So, none of the id types has a certain number of occurences in a line.
They are all separated by tab.
I am searching for a way to obtain the IDs for each line as separate columns and have found tstrsplit within data.table but cannot figure out how I can use it with multiple split arguments. Any ideas?

Edit: The expected format is:

     x1          x2        y1    y2                          z1                  z2
1  abc1000000   NA pqr2000000    NA         olk78fgzu_zuii8999_ikooo            NA
2  oljhh88999   NA lop9876666    NA                               NA            NA
3  frdt876544   NA ztr6u76532   uzrt899963  wertttts_765342_ioooosww  zuuuee_66554422_88uuiiid

Note that the id's do not include 'id' in their names. So I updated the example accordingly. The id's may appear a number of times in each line. The format given above is just an example to make the question clearer. In reality, the X type of IDs for example, can have 20 occurences in one line. The number of columns for X will be then the maximum number of appearance of this particular type of ID in a line given the whole dataset. The data is pretty large. We are talking about some 30m lines.

Body:
For the updated example and desired result:

library(tidyverse)

df <- data_frame(x = c("x=abc1000000\ty=pqr2000000\tz=olk78fgzu_zuii8999_ikooo",
                       "x=oljhh88999\ty=lop9876666",
                       "x=frdt876544\ty=ztr6u76532\ty=uzrt899963\tz=wertttts_765342_ioooosww\tz=tzuuuee_66554422_88uuiiid"))

df_tidy <- df %>%
    mutate(row = row_number()) %>%
    separate_rows(x, sep = '\t') %>%
    separate(x, c('var', 'val'), sep = '=') %>%
    group_by(row, var) %>%
    mutate(n = row_number()) %>%
    unite(var, var, n, sep = '') %>%
    spread(var, val)

df_tidy
#> # A tibble: 3 x 6
#> # Groups:   row [3]
#>     row         x1         y1         y2                       z1
#> * <int>      <chr>      <chr>      <chr>                    <chr>
#> 1     1 abc1000000 pqr2000000       <NA> olk78fgzu_zuii8999_ikooo
#> 2     2 oljhh88999 lop9876666       <NA>                     <NA>
#> 3     3 frdt876544 ztr6u76532 uzrt899963 wertttts_765342_ioooosww
#> # ... with 1 more variables: z2 <chr>

For the original example, if you want to capture all your data in a tidy form,

library(tidyverse)

df <- data_frame(x = c("xid1=abc1000000\tyid2=pqr2000000\tzid3=olk78fgzu_zuii8999_ikooo",
                       "xid4=oljhh88999\tyid5=lop9876666",
                       "xid6=frdt876544\tyid7=ztr6u76532\tyid8=uzrt899963tzid8=wertttts_765342_ioooosww\tzid9=tzuuuee_66554422_88uuiiid"))

df_tidy <- df %>%
    mutate(row_id = row_number()) %>%
    separate_rows(x, sep = '\t') %>%
    separate(x, c('id', 'value'), extra = 'merge')

df_tidy
#> # A tibble: 9 x 3
#>   row_id    id                                    value
#> *  <int> <chr>                                    <chr>
#> 1      1  xid1                               abc1000000
#> 2      1  yid2                               pqr2000000
#> 3      1  zid3                 olk78fgzu_zuii8999_ikooo
#> 4      2  xid4                               oljhh88999
#> 5      2  yid5                               lop9876666
#> 6      3  xid6                               frdt876544
#> 7      3  yid7                               ztr6u76532
#> 8      3  yid8 uzrt899963tzid8=wertttts_765342_ioooosww
#> 9      3  zid9                tzuuuee_66554422_88uuiiid

Add more separate_rows calls if it makes sense to split further by = or _.


来源: stackexchange

问:
feof() returning true when EOF is not reached
I'm trying to read from a file at a specific offset (simplified version):

```<code>typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);
</code>```

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.

I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.

A simple look in a hex editor shows there are plenty of bytes left.

答: Maybe it's a difference between textual and binary file. If you're on Windows, newlines are CRLF, which is two characters in file, but converted to only one when read. Try using fopen(..., "rb")</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to read from a file at a specific offset (simplified version):

typedef unsigned char u8;
FILE *data_fp = fopen("C:\\some_file.dat", "r");
fseek(data_fp, 0x004d0a68, SEEK_SET); // move filepointer to offset
u8 *data = new u8[0x3F0];
fread(data, 0x3F0, 1, data_fp);
delete[] data;
fclose(data_fp);

The problem becomes, that data will not contain 1008 bytes, but 529 (seems random). When it reaches 529 bytes, calls to feof(data_fp) will start returning true.

I've also tried to read in smaller chunks (8 bytes at a time) but it just looks like it's hitting EOF when it's not there yet.

A simple look in a hex editor shows there are plenty of bytes left.


问:
3D Boolean operations with Three CSG
Following the example here:

http://learningthreejs.com/blog/2011/12/10/constructive-solid-geometry-with-csg-js/

And using Three.js with https://github.com/chandlerprall/ThreeCSG, I'm trying to do 3D boolean operations on nodes from the model. Like for example if I have a wall with a window, I want to do invert() on that to get just the window.

I have a function that returns all the vertices of the polygons of a node, here's an example of vertices of an object without holes https://pastebin.com/8dhYzPwE.

I'm using ThreeCSG like this:

```<code>    const geometryThree = new THREE.Geometry();

    geometryThree.vertices.push(
        ...vertices
    );

    const geometryCsg = new ThreeBSP(geometryThree);
</code>```

But that's what I'm getting in geometryCsg:

```<code>"{
    "matrix": {
        "elements": {
            "0": 1,
            "1": 0,
            "2": 0,
            "3": 0,
            "4": 0,
            "5": 1,
            "6": 0,
            "7": 0,
            "8": 0,
            "9": 0,
            "10": 1,
            "11": 0,
            "12": 0,
            "13": 0,
            "14": 0,
            "15": 1
        }
    },
    "tree": {
        "polygons": []
    }
}"
</code>```

I think it's because the geometry.faces.length is 0.

How can I make the vertices array to be a proper Three.Geometry such that the faces won't be empty? Geometry.elementsNeedsUpdate doesn't work...

Is there an example that uses polygons of a shape as an array of Vector3s and transforms that to csg?

答:
I just worked on a demo using THREE csg: the Viewer meshes have an indexed array of vertices so you cannot create a BSP directly out of it. Also my code is using a web worker to process the meshes in order to keep the UI responsive with large models, so I need first to send the mesh data to the worker and reconstruct a simple THREE.Mesh on the worker side, the code looks like below:

```<code>// Sends component geometry to the web worker
postComponent (dbId) {

  const geometry = this.getComponentGeometry(dbId)

  const msg = {
    boundingBox: this.getComponentBoundingBox(dbId),
    matrixWorld: geometry.matrixWorld,
    nbMeshes: geometry.meshes.length,
    msgId: 'MSG_ID_COMPONENT',
    dbId
  }

  geometry.meshes.forEach((mesh, idx) => {

    msg['positions' + idx] = mesh.positions
    msg['indices' + idx] = mesh.indices
    msg['stride' + idx] = mesh.stride
  })

  this.worker.postMessage(msg)
}

// get geometry for all fragments in a component
getComponentGeometry (dbId) {

  const fragIds = Toolkit.getLeafFragIds(
    this.viewer.model, dbId)

  let matrixWorld = null

  const meshes = fragIds.map((fragId) => {

    const renderProxy = this.viewer.impl.getRenderProxy(
      this.viewer.model,
      fragId)

    const geometry = renderProxy.geometry

    const attributes = geometry.attributes

    const positions = geometry.vb
      ? geometry.vb
      : attributes.position.array

    const indices = attributes.index.array || geometry.ib

    const stride = geometry.vb ? geometry.vbstride : 3

    const offsets = geometry.offsets

    matrixWorld = matrixWorld ||
    renderProxy.matrixWorld.elements

    return {
      positions,
      indices,
      offsets,
      stride
    }
  })

  return {
    matrixWorld,
    meshes
  }
}

// On the worker side reconstruct THREE.Mesh
// from received data and create ThreeBSP
function buildComponentMesh (data) {

  const vertexArray = []

  for (let idx=0; idx < data.nbMeshes; ++idx) {

    const meshData = {
      positions: data['positions' + idx],
      indices: data['indices' + idx],
      stride: data['stride' + idx]
    }

    getMeshGeometry (meshData, vertexArray)
  }

  const geometry = new THREE.Geometry()

  for (var i = 0; i < vertexArray.length; i += 3) {

    geometry.vertices.push(vertexArray[i])
    geometry.vertices.push(vertexArray[i + 1])
    geometry.vertices.push(vertexArray[i + 2])

    const face = new THREE.Face3(i, i + 1, i + 2)

    geometry.faces.push(face)
  }

  const matrixWorld = new THREE.Matrix4()

  matrixWorld.fromArray(data.matrixWorld)

  const mesh = new THREE.Mesh(geometry)

  mesh.applyMatrix(matrixWorld)

  mesh.boundingBox = data.boundingBox

  mesh.bsp = new ThreeBSP(mesh)

  mesh.dbId = data.dbId

  return mesh
}

function getMeshGeometry (data, vertexArray) {

  const offsets = [{
    count: data.indices.length,
    index: 0,
    start: 0}
  ]

  for (var oi = 0, ol = offsets.length; oi < ol; ++oi) {

    var start = offsets[oi].start
    var count = offsets[oi].count
    var index = offsets[oi].index

    for (var i = start, il = start + count; i < il; i += 3) {

      const a = index + data.indices[i]
      const b = index + data.indices[i + 1]
      const c = index + data.indices[i + 2]

      const vA = new THREE.Vector3()
      const vB = new THREE.Vector3()
      const vC = new THREE.Vector3()

      vA.fromArray(data.positions, a * data.stride)
      vB.fromArray(data.positions, b * data.stride)
      vC.fromArray(data.positions, c * data.stride)

      vertexArray.push(vA)
      vertexArray.push(vB)
      vertexArray.push(vC)
    }
  }
}
</code>```

The complete code of my sample is there: Wall Analyzer and the live demo there.

ContentLicense: CC BY-SA 3.0

Title: 3D Boolean operations with Three CSG

Body:
Following the example here:

http://learningthreejs.com/blog/2011/12/10/constructive-solid-geometry-with-csg-js/

And using Three.js with https://github.com/chandlerprall/ThreeCSG, I'm trying to do 3D boolean operations on nodes from the model. Like for example if I have a wall with a window, I want to do invert() on that to get just the window.

I have a function that returns all the vertices of the polygons of a node, here's an example of vertices of an object without holes https://pastebin.com/8dhYzPwE.

I'm using ThreeCSG like this:

    const geometryThree = new THREE.Geometry();

    geometryThree.vertices.push(
        ...vertices
    );

    const geometryCsg = new ThreeBSP(geometryThree);

But that's what I'm getting in geometryCsg:

"{
    "matrix": {
        "elements": {
            "0": 1,
            "1": 0,
            "2": 0,
            "3": 0,
            "4": 0,
            "5": 1,
            "6": 0,
            "7": 0,
            "8": 0,
            "9": 0,
            "10": 1,
            "11": 0,
            "12": 0,
            "13": 0,
            "14": 0,
            "15": 1
        }
    },
    "tree": {
        "polygons": []
    }
}"

I think it's because the geometry.faces.length is 0.

How can I make the vertices array to be a proper Three.Geometry such that the faces won't be empty? Geometry.elementsNeedsUpdate doesn't work...

Is there an example that uses polygons of a shape as an array of Vector3s and transforms that to csg?

Body:
I just worked on a demo using THREE csg: the Viewer meshes have an indexed array of vertices so you cannot create a BSP directly out of it. Also my code is using a web worker to process the meshes in order to keep the UI responsive with large models, so I need first to send the mesh data to the worker and reconstruct a simple THREE.Mesh on the worker side, the code looks like below:

// Sends component geometry to the web worker
postComponent (dbId) {

  const geometry = this.getComponentGeometry(dbId)

  const msg = {
    boundingBox: this.getComponentBoundingBox(dbId),
    matrixWorld: geometry.matrixWorld,
    nbMeshes: geometry.meshes.length,
    msgId: 'MSG_ID_COMPONENT',
    dbId
  }

  geometry.meshes.forEach((mesh, idx) => {

    msg['positions' + idx] = mesh.positions
    msg['indices' + idx] = mesh.indices
    msg['stride' + idx] = mesh.stride
  })

  this.worker.postMessage(msg)
}

// get geometry for all fragments in a component
getComponentGeometry (dbId) {

  const fragIds = Toolkit.getLeafFragIds(
    this.viewer.model, dbId)

  let matrixWorld = null

  const meshes = fragIds.map((fragId) => {

    const renderProxy = this.viewer.impl.getRenderProxy(
      this.viewer.model,
      fragId)

    const geometry = renderProxy.geometry

    const attributes = geometry.attributes

    const positions = geometry.vb
      ? geometry.vb
      : attributes.position.array

    const indices = attributes.index.array || geometry.ib

    const stride = geometry.vb ? geometry.vbstride : 3

    const offsets = geometry.offsets

    matrixWorld = matrixWorld ||
    renderProxy.matrixWorld.elements

    return {
      positions,
      indices,
      offsets,
      stride
    }
  })

  return {
    matrixWorld,
    meshes
  }
}

// On the worker side reconstruct THREE.Mesh
// from received data and create ThreeBSP
function buildComponentMesh (data) {

  const vertexArray = []

  for (let idx=0; idx < data.nbMeshes; ++idx) {

    const meshData = {
      positions: data['positions' + idx],
      indices: data['indices' + idx],
      stride: data['stride' + idx]
    }

    getMeshGeometry (meshData, vertexArray)
  }

  const geometry = new THREE.Geometry()

  for (var i = 0; i < vertexArray.length; i += 3) {

    geometry.vertices.push(vertexArray[i])
    geometry.vertices.push(vertexArray[i + 1])
    geometry.vertices.push(vertexArray[i + 2])

    const face = new THREE.Face3(i, i + 1, i + 2)

    geometry.faces.push(face)
  }

  const matrixWorld = new THREE.Matrix4()

  matrixWorld.fromArray(data.matrixWorld)

  const mesh = new THREE.Mesh(geometry)

  mesh.applyMatrix(matrixWorld)

  mesh.boundingBox = data.boundingBox

  mesh.bsp = new ThreeBSP(mesh)

  mesh.dbId = data.dbId

  return mesh
}

function getMeshGeometry (data, vertexArray) {

  const offsets = [{
    count: data.indices.length,
    index: 0,
    start: 0}
  ]

  for (var oi = 0, ol = offsets.length; oi < ol; ++oi) {

    var start = offsets[oi].start
    var count = offsets[oi].count
    var index = offsets[oi].index

    for (var i = start, il = start + count; i < il; i += 3) {

      const a = index + data.indices[i]
      const b = index + data.indices[i + 1]
      const c = index + data.indices[i + 2]

      const vA = new THREE.Vector3()
      const vB = new THREE.Vector3()
      const vC = new THREE.Vector3()

      vA.fromArray(data.positions, a * data.stride)
      vB.fromArray(data.positions, b * data.stride)
      vC.fromArray(data.positions, c * data.stride)

      vertexArray.push(vA)
      vertexArray.push(vB)
      vertexArray.push(vC)
    }
  }
}

The complete code of my sample is there: Wall Analyzer and the live demo there.


问:
How do I persist a MySQL timestamp field as a long (epoch) field in java using JPA?
I have a column in a MySQL table like:

```<code>createdAt timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP`.
</code>```

I want it to be stored in a field like:

```<code>private Long createdAt;
</code>```

How would I do this?

答: Simply use @Temporal(TemporalType.TIMESTAMP) above createdAt

Body:
I have a column in a MySQL table like:

createdAt timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP`.

I want it to be stored in a field like:

private Long createdAt;

How would I do this?


问:
JobScheduler - How do I determine a unique Job ID?
According to the documentation, jobs must have a unique Job ID per uid.

If I use a 3rd party library which also schedules jobs, does this mean I can't use the same Job ID as theirs? If so, how can I avoid these kind of collisions?

答:
If I use a 3rd party library which also schedules jobs, does this mean I can't use the same Job ID as theirs?

Correct.

If so, how can I avoid these kind of collisions?

Ask the developer of the library what job IDs they use, or if those job IDs are configurable somehow.


问:
Kubernetes image configuration in ConfigMap
I have a Backend service which is deployed to Kubernetes.
Whenever I want to deploy I build my docker image, push it to the google docker registry with a tag (e.g. 1.1.0) and update my deployment yaml.

However, updating this file and creating another commit is a PITA. Especially because I have a production and a staging environment (actually 2 namespaces)
I recently found out about ConfigMaps in Kubernetes.

So I would like to know if it is possible to store a value in a ConfigMap with the image tag and use it? I haven't found a way so far.

Are there any good alternatives so I don't have to store the information about the current release in git? What's the best practice here? Using latest tag I guess isn't.

I want to let my CI do the deployment whenever I push to master or development (I use gitlab CI), so any approach that is easy to do on the command line without a lot of sed would be appreciated.

答:
A straightforward solution is to trigger a rolling update of your deployment by using kubectl set image:

```<code>kubectl set image deployment/foobar <container_name>=<new_image:new_tag>
</code>```

and you can use your git commit id as image tag.

Body:
A straightforward solution is to trigger a rolling update of your deployment by using kubectl set image:

kubectl set image deployment/foobar <container_name>=<new_image:new_tag>

and you can use your git commit id as image tag.


问:
How to scale up a model in a training dataset to cover all aspects of training data
I was asked in an interview to solve a use case with the help of machine learning. I have to use a Machine Learning algorithm to identify fraud from transactions. My training dataset has lets say 100,200 transactions, out of which 100,000 are legal transactions and 200 are fraud.

I cannot use the dataset as a whole to make the model because it would be a biased dataset and the model would be a very bad one.

Lets say for example I take a sample of 200 good transactions which represent the dataset well(good transactions), and the 200 fraud ones and make the model using this as the training data.

The question I was asked was that how would I scale up the 200 good transactions to the whole data set of 100,000 good records so that my result can be mapped to all types of transactions. I have never solved this kind of a scenario so I did not know how to approach it.

Any kind of guidance as to how I can go about it would be helpful.

答:
In this problem you want to classify transactions as good or fraud. However your data is really imbalance. In that you will probably be interested by Anomaly detection. I will let you read all the article for more details but I will quote a few parts in my answer.

I think this will convince you that this is what you are looking for to solve this problem:

Is it not just Classification?

The answer is yes if the following three conditions are met.

You have labeled training data Anomalous and normal classes are
  balanced ( say at least 1:5) Data is not autocorrelated. ( That one
  data point does not depend on earlier data points. This often breaks
  in time series data). If all of above is true, we do not need an
  anomaly detection techniques and we can use an algorithm like Random
  Forests or Support Vector Machines (SVM).

However, often it is very hard to find training data, and  even when
  you can find them, most anomalies are 1:1000 to 1:10^6 events where
  classes are not balanced.

Now to answer your question:

Generally, the class imbalance is solved using an ensemble built by
  resampling data many times.  The idea is to first create new datasets
  by taking all anomalous data points and adding a subset of normal data
  points (e.g. as 4 times as anomalous data points). Then a classifier
  is built for each data set using SVM or Random Forest, and those
  classifiers are combined using ensemble learning. This approach has
  worked well and produced very good results.

If the data points are autocorrelated with each other, then simple
  classifiers would not work well. We handle those use cases using time
  series classification techniques or Recurrent Neural networks.

I would also suggest another approach of the problem. In this article the author said:

If you do not have training data, still it is possible to do anomaly
  detection using unsupervised learning and semi-supervised learning.
  However, after building the model, you will have no idea how well it
  is doing as you have nothing to test it against. Hence, the results of
  those methods need to be tested in the field before placing them in
  the critical path.

However you do have a few fraud data to test if your unsupervised algorithm is doing well or not, and if it is doing a good enough job, it can be a first solution that will help gathering more data to train a supervised classifier later.

Note that I am not an expert and this is just what I've come up with after mixing my knowledge and some articles I read recently on the subject.

For more question about machine learning I suggest you to use this stackexchange community

I hope it will help you :)


问:
Accessing MySQL from PHP and another process at the same time
I'm writing a program that runs (24/7) on a Linux server and adds entries to a MySQL database.
The contents of the database are presented on a web interface with PHP and the user should be able to delete entries using the web interface.
Is it possible to access the database from multiple processes at the same time?</p>

答:
Yes multiple users can access the database at the same time.
You should however take care that the data is consistent.
If you create/edit entry with many small sql statements and in the meantime someone useses the web interface this may lead to some errors.
If you have a simple db this should not be a problem, else you should consider using transactions.

http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-transactions.html


问:
Adding a separator (a
 or a row separator) every 3

I'm building a site that get a JSON data and populates the site, so I get an unknown numbers of items, this items are on columns of 3, I would like that after each row to have a a nice looking line.

When it was static content what I did was:

```<code><ul>
  <li></li>
  <li></li>
  <li></li>
  <div class="separator"></div>
  <li></li>
  <li></li>
  <li></li>
  <div class="separator"></div>
</ul>
</code>```

but now that i get the dynamic content i dont know how to manage it.

答:
That's not a valid HTML and the browser will not render it as such. You cannot have a
 as a direct child of
. Not possible. You may try using

 instead.

I would just use this small script to add a new
 after every 3rd child:

$(function () {
  $("li:nth-child(3n)").after("
");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.seperator {
  background: #ccf;
  padding: 1px;
  list-style: none;
}</code>```

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Item 9

Item 10

```

Title: Adding a separator (a <div> or a row separator) every 3 <li>

Body:
I'm building a site that get a JSON data and populates the site, so I get an unknown numbers of items, this items are on columns of 3, I would like that after each row to have a a nice looking line.

When it was static content what I did was:

but now that i get the dynamic content i dont know how to manage it.

Body:
That's not a valid HTML and the browser will not render it as such. You cannot have a <div> as a direct child of <ul>. Not possible. You may try using <li class="separator"></li> instead.

I would just use this small script to add a new <li> after every 3rd child:

$(function () {
  $("li:nth-child(3n)").after("<li class='seperator' />");
});

.seperator {
  background: #ccf;
  padding: 1px;
  list-style: none;
}

<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
  <li>Item 6</li>
  <li>Item 7</li>
  <li>Item 8</li>
  <li>Item 9</li>
  <li>Item 10</li>
</ul>


问:
how can i achieve FibonacciSecret in php
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>
</code>```

Output

```<code>h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-
</code>```

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

答:
Alternatively, you can use recursion to avoid using too many for loops:</p>

```<code>$message = str_replace(" ", "", $message);

for($i = 0; $i < 10; $i++) {
    echo substr($message, getNthValue($i), 1);
    if($i != 9) {
        echo "-";
    }
}

function getNthValue($n) {
    if($n <= 1) {
        return $n;
    }
    if($n > 1) {
        return getNthValue($n-1) + getNthValue($n-2);
    }
}
</code>```

Body:
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>

Output

h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

Body:
Alternatively, you can use recursion to avoid using too many for loops:

$message = str_replace(" ", "", $message);

for($i = 0; $i < 10; $i++) {
    echo substr($message, getNthValue($i), 1);
    if($i != 9) {
        echo "-";
    }
}

function getNthValue($n) {
    if($n <= 1) {
        return $n;
    }
    if($n > 1) {
        return getNthValue($n-1) + getNthValue($n-2);
    }
}


问:
Error installing mysql-python: library not found for -lssl
I'm having trouble installing mysql-python. Created a new virtualenv and when installing mysql-python... here's the error message:

```<code>(env)$ pip install mysql-python
Collecting mysql-python
...

clang -bundle -undefined dynamic_lookup -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk build/temp.macosx-10.12-x86_64-2.7/_mysql.o -L/usr /local/Cellar/mysql/5.7.16/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.12-x86_64-2.7/_mysql.so
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'clang' failed with exit status 1
</code>```

Using homebrew, I have installed:

libressl

openssl

openssl@1.1

mysql

Already tried to brew link but brew refuses to do so.

The OS is MacOS Sierra.

Can anyone help? Thanks!

答:
Worked for me by doing this

```<code>$ brew uninstall mysql
$ brew install mysql-connector-c
$ brew unlink mysql-connector-c
$ brew install mysql
$ pip install mysql-python
</code>```

Which is a slightly altered version of the recipe above (note: pip install at the end!)

Body:
I'm having trouble installing mysql-python. Created a new virtualenv and when installing mysql-python... here's the error message:

(env)$ pip install mysql-python
Collecting mysql-python
...

clang -bundle -undefined dynamic_lookup -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk build/temp.macosx-10.12-x86_64-2.7/_mysql.o -L/usr /local/Cellar/mysql/5.7.16/lib -lmysqlclient -lssl -lcrypto -o build/lib.macosx-10.12-x86_64-2.7/_mysql.so
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command 'clang' failed with exit status 1

Using homebrew, I have installed:

libressl

openssl

openssl@1.1

mysql

Already tried to brew link but brew refuses to do so.

The OS is MacOS Sierra.

Can anyone help? Thanks!

Body:
Worked for me by doing this

$ brew uninstall mysql
$ brew install mysql-connector-c
$ brew unlink mysql-connector-c
$ brew install mysql
$ pip install mysql-python

Which is a slightly altered version of the recipe above (note: pip install at the end!)


问:
It is possible to use properties in a Dictionary in .NET
From a third-party program, I get an list of results, as follows:

```<code>+--------+-----------+-------------+
+  Name  + Property  + Prop. value +
+--------+-----------+-------------+
+ foo    +  prop1    +  value1     +
+--------+-----------+-------------+
+ foo    +  prop2    +  value2     +
+--------+-----------+-------------+
</code>```

There is a dozen property and each of those may or may not exist.

The aim is to create .NET object from these.

Right now, I use LINQ to populate objects (sorry, VB, but it is quite straightforward):

```<code>New myClass With {
.myprop1 = (From o In query.rows where o.name = 'foo' and o.col(1) = 'prop1' select o.col(2)).FirstOrDefault
...
.myprop12 = (From o In query.rows where o.name = 'foo' and o.col(1) = 'prop12' select o.col(2)).FirstOrDefault
</code>```

So I have basically the same line of code 12 times. I would like to simplify it.

I have in mind something like a Dictionary(Property, String), where I could define

```<code>myprop1 <-> prop1
....
myprop12 <-> prop12
</code>```

And then loop over this.
I haven't figured out how to do it. Is this possible? Is there any other way to make this kind of assignements less tedious?

答:
Sorry, but I'm going to have to do this in C#...   (I haven't tested this, but it shouldbe close..)

```<code>myClass  foo = new myClass();

var fields = from o in query.rows
             where o.name == "foo"
             select new {Property=o.col(1), Value = o.col(2) };

foreach(var prop in foo.GetType().GetProperties())
{
      var fld = fields.FirstOrDefault(f=>f.Property == prop.Name);
      if (fld != null)
              prop.SetValue(foo, fld.Value);
}
</code>```

Note, this assumes that the property name is myClass is the same as the field name, which is apparently not the case.  Mapping is best handled by a Dictionary, which you'd probably have to created manually:

```<code>var FieldByProperty = new Dictionary<string, string>();

FieldByProperty .Add["myprop1", "prop1");
FieldByProperty .Add["myprop2", "prop2");
// :

foreach(var prop in foo.GetType().GetProperties())
{
      var fldName = FieldByProperty[prop.Name];
      var fld = fields.FirstOrDefault(f=>f.Property == fldName);
      if (fld != null)
          prop.SetValue(foo, fld.Value);
}
</code>```

Body:
From a third-party program, I get an list of results, as follows:

+--------+-----------+-------------+
+  Name  + Property  + Prop. value +
+--------+-----------+-------------+
+ foo    +  prop1    +  value1     +
+--------+-----------+-------------+
+ foo    +  prop2    +  value2     +
+--------+-----------+-------------+

There is a dozen property and each of those may or may not exist.

The aim is to create .NET object from these.

Right now, I use LINQ to populate objects (sorry, VB, but it is quite straightforward):

New myClass With {
.myprop1 = (From o In query.rows where o.name = 'foo' and o.col(1) = 'prop1' select o.col(2)).FirstOrDefault
...
.myprop12 = (From o In query.rows where o.name = 'foo' and o.col(1) = 'prop12' select o.col(2)).FirstOrDefault

So I have basically the same line of code 12 times. I would like to simplify it.

I have in mind something like a Dictionary(Property, String), where I could define

myprop1 <-> prop1
....
myprop12 <-> prop12

And then loop over this.
I haven't figured out how to do it. Is this possible? Is there any other way to make this kind of assignements less tedious?

Body:
Sorry, but I'm going to have to do this in C#...   (I haven't tested this, but it shouldbe close..)

myClass  foo = new myClass();

var fields = from o in query.rows
             where o.name == "foo"
             select new {Property=o.col(1), Value = o.col(2) };

foreach(var prop in foo.GetType().GetProperties())
{
      var fld = fields.FirstOrDefault(f=>f.Property == prop.Name);
      if (fld != null)
              prop.SetValue(foo, fld.Value);
}

Note, this assumes that the property name is myClass is the same as the field name, which is apparently not the case.  Mapping is best handled by a Dictionary, which you'd probably have to created manually:

var FieldByProperty = new Dictionary<string, string>();

FieldByProperty .Add["myprop1", "prop1");
FieldByProperty .Add["myprop2", "prop2");
// :

foreach(var prop in foo.GetType().GetProperties())
{
      var fldName = FieldByProperty[prop.Name];
      var fld = fields.FirstOrDefault(f=>f.Property == fldName);
      if (fld != null)
          prop.SetValue(foo, fld.Value);
}


问:
Perl CPAN installation - dependency issue
All,

I am getting following dependency issue while installing CPAN for perl,

```<code>>yum install perl-CPAN

---> Package perl-devel.x86_64 4:5.10.1-141.el6 will be installed
--> Processing Dependency: perl = 4:5.10.1-141.el6 for package: 4:perl-devel-5.10.1-141.el6.x86_64
--> Finished Dependency Resolution Error: Package: glibc-devel-2.12-1.166.el6.x86_64 (RHEL6_ISO)
           Requires: glibc = 2.12-1.166.el6
           Installed: glibc-2.12-1.166.el6_7.3.i686 (@RHEL_UPDATES_2015)
               glibc = 2.12-1.166.el6_7.3
           Available: glibc-2.12-1.166.el6.i686 (RHEL6_ISO)
               glibc = 2.12-1.166.el6 Error: Package: perl-ExtUtils-MakeMaker-6.55-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: glibc-headers-2.12-1.166.el6.x86_64 (RHEL6_ISO)
           Requires: glibc = 2.12-1.166.el6
           Installed: glibc-2.12-1.166.el6_7.3.i686 (@RHEL_UPDATES_2015)
               glibc = 2.12-1.166.el6_7.3
           Available: glibc-2.12-1.166.el6.i686 (RHEL6_ISO)
               glibc = 2.12-1.166.el6 Error: Package: 1:perl-Digest-SHA-5.47-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: 1:perl-ExtUtils-ParseXS-2.2003.0-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: perl-Test-Harness-3.17-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: 4:perl-devel-5.10.1-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: perl-CPAN-1.9402-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: db4-devel-4.7.25-19.el6_6.x86_64 (RHEL6_ISO)
           Requires: db4 = 4.7.25-19.el6_6
           Installed: db4-4.7.25-20.el6_7.i686 (@RHEL_UPDATES_2015)
               db4 = 4.7.25-20.el6_7
           Available: db4-4.7.25-19.el6_6.i686 (RHEL6_ISO)
               db4 = 4.7.25-19.el6_6  You could try using --skip-broken to work around the problem
</code>```

How to resolve this. Installed perl version is 5.10 and Linux version is Red Hat Enterprise Linux Server release 6.7 (Santiago)

答:
Check required packages if they are 64-bit; i686=32-bit, x86_64=64-bit.
Though I prefer installing latest perlbrew, not system perl, and then necessary modules through cpan. They may be newer than redhat perl ones.</p>

Body:
All,

I am getting following dependency issue while installing CPAN for perl,

>yum install perl-CPAN

---> Package perl-devel.x86_64 4:5.10.1-141.el6 will be installed
--> Processing Dependency: perl = 4:5.10.1-141.el6 for package: 4:perl-devel-5.10.1-141.el6.x86_64
--> Finished Dependency Resolution Error: Package: glibc-devel-2.12-1.166.el6.x86_64 (RHEL6_ISO)
           Requires: glibc = 2.12-1.166.el6
           Installed: glibc-2.12-1.166.el6_7.3.i686 (@RHEL_UPDATES_2015)
               glibc = 2.12-1.166.el6_7.3
           Available: glibc-2.12-1.166.el6.i686 (RHEL6_ISO)
               glibc = 2.12-1.166.el6 Error: Package: perl-ExtUtils-MakeMaker-6.55-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: glibc-headers-2.12-1.166.el6.x86_64 (RHEL6_ISO)
           Requires: glibc = 2.12-1.166.el6
           Installed: glibc-2.12-1.166.el6_7.3.i686 (@RHEL_UPDATES_2015)
               glibc = 2.12-1.166.el6_7.3
           Available: glibc-2.12-1.166.el6.i686 (RHEL6_ISO)
               glibc = 2.12-1.166.el6 Error: Package: 1:perl-Digest-SHA-5.47-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: 1:perl-ExtUtils-ParseXS-2.2003.0-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: perl-Test-Harness-3.17-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: 4:perl-devel-5.10.1-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: perl-CPAN-1.9402-141.el6.x86_64 (RHEL6_ISO)
           Requires: perl = 4:5.10.1-141.el6
           Installed: 4:perl-5.10.1-141.el6_7.1.x86_64 (@RHEL_UPDATES_2015)
               perl = 4:5.10.1-141.el6_7.1
           Available: 4:perl-5.10.1-141.el6.x86_64 (RHEL6_ISO)
               perl = 4:5.10.1-141.el6 Error: Package: db4-devel-4.7.25-19.el6_6.x86_64 (RHEL6_ISO)
           Requires: db4 = 4.7.25-19.el6_6
           Installed: db4-4.7.25-20.el6_7.i686 (@RHEL_UPDATES_2015)
               db4 = 4.7.25-20.el6_7
           Available: db4-4.7.25-19.el6_6.i686 (RHEL6_ISO)
               db4 = 4.7.25-19.el6_6  You could try using --skip-broken to work around the problem

How to resolve this. Installed perl version is 5.10 and Linux version is Red Hat Enterprise Linux Server release 6.7 (Santiago)


问:
Regex replace name(<keepAnythingHere>) by <kept>.name
I have a hundred lines with code like

```<code>name(budget)
name(order)
...
</code>```

I would like to replace it all and have

```<code>budget.name
order.name
...
</code>```

Anyway to do this?

答:
Use the following regex pattern:

```<code>^([^()]+)\(([^()]+)\)$
</code>```

with substitution:

```<code>$2.$1
</code>```

[^()]+ - matches at least one character except ( and )

https://regex101.com/r/m5lkw6/3

Or if name word is static at the beginning of each line use the following:

```<code>^(name)\(([^()]+)\)$
</code>```

Body:
I have a hundred lines with code like

name(budget)
name(order)
...

I would like to replace it all and have

budget.name
order.name
...

Anyway to do this?

Body:
Use the following regex pattern:

^([^()]+)\(([^()]+)\)$

with substitution:

$2.$1

[^()]+ - matches at least one character except ( and )

https://regex101.com/r/m5lkw6/3

Or if name word is static at the beginning of each line use the following:

^(name)\(([^()]+)\)$


问:
Need some help understanding private / protected / public inheritance
Currently, I am learning OOP, and I've tried many inheritance examples. I just tested this code:

```<code>#include <iostream>
using namespace std;

class B
{
    int a;
protected:
    B(int i=0)
    {
        a=i;
    }

    int get_b()
    {
        return a;
    }
};

class D: private B
{
public:
    D(int x=0): B(x) {}

    int get_a()
    {
        return get_b();
    }
};

int main()
{
    D d(-89);
    cout << d.get_a();
    return 0;
}
</code>```

Why does this work? Why can I use the get_b() function? Why does the constructor B(x) work? Why doesn't it work if I change protected to private then?

Later Edit : By using the protected keyword on the constructor and function get_b() means that derived classes have acces to them if the inheritance is public. However, in this case by using private inheritance I would expect that the constructor and the get_b() function would be inaccesible from class D.

答:
Why can I use the get_b() function?

Because get_b() is protected and can be used by derived class.

Why does the constructor B(x) work?

The same reason, it is protected and accessible by derived class D in this case.

Why doesn't it work if I change protected to private then?

Because private members only accessible by class itself (B in this case) and it's friends, D does not have access to private members of B.

Later Edit : By using the protected keyword on the constructor and function get_b() means that derived classes have acces to them if the inheritance is public.

Bold part in your statement is incorrect. Inheritance specifier says how B members would be accessible in children and users of class D, it does not change access of methods of class D to members of class B.

However, in this case by using private inheritance I would expect that the constructor and the get_b() function would be inaccesible from class D.

Your expectation is wrong. Private inheritance would make members of class B inaccessible in children and users of class D, it does not affect accessibility of members of B for methods of D itself.

Body:
Currently, I am learning OOP, and I've tried many inheritance examples. I just tested this code:

#include <iostream>
using namespace std;

class B
{
    int a;
protected:
    B(int i=0)
    {
        a=i;
    }

    int get_b()
    {
        return a;
    }
};

class D: private B
{
public:
    D(int x=0): B(x) {}

    int get_a()
    {
        return get_b();
    }
};

int main()
{
    D d(-89);
    cout << d.get_a();
    return 0;
}

Why does this work? Why can I use the get_b() function? Why does the constructor B(x) work? Why doesn't it work if I change protected to private then?

Later Edit : By using the protected keyword on the constructor and function get_b() means that derived classes have acces to them if the inheritance is public. However, in this case by using private inheritance I would expect that the constructor and the get_b() function would be inaccesible from class D.


问:
Sampling with Chi2 distribution with degrees of freedom
I am working on statistic field and I am a junior in field as I am a toxicologist.

I would like to ask you how to do this in R.
I want to sample a GSD (Geometric Standard Deviation) value from a modified Chi2 distribution with degrees of freedom (5 here) and this value is calculated with the data GM = 1, GSD = 1.98. I don't know what it does really mean and I don't how to get a distribution with Chi2 in R to have a random value.

答:
In R, you can generate values based on predefined functions using r* command. For Chi^2 function, there's rchisq.

```<code>hist(rchisq(1000, df = 5))
</code>```

Body:
In R, you can generate values based on predefined functions using r* command. For Chi^2 function, there's rchisq.

hist(rchisq(1000, df = 5))


问:
ILI9340/41 cheap 2.4" LCD display SPI - can't read from the controller
In one of my projects I use the cheap 2.4" 320x240 TFT display with a ILI9340/41 controller. It works quite good, taking into consideration the price, and I do not have any problems when I display something. But I can’t read anything. I think that it uses 4 wire SPI

But unfortunately any read attempt is unsuccessful. On the first dummy write, I see some strange activity on the MISO line and MISO is driven high.

```<code>void LCD_SendCommand(SPI_TypeDef * volatile SPIx, int command)
{
    ReSetBit(CS_PORT,CS);
    ReSetBit(DC_PORT,DC);
    while(!(SPIx -> SR & SPI_SR_TXE));
        *(volatile uint8_t *)&SPIx -> DR = (uint8_t)command;
    while(!(SPIx -> SR & SPI_SR_TXE));
    while(SPIx -> SR & SPI_SR_BSY);
    SetBit(CS_PORT,CS);

}

void LCD_SendPar(SPI_TypeDef * volatile SPIx, int par)
{
    ReSetBit(CS_PORT,CS);
    SetBit(DC_PORT,DC);
    *(volatile uint8_t *)&(SPIx -> DR) = (uint8_t)(par);
    while(!(SPIx -> SR & SPI_SR_TXE));
    while(SPIx -> SR & SPI_SR_BSY);
    SetBit(CS_PORT,CS);
}
</code>```

Maybe someone knows where the problem is. I have tried literally everything.

答: I have sorted it out eventually :). For some reason it requires two consecutive software reset commands to start sending data back :), and now it works as expected.</p>

ContentLicense: CC BY-SA 4.0

Body:
In one of my projects I use the cheap 2.4" 320x240 TFT display with a ILI9340/41 controller. It works quite good, taking into consideration the price, and I do not have any problems when I display something. But I can’t read anything. I think that it uses 4 wire SPI

But unfortunately any read attempt is unsuccessful. On the first dummy write, I see some strange activity on the MISO line and MISO is driven high.

void LCD_SendCommand(SPI_TypeDef * volatile SPIx, int command)
{
    ReSetBit(CS_PORT,CS);
    ReSetBit(DC_PORT,DC);
    while(!(SPIx -> SR & SPI_SR_TXE));
        *(volatile uint8_t *)&SPIx -> DR = (uint8_t)command;
    while(!(SPIx -> SR & SPI_SR_TXE));
    while(SPIx -> SR & SPI_SR_BSY);
    SetBit(CS_PORT,CS);

}

void LCD_SendPar(SPI_TypeDef * volatile SPIx, int par)
{
    ReSetBit(CS_PORT,CS);
    SetBit(DC_PORT,DC);
    *(volatile uint8_t *)&(SPIx -> DR) = (uint8_t)(par);
    while(!(SPIx -> SR & SPI_SR_TXE));
    while(SPIx -> SR & SPI_SR_BSY);
    SetBit(CS_PORT,CS);
}

Maybe someone knows where the problem is. I have tried literally everything.


问:
Currency textbox react-native
I'm trying to create a currency input, that starts as something like

```<code>" $00.00"
</code>```

and then when you start typing, it types the cents first, then moves on to the dollars (ie, updates the right side numbers first), e.g

```<code>" $00.50"
</code>```

A reddit user posted this piece of JS code to help me : https://codepen.io/benjaminreid/pen/gRbgxK?editors=0010

```<code>const FormattedInput = class extends React.Component {
  constructor(props) {
    super(props);

    this.amountChanged = this.amountChanged.bind(this);

    this.state = {
      value: 0,
    };
  }

  amountChanged(e) {
    this.setState({
      value: e.target.value,
    });
  }

  formatValue(value) {
    return accounting.formatMoney(parseFloat(value) / 100);
  }

  render() {
    return (
      <div>
        <label for="formatted">Formatted input</label>
        <input
          id="formatted"
          type="text"
          value={this.formatValue(this.state.value)}
        />
        <label for="amount">Actual user input (type in here)</label>
        <input
          id="amount"
          type="text"
          onChange={this.amountChanged}
          value={this.state.value}
        />
      </div>
    );
  }
}

const App = () =>
  <div>
    <FormattedInput/>
  </div>
;

ReactDOM.render(
  <App/>,
  document.querySelector('#app')
);
</code>```

It works great, but the input you enter and the input that gets displayed are in two different boxes. I was wondering if there was a way to type straight into the formatted currency box?

Does anyone have a better solution perhaps? Help would be greatly appreciated.

答:
I tried to code something to solve your problem. It is not so hard to build from scratch.</p>

```<code>const FormattedInput = class extends React.Component {
  constructor(props) {
    super(props);

    this.amountChanged = this.amountChanged.bind(this);

    this.state = {
      value: '',
      rawValue: '',
    };
  }

  amountChanged(e) {
    let tmpAmount = '';
    let tmpValue = e.target.value.slice(-1);
    let newRawValue = this.state.rawValue + tmpValue;

    if ( this.state.value.length > e.target.value.length) {
      this.setState({
        value: '',
        rawValue: '',
      })
    }
    else {
      if (newRawValue.length === 1) {
        tmpAmount = '0.0' + newRawValue;
      }
      else if (newRawValue.length === 2) {
        tmpAmount = '0.' + newRawValue;
      }
      else {
        let intAmount = newRawValue.slice(0, newRawValue.length - 2);
        let centAmount = newRawValue.slice(-2);

        tmpAmount = intAmount.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '.' + centAmount;

      }

      this.setState({
        value: tmpAmount,
        rawValue: newRawValue,
      });

    }
  }

  formatValue(value) {
    return accounting.formatMoney(parseFloat(value) / 100);
  }

  render() {
    return (
      <div>
        <label for="amount">Mix</label>
        <input
          id="amount"
          type="text"
          placeholder="$0.00"
          onChange={this.amountChanged}
          value={this.state.value}
          />
      </div>
    );
  }
}

const App = () =>
<div>
  <FormattedInput/>
</div>
;

ReactDOM.render(
  <App/>,
  document.querySelector('#app')
);
</code>```

Title: Currency textbox react-native

Body:
I'm trying to create a currency input, that starts as something like

" $00.00"

and then when you start typing, it types the cents first, then moves on to the dollars (ie, updates the right side numbers first), e.g

" $00.50"

A reddit user posted this piece of JS code to help me : https://codepen.io/benjaminreid/pen/gRbgxK?editors=0010

const FormattedInput = class extends React.Component {
  constructor(props) {
    super(props);

    this.amountChanged = this.amountChanged.bind(this);

    this.state = {
      value: 0,
    };
  }

  amountChanged(e) {
    this.setState({
      value: e.target.value,
    });
  }

  formatValue(value) {
    return accounting.formatMoney(parseFloat(value) / 100);
  }

  render() {
    return (

        Formatted input
        <input
          id="formatted"
          type="text"
          value={this.formatValue(this.state.value)}
        />
        Actual user input (type in here)
        <input
          id="amount"
          type="text"
          onChange={this.amountChanged}
          value={this.state.value}
        />

    );
  }
}

const App = () =>

    <FormattedInput/>

;

ReactDOM.render(
  <App/>,
  document.querySelector('#app')
);

It works great, but the input you enter and the input that gets displayed are in two different boxes. I was wondering if there was a way to type straight into the formatted currency box?

Does anyone have a better solution perhaps? Help would be greatly appreciated.

Body:
I tried to code something to solve your problem. It is not so hard to build from scratch.

const FormattedInput = class extends React.Component {
  constructor(props) {
    super(props);

    this.amountChanged = this.amountChanged.bind(this);

    this.state = {
      value: '',
      rawValue: '',
    };
  }

  amountChanged(e) {
    let tmpAmount = '';
    let tmpValue = e.target.value.slice(-1);
    let newRawValue = this.state.rawValue + tmpValue;

    if ( this.state.value.length > e.target.value.length) {
      this.setState({
        value: '',
        rawValue: '',
      })
    }
    else {
      if (newRawValue.length === 1) {
        tmpAmount = '0.0' + newRawValue;
      }
      else if (newRawValue.length === 2) {
        tmpAmount = '0.' + newRawValue;
      }
      else {
        let intAmount = newRawValue.slice(0, newRawValue.length - 2);
        let centAmount = newRawValue.slice(-2);

        tmpAmount = intAmount.replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '.' + centAmount;

      }

      this.setState({
        value: tmpAmount,
        rawValue: newRawValue,
      });

    }
  }

  formatValue(value) {
    return accounting.formatMoney(parseFloat(value) / 100);
  }

  render() {
    return (
      <div>
        <label for="amount">Mix</label>
        <input
          id="amount"
          type="text"
          placeholder="$0.00"
          onChange={this.amountChanged}
          value={this.state.value}
          />
      </div>
    );
  }
}

const App = () =>
<div>
  <FormattedInput/>
</div>
;

ReactDOM.render(
  <App/>,
  document.querySelector('#app')
);


问:
Send Mail error 501 - Syntax error in parameters or arguments on server but not on local system
We have a mailing feature in our Wicket 6 Web Application. Recently, I had to change the credentials of the mailing server to a new one. I tested it on my local system (OS Windows, Tomcat 7 web server) and it worked perfectly fine. The mail was send and I received it.
When I applied the same credentials on our web server (OS: Debian) I get the following error message: 501 - Syntax error in parameters or arguments

I checked the mail address multiple times but everything seems to be fine. Thus, I am guessing that maybe the message is blocked somehow on the server either from the tomcat 7, the apache 2 or the hoster (although I called the hoster and they told me that their firewall is not blocking any outgoing signals). However, with the old credentials the mailing service is running perfectly fine. Thus not all outgoing signals are blocked.

I am not very experienced with such server configurations. Can anybody please give me a hint where I have to check the configuration. Thank you for your support.

EDIT

For sending the mail we are using the embedded javamail service of the spring framework. The code looks like this:

```<code>public class PrMailSendServiceImpl implements IPrMailSenderService{
    private JavaMailSenderImpl javaMailSenderService;
    private String defaultEmailFrom = "a@b.com";
    private String defaultEmailTo;
    public void sendEmail(String toEmail, String mailSubject, String mailContent) throws MessagingException {
        MimeMessage msg = javaMailSenderService.createMimeMessage();
        MimeMessageHelper mime = new MimeMessageHelper(msg, true, "UTF-8");
        mime.setText(mailContent, true);
        mime.setSubject(mailSubject);
        mime.setTo(toEmail);
        mime.setFrom(defaultEmailFrom);
        javaMailSenderService.send(msg);
    }
/*getter and setter*/
}
</code>```

The described error occurs while the send method is executed.

The spring-context.xml file contains te following configurations:

```<code><bean id="javaMailSenderService" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="mrvnet.kundenserver.de" />
    <property name="port" value="25" />
    <property name="username" value="my@mail.com" />
    <property name="password" value="myPassword" />

    <property name="javaMailProperties">
       <props>
              <prop key="mail.smtp.auth">true</prop>
              <prop key="mail.smtp.starttls.enable">true</prop>
           </props>
    </property>
</bean>

<bean id="mailSendService"  class="de.virtualsolution.procon.service.impl.PrMailSendServiceImpl">
    <property name="javaMailSenderService"><ref bean="javaMailSenderService" /></property>
    <property name="defaultEmailFrom"><value>my@mailcom</value></property>
</bean>
</code>```

答:
I figured out the problem. I took the answer from https://community.hpe.com/t5/System-Administration/Error-sending-e-mails-from-Java-ehlo-problem/td-p/4145190

Simple Mail Transfer Protocol RFCs stipulate use of HELO and EHLO.
  Invalid usage of HELO/EHLO in the SMTP dialogue is your problem.
  Most Mail Transfer Agents (MTAs)perform DNS
  (A- and PTR- resource records) verification
  on the domain name given on the SMTP HELO
  and EHLO commands. This can violate RFC 2821,
  so email is usually not rejected by default.
  In other words, EHLO and HELO typically
  require FQDN. A client MUST issue HELO or EHLO before
  starting a mail transaction.

SOLUTION (see Unable to send email using javamail api in linux)

On our server we have several sub-domains. Thus, when calling InetAddress.getLocalHost().getHostName() an exception was thrown. Therefore, to manually set the required host name for the HELO I added the line <prop key="mail.smtp.localhost">my.server.host.name</prop> in the spring-context.xml

Now it looks like:

```<code><bean id="javaMailSenderService" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="mrvnet.kundenserver.de" />
    <property name="port" value="25" />
    <property name="username" value="my@mail.com" />
    <property name="password" value="myPassword" />

    <property name="javaMailProperties">
       <props>
              <prop key="mail.smtp.auth">true</prop>
              <prop key="mail.smtp.starttls.enable">true</prop>
              <prop key="mail.smtp.localhost">my.server.host.name</prop>
           </props>
    </property>
</bean>

<bean id="mailSendService"  class="de.virtualsolution.procon.service.impl.PrMailSendServiceImpl">
    <property name="javaMailSenderService"><ref bean="javaMailSenderService" /></property>
    <property name="defaultEmailFrom"><value>my@mailcom</value></property>
</bean>
</code>```

Body:
We have a mailing feature in our Wicket 6 Web Application. Recently, I had to change the credentials of the mailing server to a new one. I tested it on my local system (OS Windows, Tomcat 7 web server) and it worked perfectly fine. The mail was send and I received it.
When I applied the same credentials on our web server (OS: Debian) I get the following error message: 501 - Syntax error in parameters or arguments

I checked the mail address multiple times but everything seems to be fine. Thus, I am guessing that maybe the message is blocked somehow on the server either from the tomcat 7, the apache 2 or the hoster (although I called the hoster and they told me that their firewall is not blocking any outgoing signals). However, with the old credentials the mailing service is running perfectly fine. Thus not all outgoing signals are blocked.

I am not very experienced with such server configurations. Can anybody please give me a hint where I have to check the configuration. Thank you for your support.

EDIT

For sending the mail we are using the embedded javamail service of the spring framework. The code looks like this:

public class PrMailSendServiceImpl implements IPrMailSenderService{
    private JavaMailSenderImpl javaMailSenderService;
    private String defaultEmailFrom = "a@b.com";
    private String defaultEmailTo;
    public void sendEmail(String toEmail, String mailSubject, String mailContent) throws MessagingException {
        MimeMessage msg = javaMailSenderService.createMimeMessage();
        MimeMessageHelper mime = new MimeMessageHelper(msg, true, "UTF-8");
        mime.setText(mailContent, true);
        mime.setSubject(mailSubject);
        mime.setTo(toEmail);
        mime.setFrom(defaultEmailFrom);
        javaMailSenderService.send(msg);
    }
/*getter and setter*/
}

The described error occurs while the send method is executed.

The spring-context.xml file contains te following configurations:

<bean id="javaMailSenderService" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="mrvnet.kundenserver.de" />
    <property name="port" value="25" />
    <property name="username" value="my@mail.com" />
    <property name="password" value="myPassword" />

    <property name="javaMailProperties">
       <props>
              <prop key="mail.smtp.auth">true</prop>
              <prop key="mail.smtp.starttls.enable">true</prop>
           </props>
    </property>
</bean>

<bean id="mailSendService"  class="de.virtualsolution.procon.service.impl.PrMailSendServiceImpl">
    <property name="javaMailSenderService"><ref bean="javaMailSenderService" /></property>
    <property name="defaultEmailFrom"><value>my@mailcom</value></property>
</bean>

Body:
I figured out the problem. I took the answer from https://community.hpe.com/t5/System-Administration/Error-sending-e-mails-from-Java-ehlo-problem/td-p/4145190

Simple Mail Transfer Protocol RFCs stipulate use of HELO and EHLO.
  Invalid usage of HELO/EHLO in the SMTP dialogue is your problem.
  Most Mail Transfer Agents (MTAs)perform DNS
  (A- and PTR- resource records) verification
  on the domain name given on the SMTP HELO
  and EHLO commands. This can violate RFC 2821,
  so email is usually not rejected by default.
  In other words, EHLO and HELO typically
  require FQDN. A client MUST issue HELO or EHLO before
  starting a mail transaction.

SOLUTION (see Unable to send email using javamail api in linux)

On our server we have several sub-domains. Thus, when calling InetAddress.getLocalHost().getHostName() an exception was thrown. Therefore, to manually set the required host name for the HELO I added the line <prop key="mail.smtp.localhost">my.server.host.name</prop> in the spring-context.xml

Now it looks like:

<bean id="javaMailSenderService" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="mrvnet.kundenserver.de" />
    <property name="port" value="25" />
    <property name="username" value="my@mail.com" />
    <property name="password" value="myPassword" />

    <property name="javaMailProperties">
       <props>
              <prop key="mail.smtp.auth">true</prop>
              <prop key="mail.smtp.starttls.enable">true</prop>
              <prop key="mail.smtp.localhost">my.server.host.name</prop>
           </props>
    </property>
</bean>

<bean id="mailSendService"  class="de.virtualsolution.procon.service.impl.PrMailSendServiceImpl">
    <property name="javaMailSenderService"><ref bean="javaMailSenderService" /></property>
    <property name="defaultEmailFrom"><value>my@mailcom</value></property>
</bean>


问:
How to Dict.get a case insensitive key?
I'd like to grab the Total-Records key of a response.headers HTTP response.

Problem is that in some browser it is as returned by the server Total-Records but in some other, it is in lower case.

I'd like to get the value of the Total-Records header regardless of its case.
How would you do that?

答:
In the absence of a general-purpose case-insensitive dictionary, you can hack together a manual lookup:

caseInsensitiveGet : String -> Dict String v -> Maybe v
caseInsensitiveGet key dict =
    let
        lowerKey = String.toLower key
    in
        Dict.toList dict
            |> List.filterMap (\(k, v) ->
                if String.toLower k == lowerKey then
                    Just v
                else
                    Nothing)
            |> List.head
```

Note that this will perform worse the larger the dictionary is. In this form it is possible to have multiple variations of the same text with different cases, so it isn't perfect, but if you're just looking for a header, it should suffice.

Title: How to Dict.get a case insensitive key?

Body:
In the absence of a general-purpose case-insensitive dictionary, you can hack together a manual lookup:

caseInsensitiveGet : String -> Dict String v -> Maybe v
caseInsensitiveGet key dict =
    let
        lowerKey = String.toLower key
    in
        Dict.toList dict
            |> List.filterMap (\(k, v) ->
                if String.toLower k == lowerKey then
                    Just v
                else
                    Nothing)
            |> List.head

Note that this will perform worse the larger the dictionary is. In this form it is possible to have multiple variations of the same text with different cases, so it isn't perfect, but if you're just looking for a header, it should suffice.


问:
Android phone restarts on updating notification
Im making an app on Xamarin for android, and the app works perfectly on my Samsung phone with Android 6.

I have a part where I download some PDFs through the app, and in the process, notification keeps showing the percent of progress done.

But so far, 2 android phones with Android 5.1 on them keep restarting in that piece of code. if I remove the notification update code, the download will go through and nothing weird happens, but when the notification is updating, the phone restarts after 1-2 percent (or better say, after 1-2 times the notification gets updated).

Also the same piece of code makes my own phone a little slow while updating the notification, so I know it's not entirely perfect.

Can anyone suggest a work around? thanks.

Here is the code:

```<code>private void downloadprogress(object sender, DownloadProgressChangedEventArgs e)
    {
        try
        {
            if (e.ProgressPercentage < 100)
            {
                mBuilder.SetProgress(100, e.ProgressPercentage, false);
                mBuilder.SetContentText("Downloading - " + e.ProgressPercentage + "%");
                mNotifyManager.Notify(Convert.ToInt32(bookid), mBuilder.Build());
            }
            else
            {
                mBuilder.SetProgress(100, e.ProgressPercentage, false);
                mBuilder.SetContentText("Preparing the file");
                mNotifyManager.Notify(Convert.ToInt32(bookid), mBuilder.Build());
            }
        }
        catch { }
    }
</code>```

this is the notification flags:

```<code>Notification.Builder mBuilder;
NotificationManager mNotifyManager;
mNotifyManager = (NotificationManager)GetSystemService(Context.NotificationService);
        mBuilder = new Notification.Builder(Application.Context);
        if (!downloadingdemo)
            mBuilder.SetContentTitle(title);
        else
            mBuilder.SetContentTitle(title + "(demo)");
        mBuilder.SetContentText("Downloading - " + "0%");
        mBuilder.SetSmallIcon(Resource.Drawable.CCicon);
        mBuilder.SetAutoCancel(true);
        mBuilder.SetOngoing(true);
        mBuilder.SetProgress(100, 0, false);
        mNotifyManager.Notify(Convert.ToInt32(bookid), mBuilder.Build());
</code>```

答:
I would have posted a comment, but they seem to be quite filled up.

How many times are you updating the notification per second? (Try logging this) Do you need to throttle it to only change if it changes a whole percentage point?

I suspect you are slamming the NotificationManager with too many calls, and it might not work on older devices.

Body:
Im making an app on Xamarin for android, and the app works perfectly on my Samsung phone with Android 6.

I have a part where I download some PDFs through the app, and in the process, notification keeps showing the percent of progress done.

But so far, 2 android phones with Android 5.1 on them keep restarting in that piece of code. if I remove the notification update code, the download will go through and nothing weird happens, but when the notification is updating, the phone restarts after 1-2 percent (or better say, after 1-2 times the notification gets updated).

Also the same piece of code makes my own phone a little slow while updating the notification, so I know it's not entirely perfect.

Can anyone suggest a work around? thanks.

Here is the code:

private void downloadprogress(object sender, DownloadProgressChangedEventArgs e)
    {
        try
        {
            if (e.ProgressPercentage < 100)
            {
                mBuilder.SetProgress(100, e.ProgressPercentage, false);
                mBuilder.SetContentText("Downloading - " + e.ProgressPercentage + "%");
                mNotifyManager.Notify(Convert.ToInt32(bookid), mBuilder.Build());
            }
            else
            {
                mBuilder.SetProgress(100, e.ProgressPercentage, false);
                mBuilder.SetContentText("Preparing the file");
                mNotifyManager.Notify(Convert.ToInt32(bookid), mBuilder.Build());
            }
        }
        catch { }
    }

this is the notification flags:

Notification.Builder mBuilder;
NotificationManager mNotifyManager;
mNotifyManager = (NotificationManager)GetSystemService(Context.NotificationService);
        mBuilder = new Notification.Builder(Application.Context);
        if (!downloadingdemo)
            mBuilder.SetContentTitle(title);
        else
            mBuilder.SetContentTitle(title + "(demo)");
        mBuilder.SetContentText("Downloading - " + "0%");
        mBuilder.SetSmallIcon(Resource.Drawable.CCicon);
        mBuilder.SetAutoCancel(true);
        mBuilder.SetOngoing(true);
        mBuilder.SetProgress(100, 0, false);
        mNotifyManager.Notify(Convert.ToInt32(bookid), mBuilder.Build());


问:
How do I select a specific record from Many-to-many relationships which does not contain a specific item in Rails 2?
I am stuck with this for a couple of hours. It could be a quick solution but my brain is overheated now. Ok here it is.

I have Session and SessionType models which have many-to-many relationships to each other as follows.

```<code>class Session < ActiveRecord::Base
  ...
  has_and_belongs_to_many :session_types
  ...
end

class SessionType < ActiveRecord::Base
  ...
  has_and_belongs_to_many :sessions
  ...
end
</code>```

What I want is to get a session which doesn't contain any specific session_type, eg.,

```<code>Session.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])
</code>```

It doesn't work for me since the above query will still give me the sessions which have session_types.id "44" in many of its associations because of the nature of many-to-many relationships.

Also the following mysql code doesn't work as well.

```<code>select sessions.* from sessions
INNER JOIN `session_types_sessions` ON `session_types_sessions`.session_id = `sessions`.id
WHERE (  session_types_sessions.session_type_id NOT IN (44))
GROUP BY sessions.id
</code>```

Any help will be appreciated.

Thanks.

答:
First select those sessions which are of type 44:

```<code>session_types_44 = Session.find(:all, :joins => :session_types,
  :conditions => { :"session_types.id" => 44 }).uniq
</code>```

and select sessions which do not fall into the above:

```<code>sessions_without_type_44 = Session.find(:all,
  :conditions => "id NOT IN (#{session_types_44.join(",")})")
</code>```

You need to be careful with that because if session_types_44 is empty array you will get SQL error.

And to answer your second question:

do you know how I could change the SQL to filter like "get me sessions which have session_type_id '43', but they must NOT have '44'

Take the result from sessions_without_type_44 and use it. First select SessionType with 43 and through association get all sessions which belong to that SessionType and their ids are within the sessions_without_type_44:

```<code>SessionType.find(43).sessions.all(:conditions => {
  :id => sessions_without_type_44 })
</code>```

Body:
I am stuck with this for a couple of hours. It could be a quick solution but my brain is overheated now. Ok here it is.

I have Session and SessionType models which have many-to-many relationships to each other as follows.

class Session < ActiveRecord::Base
  ...
  has_and_belongs_to_many :session_types
  ...
end

class SessionType < ActiveRecord::Base
  ...
  has_and_belongs_to_many :sessions
  ...
end

What I want is to get a session which doesn't contain any specific session_type, eg.,

Session.find(:all, :joins => [:session_types], :conditions => ["session_types.id <> 44"])

It doesn't work for me since the above query will still give me the sessions which have session_types.id "44" in many of its associations because of the nature of many-to-many relationships.

Also the following mysql code doesn't work as well.

select sessions.* from sessions
INNER JOIN `session_types_sessions` ON `session_types_sessions`.session_id = `sessions`.id
WHERE (  session_types_sessions.session_type_id NOT IN (44))
GROUP BY sessions.id

Any help will be appreciated.

Thanks.

Body:
First select those sessions which are of type 44:

session_types_44 = Session.find(:all, :joins => :session_types,
  :conditions => { :"session_types.id" => 44 }).uniq

and select sessions which do not fall into the above:

sessions_without_type_44 = Session.find(:all,
  :conditions => "id NOT IN (#{session_types_44.join(",")})")

You need to be careful with that because if session_types_44 is empty array you will get SQL error.

And to answer your second question:

do you know how I could change the SQL to filter like "get me sessions which have session_type_id '43', but they must NOT have '44'

Take the result from sessions_without_type_44 and use it. First select SessionType with 43 and through association get all sessions which belong to that SessionType and their ids are within the sessions_without_type_44:

SessionType.find(43).sessions.all(:conditions => {
  :id => sessions_without_type_44 })


问:
A special switch statement in C
I am reading CSAPP, the chapter about setjmp and longjmp, and encounter the following code snippets:

```<code>int rc;
switch(setjmp(buf));
if (rc == 0)
    foo();
else if (rc == 1)
    printf("sth.");
else if (rc == 2)
    printf("sth. other");
...
</code>```

The switch statement really confused me, could someone explain this usage of switch statement in C for me?

PS: This is actually an error of CSAPP(the second edition), and the author fixes this by using normal switch-case statement in the third edition. Thanks for all.

答:
You cannot call setjmp outside a conditional check location, when a longjmp is called then the execution is resumed at the setjmp location stored in the buf parameter, returning the value passed to longjmp. I believe that who wrote the code just needed a conditional check location that did nothing, hence the empty switch.

To know more check the POSIX reference page that provides the documentation for the function as stated in the ISO C standard: http://pubs.opengroup.org/onlinepubs/9699919799/functions/setjmp.html

Also the manpage for longjmp(3) seems to provide more in-depth information: http://man7.org/linux/man-pages/man3/longjmp.3.html

[Edit]

Huh, it actual looks like you can call it outside a conditional check, specifically "The entire expression of an expression statement". I do not know why they did it, even though I understand why it would be best called in a conditional, so you can check its return value from wherever you jumped from.

Title: A special switch statement in C

Body:
I am reading CSAPP, the chapter about setjmp and longjmp, and encounter the following code snippets:

int rc;
switch(setjmp(buf));
if (rc == 0)
    foo();
else if (rc == 1)
    printf("sth.");
else if (rc == 2)
    printf("sth. other");
...

The switch statement really confused me, could someone explain this usage of switch statement in C for me?

PS: This is actually an error of CSAPP(the second edition), and the author fixes this by using normal switch-case statement in the third edition. Thanks for all.


问:
excel: concatenate values from userform
I have this UserForm called CompData and it seems like this:

The main objective of this form is to update a cell in the CONSULTA sheet with this string =">" & DATE(year, month, day) (or variations) where the values of DATE and the correct math symbol come from the form.

In the "Inserir" (it's my insert button) I associated this code:

```<code>Private Sub Inserir_Click()

If Maior.Value = True Then

    Worksheets("CONSULTA").Range("K23") = "=" > " & DATE(CompData.Ano.Value, CompData.Mes.Value, CompData.Dia.Value)"

ElseIf Maior.Value = True Then

    Worksheets("CONSULTA").Range("K23") = "=" < " & DATE(CompData.Ano.Value, CompData.Mes.Value, CompData.Dia.Value)"

ElseIf MaiorIgual.Value = True Then

    Worksheets("CONSULTA").Range("K23") = "=" >= " & DATE(CompData.Ano.Value, CompData.Mes.Value, CompData.Dia.Value)"

ElseIf MenorIgual.Value = True Then

    Worksheets("CONSULTA").Range("K23") = "=" <= " & DATE(CompData.Ano.Value, CompData.Mes.Value, CompData.Dia.Value)"

End If
End Sub
</code>```

Maior, Menor, MaiorIgual and MenorIgual are the names of my option buttons.

Anyway, when I run the code, it gives me:

Run-time error 461:
  Method or data member not found

And highlights this part:

```<code>Private Sub Inserir_Click()
</code>```

I know that exists a CONCATENATE function, but I don't think it will work on my VBA  code.

I don't know if I'm concatenating it right, but I really don't know how to fix this.

答:
If you want to set the formula of K23 to =">"&DATE(2017,6,8) then you would code:

```<code>Worksheets("CONSULTA").Range("K23").Formula = "="">""&DATE(" & CompData.Ano.Value & "," & CompData.Mes.Value & "," & CompData.Dia.Value & ")"
</code>```

Note the double "" where you want to include a " within a string.

Title: excel: concatenate values from userform

Body:
I have this UserForm called CompData and it seems like this:

The main objective of this form is to update a cell in the CONSULTA sheet with this string =">" & DATE(year, month, day) (or variations) where the values of DATE and the correct math symbol come from the form.

In the "Inserir" (it's my insert button) I associated this code:

Private Sub Inserir_Click()

If Maior.Value = True Then

    Worksheets("CONSULTA").Range("K23") = "=" > " & DATE(CompData.Ano.Value, CompData.Mes.Value, CompData.Dia.Value)"

ElseIf Maior.Value = True Then

    Worksheets("CONSULTA").Range("K23") = "=" < " & DATE(CompData.Ano.Value, CompData.Mes.Value, CompData.Dia.Value)"

ElseIf MaiorIgual.Value = True Then

    Worksheets("CONSULTA").Range("K23") = "=" >= " & DATE(CompData.Ano.Value, CompData.Mes.Value, CompData.Dia.Value)"

ElseIf MenorIgual.Value = True Then

    Worksheets("CONSULTA").Range("K23") = "=" <= " & DATE(CompData.Ano.Value, CompData.Mes.Value, CompData.Dia.Value)"

End If
End Sub

Maior, Menor, MaiorIgual and MenorIgual are the names of my option buttons.

Anyway, when I run the code, it gives me:

Run-time error 461:
  Method or data member not found

And highlights this part:

Private Sub Inserir_Click()

I know that exists a CONCATENATE function, but I don't think it will work on my VBA  code.

I don't know if I'm concatenating it right, but I really don't know how to fix this.

Body:
If you want to set the formula of K23 to =">"&DATE(2017,6,8) then you would code:

Worksheets("CONSULTA").Range("K23").Formula = "="">""&DATE(" & CompData.Ano.Value & "," & CompData.Mes.Value & "," & CompData.Dia.Value & ")"

Note the double "" where you want to include a " within a string.


问:
Who gets access to Instagrams API? Devil is in the details of their statement
It seemed tricky trying to get someone at instagram to answer some questions so maybe you guys could help.

Heres what instagram said about API Access.

The Instagram API Platform can be used to build non-automated, authentic, high-quality apps and services that:

```<code>1. Help individuals share their own content with 3rd party apps.
2. Help brands and advertisers understand, manage their audience and media rights.
3. Help broadcasters and publishers discover content, get digital rights to media, and share media with proper attribution.
</code>```

So looking at number 2.

So which of these would I be allowed to do?

Does this mean that it is permissible for me to

Use the api to find specific influencers that i would like to reach out to?

Does it mean that i need to make something that gives the influencers ore information about their demographic?

Does it mean that i could make an application which allows users to find influencers and see more info on their demographic?

I assume 3 is allowed but my question is 1 allowed as well. Do I need to make apps to be used for the public or can I use the data for only one brand?

Lastly what are a list of the information per user that the api offers?

Thanks!

答:
you can do with  this link :

```<code>https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code
</code>```

replace your clinet id to your clinet-id

And replace your redirect url to your redirect url

Body:
It seemed tricky trying to get someone at instagram to answer some questions so maybe you guys could help.

Heres what instagram said about API Access.

The Instagram API Platform can be used to build non-automated, authentic, high-quality apps and services that:

1. Help individuals share their own content with 3rd party apps.
2. Help brands and advertisers understand, manage their audience and media rights.
3. Help broadcasters and publishers discover content, get digital rights to media, and share media with proper attribution.

So looking at number 2.

So which of these would I be allowed to do?

Does this mean that it is permissible for me to

Use the api to find specific influencers that i would like to reach out to?

Does it mean that i need to make something that gives the influencers ore information about their demographic?

Does it mean that i could make an application which allows users to find influencers and see more info on their demographic?

I assume 3 is allowed but my question is 1 allowed as well. Do I need to make apps to be used for the public or can I use the data for only one brand?

Lastly what are a list of the information per user that the api offers?

Thanks!

Body:
you can do with  this link :

https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code

replace your clinet id to your clinet-id

And replace your redirect url to your redirect url


问:
VS2013 Agents from where can i download?
VS2013 agents are not found in site https://www.microsoft.com/en-hk/download/details.aspx?id=40750,where can i download it from.I want it to install in build server to run unit test from TFS xaml build.

答:
You'll need to download the TFS 2013 ISO, run the installation, and the configure the build controller and agents.

You can find the TFS 2013 ISO by going here and then selecting "Visual Studio Team Foundation Server 2013 with Update 5".

Installation and configuration instructions can be found here.


问:
Xcode 9 : Module compiled with Swift 3.1 cannot be imported in Swift 4.0
After updating to Xcode 9, I tried to build one of my projects.

I use the FacebookLogin pod.
I have a compiler error in FacebookLogin/LoginButton.swift

```<code>@testable import FacebookCore
❌ Module compiled with Swift 3.1 cannot be imported in Swift 4.0
</code>```

In my target's build settings, the Swift language version is set to Swift 3.2.

I guess I need to wait for Facebook to update their pod ? Or any other suggestion ?

Thanks !

答:
Xcode 9 comes with a Swift 4 compiler that understands both Swift 3.2 and swift 4, it even lets you mix and match between the 2 versions. Unfortunately, other versions aren't supported.

Even if you set your language to Swift 3.2, it uses the Swift 4 compiler.

If you're using cocoapods, you can add this to the end of your pod file to force the pods to use Swift 3.2 or 4.0:

```<code>post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['SWIFT_VERSION'] = '3.2'
        end
    end
end
</code>```

Alternatively, you could put the files from the pod directly into your project temporarily, until FacebookLogin is updated to Swift 3.2 or 4.

Note: Edited based on Matt's feedback

Body:
After updating to Xcode 9, I tried to build one of my projects.

I use the FacebookLogin pod.
I have a compiler error in FacebookLogin/LoginButton.swift

@testable import FacebookCore
❌ Module compiled with Swift 3.1 cannot be imported in Swift 4.0

In my target's build settings, the Swift language version is set to Swift 3.2.

I guess I need to wait for Facebook to update their pod ? Or any other suggestion ?

Thanks !

Body:
Xcode 9 comes with a Swift 4 compiler that understands both Swift 3.2 and swift 4, it even lets you mix and match between the 2 versions. Unfortunately, other versions aren't supported.

Even if you set your language to Swift 3.2, it uses the Swift 4 compiler.

If you're using cocoapods, you can add this to the end of your pod file to force the pods to use Swift 3.2 or 4.0:

post_install do |installer|
    installer.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['SWIFT_VERSION'] = '3.2'
        end
    end
end

Alternatively, you could put the files from the pod directly into your project temporarily, until FacebookLogin is updated to Swift 3.2 or 4.

Note: Edited based on Matt's feedback


问:
Primeng and Angular 2 controllers validation
I'm new to the primeng controllers and I'm stuck on the validation of some complex controllers for example the spinner controller. I want to set this controller to required and using ReactiveFormsModule I'm able to set the proper validation. however, I noticed that although he have the angular classes like this

```<code><p-spinner formControlName="myspinner" class="ng-dirty ng-touched ng-invalid">
</code>```

the inner input isn't affected by it, and this is a problem because the prime css is written to affect the input field.
 Is possible to resolve this by writing a little more css, but is suppose to be like this?? or am I doing something wrong?

答:
I still don't understand why the inner input field is not affected by the validation, but in my case it was a easy fix.
what I ended up doing was, set the css to change the border-color of the input child

```<code> p-spinner.ng-dirty.ng-invalid .ui-inputtext {
  border-bottom-color: #f44336;
}
</code>```

This was enough  for me.

Body:
I'm new to the primeng controllers and I'm stuck on the validation of some complex controllers for example the spinner controller. I want to set this controller to required and using ReactiveFormsModule I'm able to set the proper validation. however, I noticed that although he have the angular classes like this

the inner input isn't affected by it, and this is a problem because the prime css is written to affect the input field.
 Is possible to resolve this by writing a little more css, but is suppose to be like this?? or am I doing something wrong?

Body:
I still don't understand why the inner input field is not affected by the validation, but in my case it was a easy fix.
what I ended up doing was, set the css to change the border-color of the input child

 p-spinner.ng-dirty.ng-invalid .ui-inputtext {
  border-bottom-color: #f44336;
}

This was enough  for me.


问:
How to calculate total width of text including the left and right bearing
I am trying to calculate the total width of a span in HTML including both the left and right bearings of the first and last characters. I have already tried Javascript's offsetWidth and jQuery's width & outerWidth functions, but neither of them return the correct value I am seeking. Here is an example of what I mean. Running in Firefox the calculated width is 135px, while measuring with the Web Developer plug-in gives an actual width of 141px.

Edit

Here is what I've tried, and here are the values it gives me:
offsetWidth = 135
jQuery.width() = 135
jQuery.outerWidth() = 135

None of them are calculating the 6px overhang on the 'f' (which would make the width 141).

答:
How about jQuery's .width()?

```<code><span id="spanId"> ... </span>
</code>```

and

```<code>var w = $('#spanId').width();
</code>```

Body:
How about jQuery's .width()?

<span id="spanId"> ... </span>

and

var w = $('#spanId').width();


问:
AspNet core MVC 1.1.3 Default selected radio button
I am trying to default a radio button to be checked.

```<code><div>@Html.RadioButtonFor(m => m.IsActive, "OofDeactive", new { @class = "isActive", @checked="checked"})</div>
<div>@Html.RadioButtonFor(m => m.IsActive, "OofActive", new { @class = "isActive" })</div>
</code>```

Note that the model contains a property

```<code>public bool IsActive { get; set; }
</code>```

I have found the same issue here but for MVC6 although it is closed: https://github.com/aspnet/Mvc/issues/3098

Is this an issue or am I doing something wrong?

答:
Can you try this. </p>

```<code> @{
    var checked = Model.IsActive ? new {@checked = "checked"} : null;
var checked1 = checked == null ? new {@checked = "checked"} : null;
    }

          <div>@Html.RadioButtonFor(m => m.IsActive, "OofDeactive", checked)</div>
            <div>@Html.RadioButtonFor(m => m.IsActive, "OofActive", checked1)</div>
</code>```

Body:
I am trying to default a radio button to be checked.

@Html.RadioButtonFor(m => m.IsActive, "OofDeactive", new { @class = "isActive", @checked="checked"})

@Html.RadioButtonFor(m => m.IsActive, "OofActive", new { @class = "isActive" })

Note that the model contains a property

public bool IsActive { get; set; }

I have found the same issue here but for MVC6 although it is closed: https://github.com/aspnet/Mvc/issues/3098

Is this an issue or am I doing something wrong?

Body:
Can you try this.

 @{
    var checked = Model.IsActive ? new {@checked = "checked"} : null;
var checked1 = checked == null ? new {@checked = "checked"} : null;
    }

          <div>@Html.RadioButtonFor(m => m.IsActive, "OofDeactive", checked)</div>
            <div>@Html.RadioButtonFor(m => m.IsActive, "OofActive", checked1)</div>