问:
React native redux able to read value but unable to update value in the same page
I'm able to read the value of redux store(Props) but i'm unable to update the redux state value(Props2), when it seems like the action is dispatched to the reducer function.

Page:

```<code>componentDidMount(){
    console.log("Props:"+this.props.user)
}

dummyFunction() {
    //Redux
    this.props.toggleTheme('red');

    //which prints the object above in the screenshot
    console.log(this.props.toggleTheme('red'));

    console.log("Props2:"+this.props.user);
}

const mapStateToProps = state => ({
  user: state.user.userData,
});

const mapDispatchToProps = dispatch => ({
  toggleTheme: (user) => dispatch(toggleTheme(user)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Tab1Screen);
</code>```

Reducer:

```<code>const initialState = {
    userData: "Apple",
  };

  const user = (state = initialState, action) => {
    switch (action.type) {
      case 'TOGGLE_THEME':
        switch(action.payload) {
          case 'red':
            console.log("Payload1:"+ action.payload);
            return { userData: "Orange" };
          case 'blue':
          console.log("Payload2:"+ action.payload);
            return { userData: "Pear" };
        }
      default:
      console.log("Payload:3"+ action.payload);
        return state;
    }
  };

  export default user;
</code>```

Actions:

```<code>import { TOGGLE_THEME } from './actionTypes';
//which TOGGLE_THEME = 'TOGGLE_THEME'

export const toggleTheme = user => ({
  type: TOGGLE_THEME,
  payload: user,
});
</code>```

Package.json

```<code> "dependencies": {
    "@expo/samples": "2.1.1",
    "expo": "^32.0.0",
    "react": "^16.8.6",
    "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
    "react-navigation": "^3.0.9",
    "react-redux": "^6.0.1",
    "redux": "^4.0.1",
  }
</code>```

Update: Tried to retrieve the state when I navigate to another page and it's working correctly, retrieving orange value. How would I be able to get the correct value in the same page(in dummyFunction)?

答:
I'm not sure whether you can get the changed redux state immediately after setting it (dispatching an action).

What you can do is:

Dispatch toggleTheme action in dummyFunction

Detect the change in props using the lifecycle methods such as componentDidUpdate or getDerivedStateFromProps

On detecting change in user prop, use it as you wish

Body:
I'm able to read the value of redux store(Props) but i'm unable to update the redux state value(Props2), when it seems like the action is dispatched to the reducer function.

Page:

componentDidMount(){
    console.log("Props:"+this.props.user)
}

dummyFunction() {
    //Redux
    this.props.toggleTheme('red');

    //which prints the object above in the screenshot
    console.log(this.props.toggleTheme('red'));

    console.log("Props2:"+this.props.user);
}

const mapStateToProps = state => ({
  user: state.user.userData,
});

const mapDispatchToProps = dispatch => ({
  toggleTheme: (user) => dispatch(toggleTheme(user)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Tab1Screen);

Reducer:

const initialState = {
    userData: "Apple",
  };

  const user = (state = initialState, action) => {
    switch (action.type) {
      case 'TOGGLE_THEME':
        switch(action.payload) {
          case 'red':
            console.log("Payload1:"+ action.payload);
            return { userData: "Orange" };
          case 'blue':
          console.log("Payload2:"+ action.payload);
            return { userData: "Pear" };
        }
      default:
      console.log("Payload:3"+ action.payload);
        return state;
    }
  };

  export default user;

Actions:

import { TOGGLE_THEME } from './actionTypes';
//which TOGGLE_THEME = 'TOGGLE_THEME'

export const toggleTheme = user => ({
  type: TOGGLE_THEME,
  payload: user,
});

Package.json

 "dependencies": {
    "@expo/samples": "2.1.1",
    "expo": "^32.0.0",
    "react": "^16.8.6",
    "react-native": "https://github.com/expo/react-native/archive/sdk-32.0.0.tar.gz",
    "react-navigation": "^3.0.9",
    "react-redux": "^6.0.1",
    "redux": "^4.0.1",
  }

Update: Tried to retrieve the state when I navigate to another page and it's working correctly, retrieving orange value. How would I be able to get the correct value in the same page(in dummyFunction)?


来源: stackexchange

问:
SQL Xml for Xpath query
Trying to return the value of an XML field via Xpath query.

Here is what the XML looks like in a snap shot.

```<code><?xml version="1.0" encoding="utf-16"?>
<ArrayOfCustomProperty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustomProperty>
    <DeveloperId>Test123</DeveloperId>
    <Key>AgreedToTerms</Key>
    <Value>True</Value>
</CustomProperty>
<CustomProperty>
    <DeveloperId>Test456</DeveloperId>
    <Key>ValidForLoyaltyPoints</Key>
    <Value>False</Value>
</CustomProperty>
</ArrayOfCustomProperty>
</code>```

(sorry for the poorly-formatted XML...StackOverflows RCE is having issues with rendering it out.  The ArrayOfCustomProperty is closed at the end, just not displayed for some reason)

This query works for me....

```<code>  SET @return = CAST(CAST(@xmlData AS xml).query('ArrayOfCustomProperty/CustomProperty/Key[text()=sql:variable("@key")]/../Value/text()') AS nvarchar(255))
</code>```

It allows me to have a function where the parameters are @xmlData and @key for what needs to be searched.  I need to have another function (or might modify this one) where I can also search the [DeveloperId] node as well, so a third parameter will be passed in as @devId.  I've tried quite a few different things but nothing has worked for me yet.  I'd like a query where I can get the [Value] when [DeveloperId] and [Key] are present using the same structure (if possible) to how the current Xpath query works.

Thanks in advance for any help.

答:
@Shnugo

Is this what you meant with your last comment?

```<code>DECLARE @tbl TABLE(YourXml XML);
INSERT INTO @tbl VALUES (@xmlData)

SELECT t.YourXml.value('(/ArrayOfCustomProperty/CustomProperty/Value/text())[1]','nvarchar(250)') AS Value
FROM @tbl t
WHERE t.YourXml.value('(/ArrayOfCustomProperty/CustomProperty/Key/text())[1]','nvarchar(250)') = @key
AND
t.YourXml.value('(/ArrayOfCustomProperty/CustomProperty/DeveloperId/text())[1]','nvarchar(250)') = @devId
</code>```

ContentLicense: CC BY-SA 4.0

Title: SQL Xml for Xpath query

Body:
Trying to return the value of an XML field via Xpath query.

Here is what the XML looks like in a snap shot.

<?xml version="1.0" encoding="utf-16"?>
<ArrayOfCustomProperty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CustomProperty>
    <DeveloperId>Test123</DeveloperId>
    <Key>AgreedToTerms</Key>
    <Value>True</Value>
</CustomProperty>
<CustomProperty>
    <DeveloperId>Test456</DeveloperId>
    <Key>ValidForLoyaltyPoints</Key>
    <Value>False</Value>
</CustomProperty>
</ArrayOfCustomProperty>

(sorry for the poorly-formatted XML...StackOverflows RCE is having issues with rendering it out.  The ArrayOfCustomProperty is closed at the end, just not displayed for some reason)

This query works for me....

  SET @return = CAST(CAST(@xmlData AS xml).query('ArrayOfCustomProperty/CustomProperty/Key[text()=sql:variable("@key")]/../Value/text()') AS nvarchar(255))

It allows me to have a function where the parameters are @xmlData and @key for what needs to be searched.  I need to have another function (or might modify this one) where I can also search the [DeveloperId] node as well, so a third parameter will be passed in as @devId.  I've tried quite a few different things but nothing has worked for me yet.  I'd like a query where I can get the [Value] when [DeveloperId] and [Key] are present using the same structure (if possible) to how the current Xpath query works.

Thanks in advance for any help.

Body:
@Shnugo

Is this what you meant with your last comment?

DECLARE @tbl TABLE(YourXml XML);
INSERT INTO @tbl VALUES (@xmlData)

SELECT t.YourXml.value('(/ArrayOfCustomProperty/CustomProperty/Value/text())[1]','nvarchar(250)') AS Value
FROM @tbl t
WHERE t.YourXml.value('(/ArrayOfCustomProperty/CustomProperty/Key/text())[1]','nvarchar(250)') = @key
AND
t.YourXml.value('(/ArrayOfCustomProperty/CustomProperty/DeveloperId/text())[1]','nvarchar(250)') = @devId


问:
Plotly hovering on tiles in the background of a cloud of points - how to show the tooltip?
I'm converting a ggplot2 plot to plotly.
The plot consists of a tile layer (in the background) and a point layer (in the foreground).
I would like to have tooltips when hovering on the tiles.

The code below mostly gets me what I am looking for. When I hover on tiles in "points free" zones, the desired tooltip appears. However, when I hover in areas with a high density of dots, the tooltips do not appear.

I thought that playing with the layerData parameter in the ggplotly call might help, but that was not the case.

library(ggplot2)
library(dplyr)
library(plotly)

set.seed(1)
dat_points <- data.frame(x = rnorm(100), y = rnorm(100))
dat_tiles <- expand.grid(tx = -3:3, ty = -3:3)
dat_tiles$val <- rnorm(nrow(dat_tiles))
dat_tiles$label <- sample(LETTERS[1:5], nrow(dat_tiles), replace = T)

p <- ggplot() +
  geom_tile(data = dat_tiles, aes(x = tx, y = ty, fill = val, text = label)) +
  geom_point(data = dat_points, aes(x = x, y = y), alpha = .5)

gg <- ggplotly(p, tooltip = "text")
gg
```

I would like that hovering on high density areas (e.g. 0, 0) would bring up tooltips with the same promptness as in low density areas.

EDIT: added static image of the plot.

答:
You can switch the order of you layers in p and because of how ggplotly() constructs from a ggplot object, you get an identical looking plot, but with the desired tooltip behavior!

```<code>p <- ggplot() +
  geom_point(data = dat_points, aes(x = x, y = y), alpha = 1) +
  geom_tile(data = dat_tiles, aes(x = tx, y = ty, fill = val, text = label))
p # this looks bad

gg <- ggplotly(p, tooltip = "text")
gg # but this looks good!
</code>```

Body:
I'm converting a ggplot2 plot to plotly.
The plot consists of a tile layer (in the background) and a point layer (in the foreground).
I would like to have tooltips when hovering on the tiles.

The code below mostly gets me what I am looking for. When I hover on tiles in "points free" zones, the desired tooltip appears. However, when I hover in areas with a high density of dots, the tooltips do not appear.

I thought that playing with the layerData parameter in the ggplotly call might help, but that was not the case.

library(ggplot2)
library(dplyr)
library(plotly)

set.seed(1)
dat_points <- data.frame(x = rnorm(100), y = rnorm(100))
dat_tiles <- expand.grid(tx = -3:3, ty = -3:3)
dat_tiles$val <- rnorm(nrow(dat_tiles))
dat_tiles$label <- sample(LETTERS[1:5], nrow(dat_tiles), replace = T)

p <- ggplot() +
  geom_tile(data = dat_tiles, aes(x = tx, y = ty, fill = val, text = label)) +
  geom_point(data = dat_points, aes(x = x, y = y), alpha = .5)

gg <- ggplotly(p, tooltip = "text")
gg

I would like that hovering on high density areas (e.g. 0, 0) would bring up tooltips with the same promptness as in low density areas.

EDIT: added static image of the plot.

Body:
You can switch the order of you layers in p and because of how ggplotly() constructs from a ggplot object, you get an identical looking plot, but with the desired tooltip behavior!

p <- ggplot() +
  geom_point(data = dat_points, aes(x = x, y = y), alpha = 1) +
  geom_tile(data = dat_tiles, aes(x = tx, y = ty, fill = val, text = label))
p # this looks bad

gg <- ggplotly(p, tooltip = "text")
gg # but this looks good!


问:
How do I ask the Vision API to apply multiple features on an image
How do I call the Vision API and apply more than one feature on an image.
I want to apply both Label Detection and the landmark detection on an image</p>

答:
```<code>from google.cloud import vision
import os

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/path/client.json"

client = vision.ImageAnnotatorClient()
response = client.annotate_image({
      'image': {'source': {'image_uri': 'gs://yourbuket/1.jpg'}},
      'features': [{'type': vision.enums.Feature.Type.LABEL_DETECTION},
      {'type': vision.enums.Feature.Type.FACE_DETECTION}],
    })
</code>```

ContentLicense: CC BY-SA 3.0


问:
Working with GitHub and Cloud
I can't find a way to work with github and a cloud server that satisfies me.

The cloud server has an 'app' which is my project and inside this app there are different deployments (git branches).

I also have a github repository with my project.

We are 4 guys working on this project. Each of us has its own branch (and deployment in the cloud).

Every time I want to try some new code, I need to commit, push into the cloud and tell the cloud to deploy it. So at the end of the day, I have a lot of commits in my git log. I would like to push to the github too, so everyone can see my branch update, but I don't want everyone to see all my meaningless commits.

I can solve that problem by doing a rebase to squash them, but next time i push into the cloud i would get in troubles and I would have to force the push. It works, but it feels wrong.

Is squashing the commits, forcing the push into de cloud, and pushing into github the only way to work?

Any ideas?

Thank you a lot. :)

答:
I think squashing the commits it the wrong thing to do. There is no meaningless commit.

Otherwise, your solutions seems to be the one that works.

Title: Working with GitHub and Cloud


问:
Why does PySpin.CameraList().GetSize() return zero devices?
Why does the following code return a cameralist with a device via PySpin.System() class and not via PySpin.CameraList() class?

The return value may differ depending on how many cameras you've attached from the manufacturer.

import PySpin

system = PySpin.System.GetInstance()

cam_list = system.GetCameras()

numCams  = cam_list.GetSize()                 # return value >= 1

numCams2  = PySpin.CameraList().GetSize()     # return value  = 0

print ("No. of cams: %s - %s" % (numCams, numCams2))
```

Result:

No. of cams: 1 - 0

答:
class PySpin.System(*args, **kwargs):

Here the system object GetCameras() is used to retrieve the list of interfaces and cameras available on your OS.
This only works if the static systempointer GetInstance() is used. Then the devices are loaded into the CameraList()
 and therefor not empty.

class PySpin.CameraList(*args):

Used to hold a list of camera objects and does not retrieve it by itself.

Hence, numCams = len(system.GetCameras()) will also work to get the No. of devices.

Body:
Why does the following code return a cameralist with a device via PySpin.System() class and not via PySpin.CameraList() class?

The return value may differ depending on how many cameras you've attached from the manufacturer.

import PySpin

system = PySpin.System.GetInstance()

cam_list = system.GetCameras()

numCams  = cam_list.GetSize()                 # return value >= 1

numCams2  = PySpin.CameraList().GetSize()     # return value  = 0

print ("No. of cams: %s - %s" % (numCams, numCams2))

Result:

No. of cams: 1 - 0


问:
Is it possible to communicate with vending machines (that uses MDB) using UART directly without using hardware adapter?
I'm building a linux-based cashless device and trying to achieve communication with VMC in vending machines over UART directly without needing additional hardware adapter to convert between 8-bit and 9-bit frame data.

I'm only using the cashless device, no intention to connect any other peripheral to the VMC.

I read questions asked about this before, some of them stressed on the need to an adapter, others suggested possible hacks to achieve the 9-bit to 8-bit conversion, but still can't find a confirmed working and stable solution.

My question is, Is it possible (and reliable) to achieve this using a pure software solution? and how?

Thanks

答:
Yes.

The 9th bit is a control bit. It will show if the data is to be interpreted as an address or as data. If you are communicating with one device and sending only data you want to strip the 9th bit out and only look at data frames. Check and see if it's always zero:

```<code>If controlBit = 0:
    ProcessData(byte)
Else:
    print("This is an address: " + byte)
</code>```

EDIT:
Many people have reported that your connection will not be stable without special hardware due to timing problems.

Instead of reinventing the wheel you can use opensource code as a starting point.
https://github.com/mhaqs/vendiverse/wiki/Programming-the-VMC

This way you don't have to make the same mistakes over and over again.

Body:
Yes.

The 9th bit is a control bit. It will show if the data is to be interpreted as an address or as data. If you are communicating with one device and sending only data you want to strip the 9th bit out and only look at data frames. Check and see if it's always zero:

If controlBit = 0:
    ProcessData(byte)
Else:
    print("This is an address: " + byte)

EDIT:
Many people have reported that your connection will not be stable without special hardware due to timing problems.

Instead of reinventing the wheel you can use opensource code as a starting point.
https://github.com/mhaqs/vendiverse/wiki/Programming-the-VMC

This way you don't have to make the same mistakes over and over again.


问:
How can I identify duplicated elements in rows
I have a data frame which looks like this but with altogether 31 variables(columns) and 11000 observations (the missing values are empty):

```<code>T1 = c("a1", "c1", "e1", "d1", "a3", "f1", "f2")
T2 = c("b1", "d1", "a1", "b2", "a3", "f1", "f3")
T3 = c(NA, NA, "e1", "d1", NA, "a4", "f3")
T4 = c( NA, NA, NA, "b2", NA, "b3", "f5")
T5 = c( NA, NA, NA, NA, NA, "a4", "f6")
T6 = c( NA, NA, NA, NA, NA,  NA, "f7")
T7 = c(NA, NA, NA, NA, NA, NA, "c1")
T8 = c(NA, NA, NA, NA, NA, NA, "c1")
T9 = c(NA, NA, NA, NA, NA, NA, "f2")
T10= c(NA, NA, NA, NA, NA, NA, "f3")
</code>```

I would like to identify if there is any duplicated element of the "T" type variables by rows, so my df would look like this:

```<code> T1 = c("a1", "c1", "e1", "d1", "a3", "f1", "f2")
 T2 = c("b1", "d1", "a1", "b2", "a3", "f1", "f3")
 T3 = c(NA, NA, "e1", "d1", NA, "a4", "f3")
 T4 = c( NA, NA, NA, b2, NA, "b3", "f5")
 T5 = c( NA, NA, NA, NA, NA, "a4", "f6")
 T6 = c( NA, NA, NA, NA, NA,  NA, "f7")
 T7 = c(NA, NA, NA, NA, NA, NA, "c1")
 T8 = c(NA, NA, NA, NA, NA, NA, "c1")
 T9 = c(NA, NA, NA, NA, NA, NA, "f2")
 T10= c(NA, NA, NA, NA, NA, NA, "f3")
 D = c(F, F, T, T, T, T, T)
</code>```

I attempted to write a function but clearly I miss something because it does not work:
first I created a new variable with empty values

```<code>df$D <- ""
</code>```

then the function:

```<code>dupl <- function(x){
     for(i in 1:nrow(x))
              if (duplicated(x[i], incomparables = NA)){
            df$D <- "TRUE"
  }else{
    df$D <- "FALSE"
  }
}

df$D <- dupl(df)
</code>```

I also tried this code but it does not give me the rows (when D takes a value of true) which contains the duplicated elements:

```<code>df$D <- apply(df[-1], 1, function(i) any(duplicated(i, incomparables = NA)))
</code>```

答:
The following uses base R only.

```<code>df1$D <- apply(df1, 1, function(x) {
  x <- na.omit(x)
  any(unlist(Map('==', x[1], x[-1])))
})

df1
#  T1 T2   T3   T4   T5   T6   T7   T8   T9  T10     D
#1 a1 b1 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> FALSE
#2 c1 d1 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> FALSE
#3 e1 a1   e1 <NA> <NA> <NA> <NA> <NA> <NA> <NA>  TRUE
#4 d1 b2   d1   b2 <NA> <NA> <NA> <NA> <NA> <NA>  TRUE
#5 a3 a3 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>  TRUE
#6 f1 f1   a4   b3   a4 <NA> <NA> <NA> <NA> <NA>  TRUE
#7 f2 f3   f3   f5   f6   f7   c1   c1   f2   f3  TRUE
</code>```

Data.

With the vectors in the question, the data.frame is created with the following code. It uses a function from external package stringr.

```<code>v <- stringr::str_sort(ls(pattern = '^T[[:digit:]]+$'), numeric = TRUE)
df1 <- data.frame(mget(v))
</code>```

Body:
I have a data frame which looks like this but with altogether 31 variables(columns) and 11000 observations (the missing values are empty):

T1 = c("a1", "c1", "e1", "d1", "a3", "f1", "f2")
T2 = c("b1", "d1", "a1", "b2", "a3", "f1", "f3")
T3 = c(NA, NA, "e1", "d1", NA, "a4", "f3")
T4 = c( NA, NA, NA, "b2", NA, "b3", "f5")
T5 = c( NA, NA, NA, NA, NA, "a4", "f6")
T6 = c( NA, NA, NA, NA, NA,  NA, "f7")
T7 = c(NA, NA, NA, NA, NA, NA, "c1")
T8 = c(NA, NA, NA, NA, NA, NA, "c1")
T9 = c(NA, NA, NA, NA, NA, NA, "f2")
T10= c(NA, NA, NA, NA, NA, NA, "f3")

I would like to identify if there is any duplicated element of the "T" type variables by rows, so my df would look like this:

 T1 = c("a1", "c1", "e1", "d1", "a3", "f1", "f2")
 T2 = c("b1", "d1", "a1", "b2", "a3", "f1", "f3")
 T3 = c(NA, NA, "e1", "d1", NA, "a4", "f3")
 T4 = c( NA, NA, NA, b2, NA, "b3", "f5")
 T5 = c( NA, NA, NA, NA, NA, "a4", "f6")
 T6 = c( NA, NA, NA, NA, NA,  NA, "f7")
 T7 = c(NA, NA, NA, NA, NA, NA, "c1")
 T8 = c(NA, NA, NA, NA, NA, NA, "c1")
 T9 = c(NA, NA, NA, NA, NA, NA, "f2")
 T10= c(NA, NA, NA, NA, NA, NA, "f3")
 D = c(F, F, T, T, T, T, T)

I attempted to write a function but clearly I miss something because it does not work:
first I created a new variable with empty values

df$D <- ""

then the function:

dupl <- function(x){
     for(i in 1:nrow(x))
              if (duplicated(x[i], incomparables = NA)){
            df$D <- "TRUE"
  }else{
    df$D <- "FALSE"
  }
}

df$D <- dupl(df)

I also tried this code but it does not give me the rows (when D takes a value of true) which contains the duplicated elements:

df$D <- apply(df[-1], 1, function(i) any(duplicated(i, incomparables = NA)))

Body:
The following uses base R only.

df1$D <- apply(df1, 1, function(x) {
  x <- na.omit(x)
  any(unlist(Map('==', x[1], x[-1])))
})

df1
#  T1 T2   T3   T4   T5   T6   T7   T8   T9  T10     D
#1 a1 b1 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> FALSE
#2 c1 d1 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> FALSE
#3 e1 a1   e1 <NA> <NA> <NA> <NA> <NA> <NA> <NA>  TRUE
#4 d1 b2   d1   b2 <NA> <NA> <NA> <NA> <NA> <NA>  TRUE
#5 a3 a3 <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>  TRUE
#6 f1 f1   a4   b3   a4 <NA> <NA> <NA> <NA> <NA>  TRUE
#7 f2 f3   f3   f5   f6   f7   c1   c1   f2   f3  TRUE

Data.

With the vectors in the question, the data.frame is created with the following code. It uses a function from external package stringr.

v <- stringr::str_sort(ls(pattern = '^T[[:digit:]]+$'), numeric = TRUE)
df1 <- data.frame(mget(v))


问:
Spring Maven reading from resources folder
I'm using Spring Boot. I want to read a json file in src/main/resources folder.

```<code>File file = new File(this.getClass().getClassLoader().getResource(inputFileName).getFile());
</code>```

Maven:

```<code><?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" output="target/classes" path="src/main/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="src" output="target/test-classes" path="src/test/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="test" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="output" path="target/classes"/>
</classpath>
</code>```

Now, when I run my Spring Boot application in Eclipse using Spring Tools (Run As -> Spring Boot App), I get NoSuchFileException and the application is trying to find the file in /target/classes/ instead of /src/main/resources folder.

Also, I cannot see the file in /target/classes/ folder. Why isn't maven copying it to target/classes?

What can I do to read from the resources folder?

答: if you are work in a normal maven java project. src/main/resources are in the class path by default. So you are fine to access the files under it when you package with maven. Even if in Eclipse project, file in resources will be copied to target/classes folder. So no problem.

Body:
I'm using Spring Boot. I want to read a json file in src/main/resources folder.

File file = new File(this.getClass().getClassLoader().getResource(inputFileName).getFile());

Maven:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" output="target/classes" path="src/main/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="src" output="target/test-classes" path="src/test/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="test" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="output" path="target/classes"/>
</classpath>

Now, when I run my Spring Boot application in Eclipse using Spring Tools (Run As -> Spring Boot App), I get NoSuchFileException and the application is trying to find the file in /target/classes/ instead of /src/main/resources folder.

Also, I cannot see the file in /target/classes/ folder. Why isn't maven copying it to target/classes?

What can I do to read from the resources folder?


问:
Mongo Aggregation Get Difference between values of array objects
Good day, I am having difficulty using aggregation in mongodb to get the date difference between two values in an array, my document structure looks as follows:

```<code>{
    "_id" : ObjectId("5c591420a890362dec70fcf4"),
    "tracetag" : "T00005",
    "amounts" : [
        {
            "_id" : ObjectId("5c5915bea890362dec71015a"),
            "startdate" : ISODate("2019-02-15T04:49:02.000+0000"),
            "enddate" : ISODate("2019-02-15T04:50:05.000+0000"),
            "amount" : 18.975946800811833,
        },
        {
            "_id" : ObjectId("5c5915bea890362dec71015b"),
            "startdate" : ISODate("2019-02-16T04:49:02.000+0000"),
            "enddate" : ISODate("2019-02-16T04:51:52.000+0000"),
            "amount" : 3.5755730555836203,
        },
        {
            "_id" : ObjectId("5c5915bea890362dec71015c"),
            "startdate" : ISODate("2019-02-17T04:49:02.000+0000"),
            "enddate" : ISODate("2019-02-17T04:50:04.000+0000"),
            "amount" : 2.3937573313380383,
        }
    ],
}
</code>```

the number of "amounts" entries are not fixed, so it could be 1 or 50 etc.

for each document, I would like to get the difference between the 'enddate' and 'startdate' (aka the duration) and I would like to sum the duration (lets call this totalduration). I can do the total 'amount' without issues, but getting the duration gives me error ""cant $subtract aarray from a array", my aggregation looks like this:

```<code>{
            "$project" : {
                "tracetag" : 1.0,
                "totalamount" : {
                    "$sum" : "$amounts.amount"
                },
                "totalduration" : {
                "$sum" : {
                     "$subtract" : [
                        "$amounts.enddate",
                        "$amounts.startdate"
                    ]
                  }
                }
            }
        },
</code>```

答:
OK so I managed to answer my own question: the 'amounts' need to be split using the $unwind operator, then a field can be added to each record (duration), in my case I wanted the duration in minutes. Afterwards I grouped everything again</p>

```<code>{
      "$unwind" : { "path" : "$amounts" }
    },
    {
      "$addFields" : {
          "duration" : { "$divide" : [ { "$subtract" : [
"$enddate", "$startdate" ]}, 60000.0 ] }
      }
    },
</code>```

Body:
Good day, I am having difficulty using aggregation in mongodb to get the date difference between two values in an array, my document structure looks as follows:

{
    "_id" : ObjectId("5c591420a890362dec70fcf4"),
    "tracetag" : "T00005",
    "amounts" : [
        {
            "_id" : ObjectId("5c5915bea890362dec71015a"),
            "startdate" : ISODate("2019-02-15T04:49:02.000+0000"),
            "enddate" : ISODate("2019-02-15T04:50:05.000+0000"),
            "amount" : 18.975946800811833,
        },
        {
            "_id" : ObjectId("5c5915bea890362dec71015b"),
            "startdate" : ISODate("2019-02-16T04:49:02.000+0000"),
            "enddate" : ISODate("2019-02-16T04:51:52.000+0000"),
            "amount" : 3.5755730555836203,
        },
        {
            "_id" : ObjectId("5c5915bea890362dec71015c"),
            "startdate" : ISODate("2019-02-17T04:49:02.000+0000"),
            "enddate" : ISODate("2019-02-17T04:50:04.000+0000"),
            "amount" : 2.3937573313380383,
        }
    ],
}

the number of "amounts" entries are not fixed, so it could be 1 or 50 etc.

for each document, I would like to get the difference between the 'enddate' and 'startdate' (aka the duration) and I would like to sum the duration (lets call this totalduration). I can do the total 'amount' without issues, but getting the duration gives me error ""cant $subtract aarray from a array", my aggregation looks like this:

{
            "$project" : {
                "tracetag" : 1.0,
                "totalamount" : {
                    "$sum" : "$amounts.amount"
                },
                "totalduration" : {
                "$sum" : {
                     "$subtract" : [
                        "$amounts.enddate",
                        "$amounts.startdate"
                    ]
                  }
                }
            }
        },

Body:
OK so I managed to answer my own question: the 'amounts' need to be split using the $unwind operator, then a field can be added to each record (duration), in my case I wanted the duration in minutes. Afterwards I grouped everything again

{
      "$unwind" : { "path" : "$amounts" }
    },
    {
      "$addFields" : {
          "duration" : { "$divide" : [ { "$subtract" : [
"$enddate", "$startdate" ]}, 60000.0 ] }
      }
    },


问:
Power BI License
When we try to Add Power BI Embedded machine in Azure console. It asks us to select machine size like A1, A2, A3 and according to that it has pricing

1) Is that monthly price only infrastructure cost or it includes Power BI license cost
2) Do we need to seperatly buy power BI pro license? or it comes pre packaged in Azure Power BI embedded service.

答:
I think that you can find answers for you questions here.

In short.

The price only covers cost of the infrastucture. There is no Power BI Pro license included. You will be charged according to usage per hour.

Only users which publish content need to have a Power BI Pro license.

Title: Power BI License


问:
Check if record exists in python. If exists then skip else process
I have a function for extracting frames from videos. I have a csv file which has the names of the videos already processed. I want to check if the name of a newly added video file is present in the csv file. If present then exit the code else process the function to extract frames from the new video

```<code>def extractFrames(m):
    global vid_name

    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        print("path of video========>>>>.",vid_files[v_f])

        #latest_file=max(vid_files, key=os.path.getctime)

        #print(latest_file)

        v1=os.path.basename(vid_files[v_f])
        try:
            vid_name = os.path.splitext(v1)[0]

            vidcap = cv2.VideoCapture(vid_files[v_f])
        except cv2.error as e:
            print(e)
        except:
                print('error')
        #condition
        fsize=os.stat(vid_files[v_f])
        print('=============size of video ===================:' , fsize.st_size)
        try:

            if (fsize.st_size > 1000):

                fps = vidcap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
                frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
                duration = frameCount/fps
                minutes = int(duration/60)
                print('fps = ' + str(fps))
                print('number of frames = ' + str(frameCount))
                print('duration (S) = ' + str(duration))
                if (duration > 1):
                    success,image = vidcap.read()

                    count=0

                    success=True

                    while success:

                        img_name = vid_name + '_f' + str(count) + ".jpg"

                        success,image = vidcap.read()
                        if count % 10 == 0 or count ==0:
                            target_non_target(img_name, image)

                        count+=1

                    vidcap.release()

                    cv2.destroyAllWindows()
        except:
            print("error")

        print('finished processing video ', vid_files[v_f])
        with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv', 'a') as csv_file:
            fieldnames = ['Video_Name','Process']
            file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv').st_size == 0
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            if file_is_empty:
                writer.writeheader()
            writer.writerow({'Video_Name':vid_name,'Process':'done'})

if __name__ == "__main__":

    x="C:\\Python36\\videos\\*.mp4"

    extractFrames(x)
</code>```

Suppose a folder has 2 videos V1 and V2 from which frames have already been extracted and the names V1 and V2 are added in the csv file. Now when i add video V3 the code should check if V3 exists already in the csv. If it exists then the code should be skipped else frames from V3 should be processed and V3 should be added in the csv file after extraction of the frames

答:
I think you might need a function to get the list completed/done videos from the csv file.
Something like this, might need to tweak a bit for the header row.

```<code>def get_completed_videos():
    completed_videos = []
    with open(".../video_info.csv") as csv_file:
        for row in csv.reader(csv_file):
            completed_videos.append(row[0])
    return completed_videos
</code>```

Then exclude them in the extracting func

```<code>def extractFrames(m):
    global vid_name

    vid_files=glob(m)
    complete_videos = get_completed_videos()
    new_vid_files = [x for x in vid_files if x not in complete_videos]

    ...
</code>```

Body:
I have a function for extracting frames from videos. I have a csv file which has the names of the videos already processed. I want to check if the name of a newly added video file is present in the csv file. If present then exit the code else process the function to extract frames from the new video

def extractFrames(m):
    global vid_name

    vid_files=glob(m)

    for v_f in range(len(vid_files)):
        print("path of video========>>>>.",vid_files[v_f])

        #latest_file=max(vid_files, key=os.path.getctime)

        #print(latest_file)

        v1=os.path.basename(vid_files[v_f])
        try:
            vid_name = os.path.splitext(v1)[0]

            vidcap = cv2.VideoCapture(vid_files[v_f])
        except cv2.error as e:
            print(e)
        except:
                print('error')
        #condition
        fsize=os.stat(vid_files[v_f])
        print('=============size of video ===================:' , fsize.st_size)
        try:

            if (fsize.st_size > 1000):

                fps = vidcap.get(cv2.CAP_PROP_FPS)      # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
                frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
                duration = frameCount/fps
                minutes = int(duration/60)
                print('fps = ' + str(fps))
                print('number of frames = ' + str(frameCount))
                print('duration (S) = ' + str(duration))
                if (duration > 1):
                    success,image = vidcap.read()

                    count=0

                    success=True

                    while success:

                        img_name = vid_name + '_f' + str(count) + ".jpg"

                        success,image = vidcap.read()
                        if count % 10 == 0 or count ==0:
                            target_non_target(img_name, image)

                        count+=1

                    vidcap.release()

                    cv2.destroyAllWindows()
        except:
            print("error")

        print('finished processing video ', vid_files[v_f])
        with open("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv', 'a') as csv_file:
            fieldnames = ['Video_Name','Process']
            file_is_empty = os.stat("C:\\multi_cat_3\\models\\research\\object_detection\\my_imgs"+'/video_info.csv').st_size == 0
            writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
            if file_is_empty:
                writer.writeheader()
            writer.writerow({'Video_Name':vid_name,'Process':'done'})

if __name__ == "__main__":

    x="C:\\Python36\\videos\\*.mp4"

    extractFrames(x)

Suppose a folder has 2 videos V1 and V2 from which frames have already been extracted and the names V1 and V2 are added in the csv file. Now when i add video V3 the code should check if V3 exists already in the csv. If it exists then the code should be skipped else frames from V3 should be processed and V3 should be added in the csv file after extraction of the frames

Body:
I think you might need a function to get the list completed/done videos from the csv file.
Something like this, might need to tweak a bit for the header row.

def get_completed_videos():
    completed_videos = []
    with open(".../video_info.csv") as csv_file:
        for row in csv.reader(csv_file):
            completed_videos.append(row[0])
    return completed_videos

Then exclude them in the extracting func

def extractFrames(m):
    global vid_name

    vid_files=glob(m)
    complete_videos = get_completed_videos()
    new_vid_files = [x for x in vid_files if x not in complete_videos]

    ...


问:
How to determine if drive is external drive
How can I determine if a drive is a external drive plugged in through usb ? I checked the DriveInfo.DriveType but with my 1TB external drive plugged in through usb it shows up as a fixed drive.

Thoughts ?

答:
I came across this question looking for a way to get a list of external drives, and I found that I could simplify a lot by updating the syntax. Also, some USB drives are UAS or USB attached SCSI, and the interface for those types of drives will actually show up as SCSI and not USB. From my tests, I've found that just checking for the terms "external" and "removable" in the physical disk's media type is sufficient.

public List<DriveInfo> getExternalDrives()
{
    var drives = DriveInfo.GetDrives();
    var externalDrives = new List<DriveInfo>();

    var allPhysicalDisks = new ManagementObjectSearcher("select MediaType, DeviceID from Win32_DiskDrive").Get();

    foreach (var physicalDisk in allPhysicalDisks)
    {
        var allPartitionsOnPhysicalDisk = new ManagementObjectSearcher($"associators of {{Win32_DiskDrive.DeviceID='{physicalDisk["DeviceID"]}'}} where AssocClass = Win32_DiskDriveToDiskPartition").Get();
        foreach(var partition in allPartitionsOnPhysicalDisk)
        {
            if (partition == null)
                continue;

            var allLogicalDisksOnPartition = new ManagementObjectSearcher($"associators of {{Win32_DiskPartition.DeviceID='{partition["DeviceID"]}'}} where AssocClass = Win32_LogicalDiskToPartition").Get();
            foreach(var logicalDisk in allLogicalDisksOnPartition)
            {
                if (logicalDisk == null)
                    continue;

                var drive = drives.Where(x => x.Name.StartsWith(logicalDisk["Name"] as string, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                var mediaType = (physicalDisk["MediaType"] as string).ToLowerInvariant();
                if (mediaType.Contains("external") || mediaType.Contains("removable"))
                    externalDrives.Add(drive);
            }
        }
    }
    return externalDrives;
}
```


问:
Failed to find data source: ignite
I have a three node spark cluster and three node ignite cluster.
Spark version: 2.3
Ignite version: 2.7

This is how I set the classpath in Spark's spark-default.conf:

```<code>spark.driver.extraClassPath /home/user/apache-ignite-2.7.0-bin/libs/*:/home/user/apache-ignite-2.7.0-bin/libs/ignite-indexing/*:/home/user/apache-ignite-2.7.0-bin/libs/optional/ignite-spark/*:/home/user/apache-ignite-2.7.0-bin/libs/ignite-spring/*
</code>```

In my Spark (Java) code, I am creating a dataframe and writing to Ignite like this:

```<code>df.write()
.format(IgniteDataFrameSettings.FORMAT_IGNITE())
.option(IgniteDataFrameSettings.OPTION_CONFIG_FILE(), confPath)
.option(IgniteDataFrameSettings.OPTION_TABLE(), tableName)
.mode(SaveMode.Append)
.option(IgniteDataFrameSettings.OPTION_CREATE_TABLE_PRIMARY_KEY_FIELDS(), primaryKey)
.option(IgniteDataFrameSettings.OPTION_CREATE_TABLE_PARAMETERS(), "template=partitioned")
.save();
</code>```

I am getting the following error in Spark:

```<code>java.lang.ClassNotFoundException: Failed to find data source: ignite. Please find packages at http://spark.apache.org/third-party-projects.html
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:635)
at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:241)

Caused by: java.lang.ClassNotFoundException: ignite.DefaultSource
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:618)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:618)
at scala.util.Try$.apply(Try.scala:192)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:618)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:618)
at scala.util.Try.orElse(Try.scala:84)
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:618)
</code>```

What else should I do to resolve this issue? Any help is highly appreciated.
Thank you.

答:
This error means that you don't have next in resources:

META-INF.services/org.apache.spark.sql.sources.DataSourceRegister

That should be a part of ignite-spark dependency.

So what you should check:

1)That ignite-spark-2.7.0.jar exists in the classpath of all your nodes where you have Spark nodes.

2)In case if you use spark.driver.extraClassPath then please check that:

a. You do it client mode (--deploy-mode client) because Spark fires up a Netty HTTP server which distributes the files on startup for each of the worker nodes. In cluster mode spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node.

b. I am not sure but looks like extraClassPath requires the list of jar files instead of /path/to/lib/*. You can try to use next:

```<code>EXECUTOR_PATH=""
   for eachjarinlib in $JARS ; do
if [ "$eachjarinlib" != "APPLICATIONJARTOBEADDEDSEPERATELY.JAR" ]; then
       EXECUTOR_PATH=file:$eachjarinlib:$EXECUTOR_PATH
fi
done
spark-submit --deploy-mode client --master yarn --conf "spark.driver.extraClassPath=$EXECUTOR_PATH" --class $EXAMPLE_CLASS $PATH_TO_JAR
</code>```

where $JARS is a path to your libs.

Title: Failed to find data source: ignite

Body:
I have a three node spark cluster and three node ignite cluster.
Spark version: 2.3
Ignite version: 2.7

This is how I set the classpath in Spark's spark-default.conf:

spark.driver.extraClassPath /home/user/apache-ignite-2.7.0-bin/libs/*:/home/user/apache-ignite-2.7.0-bin/libs/ignite-indexing/*:/home/user/apache-ignite-2.7.0-bin/libs/optional/ignite-spark/*:/home/user/apache-ignite-2.7.0-bin/libs/ignite-spring/*

In my Spark (Java) code, I am creating a dataframe and writing to Ignite like this:

df.write()
.format(IgniteDataFrameSettings.FORMAT_IGNITE())
.option(IgniteDataFrameSettings.OPTION_CONFIG_FILE(), confPath)
.option(IgniteDataFrameSettings.OPTION_TABLE(), tableName)
.mode(SaveMode.Append)
.option(IgniteDataFrameSettings.OPTION_CREATE_TABLE_PRIMARY_KEY_FIELDS(), primaryKey)
.option(IgniteDataFrameSettings.OPTION_CREATE_TABLE_PARAMETERS(), "template=partitioned")
.save();

I am getting the following error in Spark:

java.lang.ClassNotFoundException: Failed to find data source: ignite. Please find packages at http://spark.apache.org/third-party-projects.html
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:635)
at org.apache.spark.sql.DataFrameWriter.save(DataFrameWriter.scala:241)

Caused by: java.lang.ClassNotFoundException: ignite.DefaultSource
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:618)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23$$anonfun$apply$15.apply(DataSource.scala:618)
at scala.util.Try$.apply(Try.scala:192)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:618)
at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$23.apply(DataSource.scala:618)
at scala.util.Try.orElse(Try.scala:84)
at org.apache.spark.sql.execution.datasources.DataSource$.lookupDataSource(DataSource.scala:618)

What else should I do to resolve this issue? Any help is highly appreciated.
Thank you.

Body:
This error means that you don't have next in resources:

META-INF.services/org.apache.spark.sql.sources.DataSourceRegister

That should be a part of ignite-spark dependency.

So what you should check:

1)That ignite-spark-2.7.0.jar exists in the classpath of all your nodes where you have Spark nodes.

2)In case if you use spark.driver.extraClassPath then please check that:

a. You do it client mode (--deploy-mode client) because Spark fires up a Netty HTTP server which distributes the files on startup for each of the worker nodes. In cluster mode spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node.

b. I am not sure but looks like extraClassPath requires the list of jar files instead of /path/to/lib/*. You can try to use next:

EXECUTOR_PATH=""
   for eachjarinlib in $JARS ; do
if [ "$eachjarinlib" != "APPLICATIONJARTOBEADDEDSEPERATELY.JAR" ]; then
       EXECUTOR_PATH=file:$eachjarinlib:$EXECUTOR_PATH
fi
done
spark-submit --deploy-mode client --master yarn --conf "spark.driver.extraClassPath=$EXECUTOR_PATH" --class $EXAMPLE_CLASS $PATH_TO_JAR

where $JARS is a path to your libs.


问:
Checking for null and empty values in javascript
What is wrong with this if statement? If i pass not empty values i still don't get in to the if block

Both val1 and val2 have values:

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}```
</div>
</div>
</p>

<p><code>val1</code> is empty and <code>val2</code> has a value:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let val1 = ''
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}</code>```

答:
You want to use && and not ||, because what you are currently saying is:

Val cannot be null or it cannot be empty.

As long as one of those evaluates to true, it will enter the if statement. Since an empty string does not equal null, the null check is true which means one of the checks evaluated to true and would enter the if statement. If it was vise versa, then the empty string would evaluate to true and again it would enter the if statement.

This would make more sense if you were checking for equality and would then read as follows:

Val can be null or it can be empty.

However, that isn't what you are looking for, so what you want to say is:

Val cannot be null AND it cannot be empty.

When testing a single variable to not equal multiple values use an && check.

When testing a single variable to equal one of multiple values use an || check.

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null && val1 !== '') && (val2 !== null && val2 !== '')) {
  console.log(val1, val2);
}

val1 = ''

if ((val1 !== null && val1 !== '') && (val2 !== null && val2 !== '')) {
  console.log(val1, val2);
}```

Body:
What is wrong with this if statement? If i pass not empty values i still don't get in to the if block

Both val1 and val2 have values:

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}

val1 is empty and val2 has a value:

let val1 = ''
let val2 = 'medical'

if ((val1 !== null || val1 !== '') && (val2 !== null || val2 !== '')) {

  console.log(val1, val2);
}


问:
ORM vs Handcoded Data Access Layer
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

```
 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)
```

Hand Coded Advantages

```
 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only
```

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

答:
I've been writing and maintaining my own ORM for 8 years now. It started in Java, then translated to C#. I can't imagine writing any database backed system without it. It is way simpler than NHibernate, and doesn't have all its features but it gets the job done and it is quite fast even though it uses reflection extensively, since it replaces XML configuration with reflection over the DAO class definitions.

I'm quite happy with it, and would not use any other approach.

EDIT: regarding SQL injection attacks: a recent system I developed using this ORM was extensively audited and absolutely no injection was permitted. The reason is simple: it generates SQL on the fly and always uses parameters, no string concatenation.

OwnerDisplayName: Frustrating Developments

ContentLicense: CC BY-SA 2.5

Title: ORM vs Handcoded Data Access Layer

Body:
I'm a bit scared to ask this question as it may start a religous war so I want to be really clear on what I'm looking for. I'm looking for a reason(s) why you would or have jumped one way or the other and also for items to add to my lists. I'm looking for the big ticket, big bang items. Also, items specific to a product, maybe, if they are really relevant. At this point I'm trying to evaluate ORM vs Manual not product A vs product B.

ORM Advantages

 - Quick to code and low maintenance (in some/most scenarios)
 - Additional features for "free" (no developer effort)

Hand Coded Advantages

 - More Efficient (at runtime, maybe not at dev time?)
 - Less layers of complexity
 - Most ORMS seem to struggle with being retricted to sprocs only

In the interests of full disclosure, I really don't like the idea of "something" executing code against my database that I can't directly modify, if I see fit but I can see the potentially massive development time advatages of an ORM.

Its probably also worth noting I'm in a .Net world

[edit]
(the question at Using an ORM or plain SQL? seems to answer many of the questions and reinforce the point about performance)

So, to alter my question slightly

Has any built an app using an ORM in the early stages and then gradually replaced with with a handcoded DAL? What were the pitfalls of this approach?

[Further Edit - getting to the heart of the problem now]
Having a website be able to execute any SQL against my database is scary. If all access is through sprocs my database lives in nice, safe, comfortable isolation. Using exclusively sprocs removes a lot of, if not all, SQL injection attack vectors. Any comments on that?

LastEditorDisplayName: Frustrating Developments


问:
CodeIgniter/jQuery - Ajax call returns full html page instead of my echo
In my view I have an ajax call:

```<code>    $(".previous").click(function() {
        $.ajax({
            type: "POST",
            url: "planner/get_cal",
            data: {current_month: current_month},
            success: function(msg){
                alert(msg);
            }

        });
</code>```

the get_cal function in my Planner controller:

```<code>function get_cal()
{
    echo "dinosaurs";
}
</code>```

However, instead of returning "dinosaurs", it returns a full HTML page. I can't figure out why. Thoughts? Thanks a lot.

答:
Try setting the dataType to "text"</p>

```<code>
$.ajax({
  type: "POST",
  url: "planner/get_cal",
  data: {current_month: current_month},
  dataType: "text",
  success: function(msg){
      alert(msg);
  }
});
</code>```

Body:
In my view I have an ajax call:

    $(".previous").click(function() {
        $.ajax({
            type: "POST",
            url: "planner/get_cal",
            data: {current_month: current_month},
            success: function(msg){
                alert(msg);
            }

        });

the get_cal function in my Planner controller:

function get_cal()
{
    echo "dinosaurs";
}

However, instead of returning "dinosaurs", it returns a full HTML page. I can't figure out why. Thoughts? Thanks a lot.

Body:
Try setting the dataType to "text"

$.ajax({
  type: "POST",
  url: "planner/get_cal",
  data: {current_month: current_month},
  dataType: "text",
  success: function(msg){
      alert(msg);
  }
});


问:
Laravel Intervention Image GD library extension
First of all, I am sorry if my question may be too vague. So, I will try to clarify my question as much as possible.

I am currently developing a Laravel application, and I am trying to use Intervention Image Facade. When I tried to use it to test an upload, I got the following error:-

```<code>NotSupportedException in Driver.php line 16: GD Library extension not available with this PHP installation.
</code>```

So, as I would try to do, I installed the GD library using sudo apt-get install libgd3 and the php gd driver using sudo apt-get php5.6-gd. However, this did not work, and the same error keeps popping up in laravel. What have I clearly missed, and what should I follow next?

Edit 1.  I used the following command to see if php actually supports gd driver : - php -i | grep -i --color gd

The following result came: -

```<code>/etc/php/5.6/cli/conf.d/20-gd.ini,
gd
GD Support => enabled
GD headers Version => 2.2.3
GD library Version => 2.2.3
gd.jpeg_ignore_warning => 0 => 0
GDM_LANG => en_US
GDMSESSION => ubuntu
_SERVER["GDM_LANG"] => en_US
_SERVER["GDMSESSION"] => ubuntu
</code>```

Hope this helps even more.

EDIT 2 Thanks to all who answered. I found my solution in Mayank Pandey's answer.

答:
After all the above failed, I upgraded to php 7.3.x from php7.2.x, using

```<code>    sudo apt install php
</code>```

then installed gd

```<code>    sudo apt-get install php7.3-gd
</code>```

to be sure, restart the apache server or xampp(as was for my case) and also restart php artisan serve.

Using the appropriate php.ini file, ensure that "extension=php_gd2.dll" is enabled by removing the semicolon that appears before it.

then check what you have on grep through

```<code>    php -i | grep -i --color gd
</code>```

it should look like this.

```<code>/etc/php/7.3/cli/conf.d/20-gd.ini,
gd
GD Support => enabled
GD headers Version => 2.2.5
GD library Version => 2.2.5
gd.jpeg_ignore_warning => 1 => 1
GDM_LANG => C.UTF-8
GDMSESSION => gnome
XAUTHORITY => /run/user/1000/gdm/Xauthority
$_SERVER['GDM_LANG'] => C.UTF-8
$_SERVER['GDMSESSION'] => gnome
$_SERVER['XAUTHORITY'] => /run/user/1000/gdm/Xauthority
</code>```

in the case that after this, you get an error concerning drivers on your laravel app, this answer may help solve it.Laravel 5 PDOException Could Not Find Driver

I hope this helps you.

Body:
First of all, I am sorry if my question may be too vague. So, I will try to clarify my question as much as possible.

I am currently developing a Laravel application, and I am trying to use Intervention Image Facade. When I tried to use it to test an upload, I got the following error:-

NotSupportedException in Driver.php line 16: GD Library extension not available with this PHP installation.

So, as I would try to do, I installed the GD library using sudo apt-get install libgd3 and the php gd driver using sudo apt-get php5.6-gd. However, this did not work, and the same error keeps popping up in laravel. What have I clearly missed, and what should I follow next?

Edit 1.  I used the following command to see if php actually supports gd driver : - php -i | grep -i --color gd

The following result came: -

/etc/php/5.6/cli/conf.d/20-gd.ini,
gd
GD Support => enabled
GD headers Version => 2.2.3
GD library Version => 2.2.3
gd.jpeg_ignore_warning => 0 => 0
GDM_LANG => en_US
GDMSESSION => ubuntu
_SERVER["GDM_LANG"] => en_US
_SERVER["GDMSESSION"] => ubuntu

Hope this helps even more.

EDIT 2 Thanks to all who answered. I found my solution in Mayank Pandey's answer.

Body:
After all the above failed, I upgraded to php 7.3.x from php7.2.x, using

    sudo apt install php

then installed gd

    sudo apt-get install php7.3-gd

to be sure, restart the apache server or xampp(as was for my case) and also restart php artisan serve.

Using the appropriate php.ini file, ensure that "extension=php_gd2.dll" is enabled by removing the semicolon that appears before it.

then check what you have on grep through

    php -i | grep -i --color gd

it should look like this.

/etc/php/7.3/cli/conf.d/20-gd.ini,
gd
GD Support => enabled
GD headers Version => 2.2.5
GD library Version => 2.2.5
gd.jpeg_ignore_warning => 1 => 1
GDM_LANG => C.UTF-8
GDMSESSION => gnome
XAUTHORITY => /run/user/1000/gdm/Xauthority
$_SERVER['GDM_LANG'] => C.UTF-8
$_SERVER['GDMSESSION'] => gnome
$_SERVER['XAUTHORITY'] => /run/user/1000/gdm/Xauthority

in the case that after this, you get an error concerning drivers on your laravel app, this answer may help solve it.Laravel 5 PDOException Could Not Find Driver

I hope this helps you.


问:
Find a row and its index then delete this row using index
I would looking for a way to basically delete, step by step, a specific row.

```<code>      categorie     note    nbavis  taille      nbdll       type    prix    genre
10  ART_AND_DESIGN  4.1     159     19000000    10000       Free    0       Art & Design
15  ART_AND_DESIGN  3.9     967     14000000    500000      Free    0       Art & Design
16  ART_AND_DESIGN  4.7     87510   8.7000000   5000000     Free    0       Art & Design
17  ART_AND_DESIGN  4.5     215644  25000000    50000000    Free    0       Art & Design
28  ART_AND_DESIGN  4.3     967     2.8000000   100000      Free    Everyone Art & Design
</code>```

After deleting some row because of NaN, id's are different than index.
So, I used :

```<code>app.loc[app['prix']=='Everyone',:]
</code>```

To learn more about which row contains "Everyone" in the column "prix".

Now I would like to find the index of this row which is different from 28 (On this example, it's 4, python count from 0 right ?)

I tried :

```<code>app.index[app['prix'] == 'Everyone'].tolist()
</code>```

But the result give me [28].
Then I tried

```<code>app.loc[app.index==28]
</code>```

Same result.
app.index[28] will told me :

```<code>IndexError: index 28 is out of bounds for axis 0 with size 5
</code>```

I'm pretty sure I have missed something. There are many ways to do it, but I would like to do it with this approach. For exemple .drop , del , ...
There are many topics, but none fits with these conditions. Maybe it's not possible. How would you do this with few code lines?

Thanks

EDIT :
There are the solutions I was looking for :

♣ Reset the Index

```<code>app = app.reset_index()
</code>```

♣ Find the rows (and the index)

```<code>app.loc[app['prix']=='Everyone',:]
</code>```

♣ Delete this row using the index

```<code>app = app.drop(4795)
</code>```

◘ Other solution was : app.drop([28])
Thanks to this community. And thanks for the Edit of my topic, my english is horrible ahah.

答:
Try this:

```<code>for r in app.iterrows():
     if r[1]['prix']=='Everyone':
           print(r[0])
</code>```

With iterrows() method you can print the index by r[0], and the columns will be in r[1],
if yoy want to set a column as a index you can use:

```<code>app.set_index("Column Name")
</code>```

Body:
I would looking for a way to basically delete, step by step, a specific row.

      categorie     note    nbavis  taille      nbdll       type    prix    genre
10  ART_AND_DESIGN  4.1     159     19000000    10000       Free    0       Art & Design
15  ART_AND_DESIGN  3.9     967     14000000    500000      Free    0       Art & Design
16  ART_AND_DESIGN  4.7     87510   8.7000000   5000000     Free    0       Art & Design
17  ART_AND_DESIGN  4.5     215644  25000000    50000000    Free    0       Art & Design
28  ART_AND_DESIGN  4.3     967     2.8000000   100000      Free    Everyone Art & Design

After deleting some row because of NaN, id's are different than index.
So, I used :

app.loc[app['prix']=='Everyone',:]

To learn more about which row contains "Everyone" in the column "prix".

Now I would like to find the index of this row which is different from 28 (On this example, it's 4, python count from 0 right ?)

I tried :

app.index[app['prix'] == 'Everyone'].tolist()

But the result give me [28].
Then I tried

app.loc[app.index==28]

Same result.
app.index[28] will told me :

IndexError: index 28 is out of bounds for axis 0 with size 5

I'm pretty sure I have missed something. There are many ways to do it, but I would like to do it with this approach. For exemple .drop , del , ...
There are many topics, but none fits with these conditions. Maybe it's not possible. How would you do this with few code lines?

Thanks

EDIT :
There are the solutions I was looking for :

♣ Reset the Index

app = app.reset_index()

♣ Find the rows (and the index)

app.loc[app['prix']=='Everyone',:]

♣ Delete this row using the index

app = app.drop(4795)

◘ Other solution was : app.drop([28])
Thanks to this community. And thanks for the Edit of my topic, my english is horrible ahah.

Body:
Try this:

for r in app.iterrows():
     if r[1]['prix']=='Everyone':
           print(r[0])

With iterrows() method you can print the index by r[0], and the columns will be in r[1],
if yoy want to set a column as a index you can use:

app.set_index("Column Name")


问:
How to manipulate numeric output with variable-like properties based on user input
I am computing digits of pi based on Ramanujan's formula, and I'm allowing the user to control the number of iterations of the summation. I want the number of decimal places to change based on the desired number of iterations.

Python doesn't allow numeric output to change as far as I know with using:

result = 3.14159...

a = 50

b = 48

print('result = %a.bf' % result')

But based on number of iterations the precision of pi sky rockets, but for small number of iterations (1, 2, ...) not many decimal places are needed.

What I would like to happen is the following:

```<code>while True:

   k = int(input("How many iterations do you want? "))

   num_digits = k * 10
   a = num_digits
   b = num_digits - 2

   result = calculate_pi(k)

   print('result = %a.bf' % result')
   .
   .
   .

</code>```

I understand that this is not how Python's numeric formatting works but I don't know how to translate what I want to happen in English into the script.

答:
python3.6+:

```<code>print(f'result = %{a}.{b}f' % result)
</code>```

older python:

```<code>print(('result = %%%d.%df' % (a, b)) % result) # %% is used to escape '%'
print('results = %{}.{}f'.format(a, b) % a)
</code>```

In both cases, the idea is to first create a string with the right placeholder you want (%X.Yf) and then using it in a second pass.

Body:
I am computing digits of pi based on Ramanujan's formula, and I'm allowing the user to control the number of iterations of the summation. I want the number of decimal places to change based on the desired number of iterations.

Python doesn't allow numeric output to change as far as I know with using:

result = 3.14159...

a = 50

b = 48

print('result = %a.bf' % result')

But based on number of iterations the precision of pi sky rockets, but for small number of iterations (1, 2, ...) not many decimal places are needed.

What I would like to happen is the following:

while True:

   k = int(input("How many iterations do you want? "))

   num_digits = k * 10
   a = num_digits
   b = num_digits - 2

   result = calculate_pi(k)

   print('result = %a.bf' % result')
   .
   .
   .

I understand that this is not how Python's numeric formatting works but I don't know how to translate what I want to happen in English into the script.

Body:
python3.6+:

print(f'result = %{a}.{b}f' % result)

older python:

print(('result = %%%d.%df' % (a, b)) % result) # %% is used to escape '%'
print('results = %{}.{}f'.format(a, b) % a)

In both cases, the idea is to first create a string with the right placeholder you want (%X.Yf) and then using it in a second pass.


答:
You need to change the || to && in your if statement.

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null && val1 !== '') && (val2 !== null && val2 !== '')) {

  console.log(val1, val2);
}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let val1 = ''
let val2 = 'medical'

if ((val1 !== null && val1 !== '') && (val2 !== null && val2 !== '')) {

  console.log(val1, val2);
}</code>```

This should solve your problem.

Title: Checking for null and empty values in javascript

Body:
You need to change the || to && in your if statement.

let val1 = 'category'
let val2 = 'medical'

if ((val1 !== null && val1 !== '') && (val2 !== null && val2 !== '')) {

  console.log(val1, val2);
}

let val1 = ''
let val2 = 'medical'

if ((val1 !== null && val1 !== '') && (val2 !== null && val2 !== '')) {

  console.log(val1, val2);
}

This should solve your problem.


问:
.net construct / pattern to block by segment of code, not by thread
Is there a construct or pattern in .net that defines a segment of code that can be accessed by multiple threads but blocks if any thread is in some other segment of code (and vice-versa)?  For example:

```<code>void SomeOperationA()
{
    Block( B )
    {
        Segment1:
        ... only executes if no threads are executing in Segment2 ...
    }
}

}

void SomeOperationB()
{
    Block( A )
    {
        Segment2:
        ... only executes if no threads are executing in Segment1 ...
    }
}
</code>```

Edit

Several threads should be able to access Segment1/Segment2 simultaneously (only one Segment being "active" at a time.  If Segment 1 is executing, another thread should be able to execute Segment1 but not Segment2.

Edit 2

Given all the comments/replies and my real-world scenario, I realize that its a bit crazy to require Segment2 to be accessed by multiple-threads.

答:
This is a rather unusual model for protecting resources from improper concurrent access. I would first consider whether your use case can't be translated into an equivalent scenario where you can use simple locks. If you could provide more details on why you need this kind of locking scheme it may be possible for the community to offer other ideas.

To address your specific question, nothing in .NET or even Win32 directly supports this locking model, however you may be able to build it out of other primitives. I would look at using a pair of ReaderWriterLockSlim instances to protect each resource. As threads enter SegmentA you aquire a write read lock on A and a write lock B ... and vice verse for threads entering SegmentB. This would allow multiple threads to execute within each segment, but not at the same time.

EDIT: Given your reply in the comments to your question, I am more convinced you need to look at using a Reader/Writer locking model. What you're looking for is a way to protect a resource such that when "writers" are doing work (serializing the dictionary) no readers or other writers can enter and when "readers" are doing work they don't block each other but block all other writers. This is a classic case for reader/writer locks.

EDIT 2: Now that I've have more time, I think it's worth elaborating on one points. The way to think about locks is that they protect data resources (memory, files, etc) rather than areas of code. The fact that we need to define critical sections of code that only one thread at a time can enter is an implementation detail that one shouldn't confuse with how shared resources are used (and must be protected). In your question, the focus on how to control which threads can enter which section of code misdirects from the real problem: which data resources you are trying to protect against what kind of changes. Once you look at the problem from that perspective, it makes it clearer which implementation paradigms make sense.

Here are some good resources on reader/writer locking models:

http://msdn.microsoft.com/en-us/magazine/cc163599.aspx

http://msdn.microsoft.com/en-us/library/bz6sth95.aspx

http://blogs.msdn.com/b/vancem/archive/2006/03/29/564854.aspx

Body:
Is there a construct or pattern in .net that defines a segment of code that can be accessed by multiple threads but blocks if any thread is in some other segment of code (and vice-versa)?  For example:

void SomeOperationA()
{
    Block( B )
    {
        Segment1:
        ... only executes if no threads are executing in Segment2 ...
    }
}

}

void SomeOperationB()
{
    Block( A )
    {
        Segment2:
        ... only executes if no threads are executing in Segment1 ...
    }
}

Edit

Several threads should be able to access Segment1/Segment2 simultaneously (only one Segment being "active" at a time.  If Segment 1 is executing, another thread should be able to execute Segment1 but not Segment2.

Edit 2

Given all the comments/replies and my real-world scenario, I realize that its a bit crazy to require Segment2 to be accessed by multiple-threads.


问:
typescript convert to asynchronous
I have the following functions:

```<code>function f (x : number): number {
 return 1/x
}

function g (x : number): number {
 return x*x
}

function h (x : number): number {
 return f(g(x))
}
</code>```

I am trying to convert h (g and f too if needed) to an asynchronous function just with callbacks and not with promises but I am stuck with that.

I know that each function should have a function callback as a parameter but I am not sure how to do that.

答:
We can start with f that provides an example of error management:

```<code>function f(x: number, cb: (err: any, result?: number) => void): void {
  if (x === 0)
    cb(new Error("Cannot call 'f' with zero"))
  else
    cb(null, 1/x)
}
</code>```

Here is how to use it:

```<code>f(5, (err, result) => {
  if (!err)
    console.log("… do something with:", result)
})
</code>```

The g function is easy:

```<code>function g(x: number, cb: (err: any, result?: number) => void): void {
    cb(null, x * x)
}
</code>```

And h becomes to look like to a good old-fashioned callback hell:

```<code>function h(x: number, cb: (err: any, result?: number) => void): void {
    g(x, (err, gResult) => {
        if (err)
            cb(err)
        else
            f(gResult, cb)
    })
}
</code>```

Thanks for this moment of nostalgia.

Title: typescript convert to asynchronous

Body:
I have the following functions:

function f (x : number): number {
 return 1/x
}

function g (x : number): number {
 return x*x
}

function h (x : number): number {
 return f(g(x))
}

I am trying to convert h (g and f too if needed) to an asynchronous function just with callbacks and not with promises but I am stuck with that.

I know that each function should have a function callback as a parameter but I am not sure how to do that.

Body:
We can start with f that provides an example of error management:

function f(x: number, cb: (err: any, result?: number) => void): void {
  if (x === 0)
    cb(new Error("Cannot call 'f' with zero"))
  else
    cb(null, 1/x)
}

Here is how to use it:

f(5, (err, result) => {
  if (!err)
    console.log("… do something with:", result)
})

The g function is easy:

function g(x: number, cb: (err: any, result?: number) => void): void {
    cb(null, x * x)
}

And h becomes to look like to a good old-fashioned callback hell:

function h(x: number, cb: (err: any, result?: number) => void): void {
    g(x, (err, gResult) => {
        if (err)
            cb(err)
        else
            f(gResult, cb)
    })
}

Thanks for this moment of nostalgia.


问:
Connect to Google Cloud postgres SQl from Google App Engine Custom flex environment
I have a Java application for which the database configuration is read through the following file:

db.properties

```<code>dataSourceClassName = org.postgresql.ds.PGSimpleDataSource
dataSource.serverName = 127.0.0.1
dataSource.databaseName = <db name>
dataSource.portNumber = 5432
dataSource.user = postgres
dataSource.password = <password>
maximumPoolSize = 5
</code>```

I have built a Dockerfile which

creates a container for the java application

exposes ports 8080, and 5432

starts the webserver with ENTRYPOINT ["mvn", "jetty:run"]

My app.yaml file for flex environment:

```<code>runtime: custom
env: flex

network:
  instance_tag: nlpapigae
  session_affinity: true
#  forwarded_ports:
#    - 8080
resources:
  cpu: 8
  memory_gb: 40
  disk_size_gb: 32
automatic_scaling:
  min_num_instances: 1
  max_num_instances: 10
  cool_down_period_sec: 180
  cpu_utilization:
    target_utilization: .75
beta_settings:
  cloud_sql_instances: <instance name>=tcp:5432
env_variables:
  POSTGRES_HOST: "/cloudsql/<instance name>"
  POSTGRES_DB: <db name>
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: <password>
</code>```

When I deploy the application, I get the error that Postgres db is not reachable. How do i get this right?

答:
Try enabling the Cloud SQL Admin API. If you are connecting between multiple projects, check out the Connecting to App Engine page to ensure your service account has the correct permissions. </p>

<p>As a Java user, you may also be interested in the Cloud SQL JDBC Socket Factory. </p>

Body:
I have a Java application for which the database configuration is read through the following file:

db.properties

dataSourceClassName = org.postgresql.ds.PGSimpleDataSource
dataSource.serverName = 127.0.0.1
dataSource.databaseName = <db name>
dataSource.portNumber = 5432
dataSource.user = postgres
dataSource.password = <password>
maximumPoolSize = 5

I have built a Dockerfile which

creates a container for the java application

exposes ports 8080, and 5432

starts the webserver with ENTRYPOINT ["mvn", "jetty:run"]

My app.yaml file for flex environment:

runtime: custom
env: flex

network:
  instance_tag: nlpapigae
  session_affinity: true
#  forwarded_ports:
#    - 8080
resources:
  cpu: 8
  memory_gb: 40
  disk_size_gb: 32
automatic_scaling:
  min_num_instances: 1
  max_num_instances: 10
  cool_down_period_sec: 180
  cpu_utilization:
    target_utilization: .75
beta_settings:
  cloud_sql_instances: <instance name>=tcp:5432
env_variables:
  POSTGRES_HOST: "/cloudsql/<instance name>"
  POSTGRES_DB: <db name>
  POSTGRES_USER: postgres
  POSTGRES_PASSWORD: <password>

When I deploy the application, I get the error that Postgres db is not reachable. How do i get this right?

Body:
Try enabling the Cloud SQL Admin API. If you are connecting between multiple projects, check out the Connecting to App Engine page to ensure your service account has the correct permissions.

As a Java user, you may also be interested in the Cloud SQL JDBC Socket Factory.


问:
Angular blocking (synchronize) http call
I have an Angular app which renews the jwt every 2 mins. There is a potential issue is, while the jwt is renewing, user may do some action will fire another http call go with the old jwt.

How can I ensure the renewjwt() is finished before another potential http calls fire?

My initial idea is toggling a global flag before renewjwt() call and in the callback function that when it is done.

Is there a good way to accomplish this with native Angular or rxjs?

答:
you can use delayWhen operator which will delay emitted values base on another observable.

for that you can create observable like following :

```<code>function renewTokenIfNeeded$(): Observable<void> {
  console.log('Renew token start');
  /**
   * Here you should have have :
   * If current token is valid,
   * ---- then return of(number),
   * else
   * ---- then return this.http.post([...])
   */
  // for demonstration prupose i always renew the token.
  return of(null).pipe(delay(
    Math.floor(Math.random() * 1000) + 1
  ), tap(() => console.log('renew token stop')));

}

/**
 * Each 100 ms i trigger new dummy http request. By exhaustMap i will ignore all future "interval" emission until my dummy http request is complete stream.
 */
const renewTokensTimer$ = interval(100).pipe(exhaustMap(() => renewTokenIfNeeded$()));
</code>```

data stream will looks like :

```<code>|...|...|...|................|...|...|...|
</code>```

1/ Like this i have stream which will emit new number each 100ms until you consider your current as dirty.

2/ Then it will perform the http request to fetch the new one.

3/ The interval source observable will not emit new value until you exhaust the http request.

then you can simply use it like following :

```<code>of(null) // Create dummy observable.
    .pipe(delayWhen(() => renewTokenIfNeeded$())) // Delay it if token have to be renew.
    .pipe(mergeMap(() => myRegularHttpRequest$)) // perform my http request, i am 100% here i have fresh JWT
    .subscribe(console.log) // You can safely consume the API answer.
</code>```

live poc

Body:
you can use delayWhen operator which will delay emitted values base on another observable.

for that you can create observable like following :

function renewTokenIfNeeded$(): Observable<void> {
  console.log('Renew token start');
  /**
   * Here you should have have :
   * If current token is valid,
   * ---- then return of(number),
   * else
   * ---- then return this.http.post([...])
   */
  // for demonstration prupose i always renew the token.
  return of(null).pipe(delay(
    Math.floor(Math.random() * 1000) + 1
  ), tap(() => console.log('renew token stop')));

}

/**
 * Each 100 ms i trigger new dummy http request. By exhaustMap i will ignore all future "interval" emission until my dummy http request is complete stream.
 */
const renewTokensTimer$ = interval(100).pipe(exhaustMap(() => renewTokenIfNeeded$()));

data stream will looks like :

|...|...|...|................|...|...|...|

1/ Like this i have stream which will emit new number each 100ms until you consider your current as dirty.

2/ Then it will perform the http request to fetch the new one.

3/ The interval source observable will not emit new value until you exhaust the http request.

then you can simply use it like following :

of(null) // Create dummy observable.
    .pipe(delayWhen(() => renewTokenIfNeeded$())) // Delay it if token have to be renew.
    .pipe(mergeMap(() => myRegularHttpRequest$)) // perform my http request, i am 100% here i have fresh JWT
    .subscribe(console.log) // You can safely consume the API answer.

live poc


问:
Copy multiple files from one folder to another
I am trying to copy multiple files from one folder to another using the following code

```<code>val pathCorpus = Files.copy(
  Paths.get("src/main/resources/corpusDirectory/corpus.mallet"),
  Paths.get("src/main/resources/corpus.mallet"),
  StandardCopyOption.REPLACE_EXISTING
)

val pathInferencer = Files.copy(
  Paths.get("src/main/resources/corpusDirectory/inferencer"),
  Paths.get("src/main/resources/inferencer"),
  StandardCopyOption.REPLACE_EXISTING
)
</code>```

As I need to copy two files, I am using Files.copy twice.
The code is working but I believe there should be better way to write the code, like copying files recursively.

答:
I like to use bash

```<code>import scala.sys.process.stringToProcess
val copyFiles: String = s"cp -R src/main/resources/corpusDirectory/ src/main/resources/".!!
</code>```

And you can use bash cp: https://www.cyberciti.biz/faq/copy-command/

Body:
I am trying to copy multiple files from one folder to another using the following code

val pathCorpus = Files.copy(
  Paths.get("src/main/resources/corpusDirectory/corpus.mallet"),
  Paths.get("src/main/resources/corpus.mallet"),
  StandardCopyOption.REPLACE_EXISTING
)

val pathInferencer = Files.copy(
  Paths.get("src/main/resources/corpusDirectory/inferencer"),
  Paths.get("src/main/resources/inferencer"),
  StandardCopyOption.REPLACE_EXISTING
)

As I need to copy two files, I am using Files.copy twice.
The code is working but I believe there should be better way to write the code, like copying files recursively.

Body:
I like to use bash

import scala.sys.process.stringToProcess
val copyFiles: String = s"cp -R src/main/resources/corpusDirectory/ src/main/resources/".!!

And you can use bash cp: https://www.cyberciti.biz/faq/copy-command/


问:
Byte Array to String Conversion Formatting Issues
I'm using a network stream to transmit data from a text box in windows forms, when this data is read I write it out to the console, while the transmitted data outputs fine it seems to generate a strange gap that I haven't been able to identify as a new line or as a lot of spaces.

I've tried using the Replace function to replace spaces ' ' and new lines '\n' with null characters but this seems to have not fixed the problem and there is still an abnormal gap between the read data and whatever comes after it.

The output should say:
John Doe joined

But instead says:
John Doe

                                                                                joined

```<code>TcpClient clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
clientSocket.GetStream().Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);
string dataFromClient = Encoding.ASCII.GetString(bytesFrom);
Console.WriteLine($"{dataFromClient} joined");
</code>```

答:
Your code is trying to decode the entire bytesFrom array, whether it contains data or not. Stream.Read doesn't overwrite the entire buffer, it overwrites only the bytes it needs and returns the number of bytes.

This means that the first time you try to decode the buffer you'll be trying to decode the 0s it contains as well. The second time you may end up decoding mixed old and new data.

You should change your code to :

```<code>byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
using(var stream=clientSocket.GetStream())
{
    var read=stream.Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);
    var text = Encoding.ASCII.GetString(bytesFrom,0,read);
    Console.WriteLine("Actual Text: {0}",text);
}
</code>```

Another problem is that Encoding.ASCII is the 7-bit US-ASCII codepage. Any character that isn't contained in that codepage will be lost and replaced by ?. .NET strings are Unicode (UTF16). Use the UTF8 encoding at least, both on the server and client to avoid losing data

Body:
I'm using a network stream to transmit data from a text box in windows forms, when this data is read I write it out to the console, while the transmitted data outputs fine it seems to generate a strange gap that I haven't been able to identify as a new line or as a lot of spaces.

I've tried using the Replace function to replace spaces ' ' and new lines '\n' with null characters but this seems to have not fixed the problem and there is still an abnormal gap between the read data and whatever comes after it.

The output should say:
John Doe joined

But instead says:
John Doe

                                                                                joined

TcpClient clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
clientSocket.GetStream().Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);
string dataFromClient = Encoding.ASCII.GetString(bytesFrom);
Console.WriteLine($"{dataFromClient} joined");

Body:
Your code is trying to decode the entire bytesFrom array, whether it contains data or not. Stream.Read doesn't overwrite the entire buffer, it overwrites only the bytes it needs and returns the number of bytes.

This means that the first time you try to decode the buffer you'll be trying to decode the 0s it contains as well. The second time you may end up decoding mixed old and new data.

You should change your code to :

byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
using(var stream=clientSocket.GetStream())
{
    var read=stream.Read(bytesFrom, 0, clientSocket.ReceiveBufferSize);
    var text = Encoding.ASCII.GetString(bytesFrom,0,read);
    Console.WriteLine("Actual Text: {0}",text);
}

Another problem is that Encoding.ASCII is the 7-bit US-ASCII codepage. Any character that isn't contained in that codepage will be lost and replaced by ?. .NET strings are Unicode (UTF16). Use the UTF8 encoding at least, both on the server and client to avoid losing data


问:
Convert a string made from array toString() back to Array
I converted an array to a string and added it to a TextArea. The user edited the TextArea and I need to now update the array by calling in the same string of data I first produced. How would you do this?

The string which I have produced and need to convert back to an array is:

```<code>{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}
</code>```

I tried to use the JSON Parser JSON.parse(text)

答:
Format your string:

const text = '{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}'

console.log(JSON.parse(`[ ${text}]`))```

Body:
I converted an array to a string and added it to a TextArea. The user edited the TextArea and I need to now update the array by calling in the same string of data I first produced. How would you do this?

The string which I have produced and need to convert back to an array is:

{"color":"red","x":218,"y":-11,"width":60,"height":60},{"color":"blue","cx":114,"cy":83,"radius":30}

I tried to use the JSON Parser JSON.parse(text)


问:
How to extract digest algorithm from signed dll using PowerShell?
I have a dll file which is digitally signed. I need to write a PowerShell command which could get me the Digest Algorithm that is used for the Digital Signature.

Digest Algorithm info I need:

I tried with Get-AuthenticodeSignature but this didn't get me the Digest Algorithm info.

After running the following command I get the below result.

```<code>Get-AuthenticodeSignature "C:\Program Files\Application Verifier\vrfauto.dll" | Format-List
</code>```

Results of above:

答:
So what you are looking for is

```<code>Get-AuthenticodeSignature | %{
    $_.SignerCertificate.SignatureAlgorithm.FriendlyName
}
</code>```

Lets go over how we got to there. First i find a file that has a Digital Signature. I will use PowerShell-6.1.2-win-x64.msi for this example.

```<code>Get-AuthenticodeSignature -FilePath C:\test\PowerShell-6.1.2-win-x64.msi | get-member
</code>```

We see there is a object for the SignerCertificate

```<code>SignerCertificate      Property   System.Security.Cryptography.X509Certificates.X509Certificate2 SignerCertificate {get;}
</code>```

So lets see what that holds

```<code>Get-AuthenticodeSignature -FilePath C:\test\PowerShell-6.1.2-win-x64.msi | %{
    $_.SignerCertificate | get-member
}
</code>```

Now we see there is a SignatureAlgorithm property

```<code>SignatureAlgorithm              Property       System.Security.Cryptography.Oid SignatureAlgorithm {get;}
</code>```

Now we dig one more deep

```<code>Get-AuthenticodeSignature -FilePath C:\test\PowerShell-6.1.2-win-x64.msi | %{
    $_.SignerCertificate.SignatureAlgorithm | get-member
}
</code>```

We get :

```<code>FriendlyName Property   string FriendlyName {get;set;}
Value        Property   string Value {get;set;}
</code>```

We can see there both strings so we test out which is better for us...turns out its friendly name :

```<code>Get-AuthenticodeSignature -FilePath C:\test\PowerShell-6.1.2-win-x64.msi | %{
    $_.SignerCertificate.SignatureAlgorithm.FriendlyName
}
</code>```

Returns

```<code>sha256RSA
</code>```

Body:
I have a dll file which is digitally signed. I need to write a PowerShell command which could get me the Digest Algorithm that is used for the Digital Signature.

Digest Algorithm info I need:

I tried with Get-AuthenticodeSignature but this didn't get me the Digest Algorithm info.

After running the following command I get the below result.

Get-AuthenticodeSignature "C:\Program Files\Application Verifier\vrfauto.dll" | Format-List

Results of above:

Body:
So what you are looking for is

Get-AuthenticodeSignature | %{
    $_.SignerCertificate.SignatureAlgorithm.FriendlyName
}

Lets go over how we got to there. First i find a file that has a Digital Signature. I will use PowerShell-6.1.2-win-x64.msi for this example.

Get-AuthenticodeSignature -FilePath C:\test\PowerShell-6.1.2-win-x64.msi | get-member

We see there is a object for the SignerCertificate

SignerCertificate      Property   System.Security.Cryptography.X509Certificates.X509Certificate2 SignerCertificate {get;}

So lets see what that holds

Get-AuthenticodeSignature -FilePath C:\test\PowerShell-6.1.2-win-x64.msi | %{
    $_.SignerCertificate | get-member
}

Now we see there is a SignatureAlgorithm property

SignatureAlgorithm              Property       System.Security.Cryptography.Oid SignatureAlgorithm {get;}

Now we dig one more deep

Get-AuthenticodeSignature -FilePath C:\test\PowerShell-6.1.2-win-x64.msi | %{
    $_.SignerCertificate.SignatureAlgorithm | get-member
}

We get :

FriendlyName Property   string FriendlyName {get;set;}
Value        Property   string Value {get;set;}

We can see there both strings so we test out which is better for us...turns out its friendly name :

Get-AuthenticodeSignature -FilePath C:\test\PowerShell-6.1.2-win-x64.msi | %{
    $_.SignerCertificate.SignatureAlgorithm.FriendlyName
}

Returns

sha256RSA


问:
Find dependant (reverse dependencies) in maven project
I'm trying to find a command that does the opposite of mvn dependency:tree. I want to find out all the projects that depend on a specific module. As trivial as it may sound, I couldn't find such thing.

The use case is in order to find, in a very large project, if I can delete a module or if there are other modules that use it as their dependency.

答:
This is something that is not part of Maven. But it can be implemented in Maven repositories like Nexus and Bintray. The closest I've found is in Bintray and its Build Integration.

But since my clients are using different Maven repositories I needed something that works for any repository. So I created Pom Dependency Analyzer Web that can keep track of dependents, and dependencies.


问:
How do I obtain and set-up a "messaging provider" for a JAXM client to call an asynchronous SOAP API?
I am trying to use JAXM to create a client that would call a third-party asynchronous SOAP API.  According to the JAXM documentation (https://docs.oracle.com/cd/E19644-01/817-5452/wsgjaxm.html#wp41528), a "messaging provider" is required for asynchronous calls.

I see that I would need to use the ProviderConnectionFactory for asynchronous calls (http://www.inf.fu-berlin.de/lehre/SS03/19560-P/Docs/JWSDP/tutorial/doc/JAXM4.html), but I don't know how to obtain (and set-up) a "messaging provider".

答:
You need to contact your service provider.

There are several asynchronous queuing systems available and you will need to use the same one as your service provider.

Having installed the appropriate software you will also need to configure the a connection to the service.


问:
How to display the today date in contact form 7 without datepicker
i want to display the current date (today date the date off submission of the form)  in field date in contact form 7  without choosing it using the datepicker,i want also to disable the datepicker if it's possible.please help.</p>

答:
You have to add this script.

```<code><script>
jQuery(function ($) {
   var now = new Date();
   var day = ("0" + now.getDate()).slice(-2);
   var month = ("0" + (now.getMonth() + 1)).slice(-2);
   var today = now.getFullYear()+"-"+(month)+"-"+(day);
   $('#MydatePicker').val(today);
   $("#MydatePicker").attr("min", today);
});
</script>

[date* your-date class:required id:MydatePicker]
</code>```

Please check it.

Body:
You have to add this script.

<script>
jQuery(function ($) {
   var now = new Date();
   var day = ("0" + now.getDate()).slice(-2);
   var month = ("0" + (now.getMonth() + 1)).slice(-2);
   var today = now.getFullYear()+"-"+(month)+"-"+(day);
   $('#MydatePicker').val(today);
   $("#MydatePicker").attr("min", today);
});
</script>

[date* your-date class:required id:MydatePicker]

Please check it.


问:
How to move my border-top to the very top of the page?
I'm trying to make an hover effects on my nav bar, I want to have a line on top of the li where your cursor is.

I've given the li a border-top property but i need the line to be at the very top of the page not directly on top of the li.

#liste li:hover{
    border-top: 3px solid;
    color: #5CABD1;
}
```

I already know the problem is the border top property but i dont know others way to put a line on top of my li. Here is a photo of my nav bar and the current border-top effect.

答:
```<code><ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<style>
 ul {
  list-style-type: none;
  margin-top: 60px;
  padding: 0;
  overflow: hidden;
 }

 li {
  float: left;
 }

 li a {
 display: block;
 padding: 8px;
 background-color: #dddddd;
 text-decoration:none
}
li a:hover:before{
  content:'';
  position:absolute;
  top:10px;
  border-top:2px solid red;
  width:40px;
  height:1px;
}
</style>
</code>```

You can use the pseudo element to do it . Here is a demo that works on hover
https://jsfiddle.net/Lnso4u6z/3/

Body:
I'm trying to make an hover effects on my nav bar, I want to have a line on top of the li where your cursor is.

I've given the li a border-top property but i need the line to be at the very top of the page not directly on top of the li.

#liste li:hover{
    border-top: 3px solid;
    color: #5CABD1;
}

I already know the problem is the border top property but i dont know others way to put a line on top of my li. Here is a photo of my nav bar and the current border-top effect.

Body:
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<style>
 ul {
  list-style-type: none;
  margin-top: 60px;
  padding: 0;
  overflow: hidden;
 }

 li {
  float: left;
 }

 li a {
 display: block;
 padding: 8px;
 background-color: #dddddd;
 text-decoration:none
}
li a:hover:before{
  content:'';
  position:absolute;
  top:10px;
  border-top:2px solid red;
  width:40px;
  height:1px;
}
</style>

You can use the pseudo element to do it . Here is a demo that works on hover
https://jsfiddle.net/Lnso4u6z/3/