问:
Retrieve both edges and vertices in gremlin json
Hi I'm new to gremlin and need to, basically, get everything current to return as a json file. I'm using Syndeia which has a raw query option. I'm having difficulty figuring out how to get both vertices and edges to output. This is what I have thus far:

g.V().has('sLabel','Artifact').has('_isLatest','TRUE').both()

But I also need

g.V().has('sLabel','Artifact').has('_isLatest','TRUE').bothE()

Which gives me all the edges I need, but not the vertices. I realize that g.V() gives vertices and g.E() gives edges, but am unsure how to obtain both/combine them in the one line query. My json comes back as either

```<code>         "vertices":[] 0 items
         "edges":[...] 90 items
</code>```

Or

```<code>         "vertices":[...] 90 items
         "edges":[] 0 items
</code>```

My next idea is to do multiple queries into java to parse, combine, and manipulate there. I would really like to avoid doing this, but will if it's the only way. Thank you for being kind and understanding and for your help. I appreciate you all.

答:
You can do it as follows,

Just see the code below have demonstrated the following,

Vertex query

Edge query

combined query

converted combined query into valueMap

Converted the combined query valueMap into JSON (using version 3)

Converted the combined query valueMap into JSON (using version 1)

Vertex Query

```<code>    gremlin> g.V(131200).both()
    ==>v[40992]
    ==>v[12336]
    ==>v[20608]
    ==>v[180376]
    gremlin>
</code>```

Edge query

```<code>    gremlin> g.V(131200).bothE()
    ==>e[7rps-2t8g-1fdh-vmo][131200-locatedin->40992]
    ==>e[3qpy-9io-1bf9-2t8g][12336-containedin->131200]
    ==>e[7rbk-fwg-1bf9-2t8g][20608-containedin->131200]
    ==>e[7l03-3v6g-1bf9-2t8g][180376-containedin->131200]
    gremlin>
</code>```

Combined query

```<code>    gremlin>
    gremlin>g.V(131200).project('nodes','edges').by(both().fold()).by(bothE().fold())
    ==>[nodes:[v[40992],v[12336],v[20608],v[180376]],edges:[e[7rps-2t8g-1fdh-vmo][131200-locatedin->40992],e[3qpy-9io-1bf9-2t8g][12336-containedin->131200],e[7rbk-fwg-1bf9-2t8g][20608-containedin->131200],e[7l03-3v6g-1bf9-2t8g][180376-containedin->131200]]]
    gremlin>
</code>```

converted combined query into valueMap

```<code>    gremlin>
    gremlin> output = g.V(131200).project('nodes','edges').by(both().valueMap().fold()).by(bothE().valueMap().fold()).next()
    ==>nodes=[{gId=[0b98e8d5-681d-4155-8aaf-5d86babc0cff], isDeleted=[FALSE], isEntity=[TRUE], name=[TotsukaCDC], basetype=[GeoLocation], source=[RCP-Base], type=[DC], geographyL2DisplayName=[KANAGAWA], geographyL2Name=[KANAGAWA], geographyL4Name=[KNG-TOTSUKAKU-NORTH], geographyL4DisplayName=[KNG-TOTSUKAKU-NORTH], displayName=[TotsukaCDC], latitude=[139.525166], locationType=[CDC], geographyL1Name=[KANTO], geographyL3DisplayName=[YOKOHAMA-SHI], geographyL3Name=[YOKOHAMA-SHI], geographyL1DisplayName=[KANTO], locationCode=[tt], longitude=[35.416535]}, {gId=[90e7407c-cd34-44b0-9bf9-1a8866aac429], isDeleted=[FALSE], isEntity=[TRUE], name=[UHN2KNGcdcttRA01_HundredGigE0/0/0/6], basetype=[Entity], source=[RCP-Base], type=[PhysicalPort], portInUse=[TRUE], portNum=[HundredGigE0/0/0/6]}, {gId=[d0fc7284-4cd8-4cba-8d3d-be3c4ca2ba31], isDeleted=[FALSE], isEntity=[TRUE], name=[UHN2KNGcdcttRA01_Hu0/2/0/35], basetype=[Entity], source=[RCP-Base], type=[PhysicalPort], portInUse=[TRUE], portNum=[Hu0/2/0/35]}, {gId=[2f4f5a3a-b88f-4915-acd5-a1d873507f11], isDeleted=[FALSE], isEntity=[TRUE], name=[UHN2KNGcdcttRA01_HundredGigE0/1/0/6], basetype=[Entity], source=[RCP-Base], type=[PhysicalPort], portInUse=[TRUE], portNum=[HundredGigE0/1/0/6]}]
    ==>edges=[{destName=TotsukaCDC, srcName=UHN2KNGcdcttRA01, gId=1133ff0f-2f4b-4d21-b2d6-fed796ed13f9}, {gId=220d7d2b-8b96-4331-bdc1-50127685946a, destName=UHN2KNGcdcttRA01, srcName=UHN2KNGcdcttRA01_HundredGigE0/0/0/6}, {gId=ebd78fc0-a66c-4033-a776-f80210c02e63, destName=UHN2KNGcdcttRA01, srcName=UHN2KNGcdcttRA01_Hu0/2/0/35}, {srcName=UHN2KNGcdcttRA01_HundredGigE0/1/0/6, gId=0df0f3d0-037a-4caa-9f81-6a6df1c22e25, destName=UHN2KNGcdcttRA01}]
    gremlin>
</code>```

Converted the combined query valueMap into JSON (Using Version 3)

```<code>    gremlin>
    gremlin> mapper = GraphSONMapper.build().version(GraphSONVersion.V3_0).create().createMapper()
    ==>org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper@10a907ec
    gremlin>
    gremlin> mapper.writeValueAsString(output) // output is a variable in which data is collected in step 4
    ==>{"@type":"g:Map","@value":["nodes",{"@type":"g:List","@value":[{"@type":"g:Map","@value":["gId",{"@type":"g:List","@value":["0b98e8d5-681d-4155-8aaf-5d86babc0cff"]},"isDeleted",{"@type":"g:List","@value":["FALSE"]},"isEntity",{"@type":"g:List","@value":["TRUE"]},"name",{"@type":"g:List","@value":["TotsukaCDC"]},"basetype",{"@type":"g:List","@value":["GeoLocation"]},"source",{"@type":"g:List","@value":["RCP-Base"]},"type",{"@type":"g:List","@value":["DC"]},"geographyL2DisplayName",{"@type":"g:List","@value":["KANAGAWA"]},"geographyL2Name",{"@type":"g:List","@value":["KANAGAWA"]},"geographyL4Name",{"@type":"g:List","@value":["KNG-TOTSUKAKU-NORTH"]},"geographyL4DisplayName",{"@type":"g:List","@value":["KNG-TOTSUKAKU-NORTH"]},"displayName",{"@type":"g:List","@value":["TotsukaCDC"]},"latitude",{"@type":"g:List","@value":[{"@type":"g:Double","@value":139.525166}]},"locationType",{"@type":"g:List","@value":["CDC"]},"geographyL1Name",{"@type":"g:List","@value":["KANTO"]},"geographyL3DisplayName",{"@type":"g:List","@value":["YOKOHAMA-SHI"]},"geographyL3Name",{"@type":"g:List","@value":["YOKOHAMA-SHI"]},"geographyL1DisplayName",{"@type":"g:List","@value":["KANTO"]},"locationCode",{"@type":"g:List","@value":["tt"]},"longitude",{"@type":"g:List","@value":[{"@type":"g:Double","@value":35.416535}]}]},{"@type":"g:Map","@value":["gId",{"@type":"g:List","@value":["90e7407c-cd34-44b0-9bf9-1a8866aac429"]},"isDeleted",{"@type":"g:List","@value":["FALSE"]},"isEntity",{"@type":"g:List","@value":["TRUE"]},"name",{"@type":"g:List","@value":["UHN2KNGcdcttRA01_HundredGigE0/0/0/6"]},"basetype",{"@type":"g:List","@value":["Entity"]},"source",{"@type":"g:List","@value":["RCP-Base"]},"type",{"@type":"g:List","@value":["PhysicalPort"]},"portInUse",{"@type":"g:List","@value":["TRUE"]},"portNum",{"@type":"g:List","@value":["HundredGigE0/0/0/6"]}]},{"@type":"g:Map","@value":["gId",{"@type":"g:List","@value":["d0fc7284-4cd8-4cba-8d3d-be3c4ca2ba31"]},"isDeleted",{"@type":"g:List","@value":["FALSE"]},"isEntity",{"@type":"g:List","@value":["TRUE"]},"name",{"@type":"g:List","@value":["UHN2KNGcdcttRA01_Hu0/2/0/35"]},"basetype",{"@type":"g:List","@value":["Entity"]},"source",{"@type":"g:List","@value":["RCP-Base"]},"type",{"@type":"g:List","@value":["PhysicalPort"]},"portInUse",{"@type":"g:List","@value":["TRUE"]},"portNum",{"@type":"g:List","@value":["Hu0/2/0/35"]}]},{"@type":"g:Map","@value":["gId",{"@type":"g:List","@value":["2f4f5a3a-b88f-4915-acd5-a1d873507f11"]},"isDeleted",{"@type":"g:List","@value":["FALSE"]},"isEntity",{"@type":"g:List","@value":["TRUE"]},"name",{"@type":"g:List","@value":["UHN2KNGcdcttRA01_HundredGigE0/1/0/6"]},"basetype",{"@type":"g:List","@value":["Entity"]},"source",{"@type":"g:List","@value":["RCP-Base"]},"type",{"@type":"g:List","@value":["PhysicalPort"]},"portInUse",{"@type":"g:List","@value":["TRUE"]},"portNum",{"@type":"g:List","@value":["HundredGigE0/1/0/6"]}]}]},"edges",{"@type":"g:List","@value":[{"@type":"g:Map","@value":["destName","TotsukaCDC","srcName","UHN2KNGcdcttRA01","gId","1133ff0f-2f4b-4d21-b2d6-fed796ed13f9"]},{"@type":"g:Map","@value":["gId","220d7d2b-8b96-4331-bdc1-50127685946a","destName","UHN2KNGcdcttRA01","srcName","UHN2KNGcdcttRA01_HundredGigE0/0/0/6"]},{"@type":"g:Map","@value":["gId","ebd78fc0-a66c-4033-a776-f80210c02e63","destName","UHN2KNGcdcttRA01","srcName","UHN2KNGcdcttRA01_Hu0/2/0/35"]},{"@type":"g:Map","@value":["srcName","UHN2KNGcdcttRA01_HundredGigE0/1/0/6","gId","0df0f3d0-037a-4caa-9f81-6a6df1c22e25","destName","UHN2KNGcdcttRA01"]}]}]}
    gremlin>
</code>```

Converted the combined query valueMap into JSON (Using Version 1)

```<code>    gremlin>
    gremlin> mapper1 = GraphSONMapper.build().version(GraphSONVersion.V1_0).create().createMapper()
    ==>org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper@1a7163e3
    gremlin>
    gremlin> mapper1.writeValueAsString(output)
    ==>{"nodes":[{"gId":["0b98e8d5-681d-4155-8aaf-5d86babc0cff"],"isDeleted":["FALSE"],"isEntity":["TRUE"],"name":["TotsukaCDC"],"basetype":["GeoLocation"],"source":["RCP-Base"],"type":["DC"],"geographyL2DisplayName":["KANAGAWA"],"geographyL2Name":["KANAGAWA"],"geographyL4Name":["KNG-TOTSUKAKU-NORTH"],"geographyL4DisplayName":["KNG-TOTSUKAKU-NORTH"],"displayName":["TotsukaCDC"],"latitude":[139.525166],"locationType":["CDC"],"geographyL1Name":["KANTO"],"geographyL3DisplayName":["YOKOHAMA-SHI"],"geographyL3Name":["YOKOHAMA-SHI"],"geographyL1DisplayName":["KANTO"],"locationCode":["tt"],"longitude":[35.416535]},{"gId":["90e7407c-cd34-44b0-9bf9-1a8866aac429"],"isDeleted":["FALSE"],"isEntity":["TRUE"],"name":["UHN2KNGcdcttRA01_HundredGigE0/0/0/6"],"basetype":["Entity"],"source":["RCP-Base"],"type":["PhysicalPort"],"portInUse":["TRUE"],"portNum":["HundredGigE0/0/0/6"]},{"gId":["d0fc7284-4cd8-4cba-8d3d-be3c4ca2ba31"],"isDeleted":["FALSE"],"isEntity":["TRUE"],"name":["UHN2KNGcdcttRA01_Hu0/2/0/35"],"basetype":["Entity"],"source":["RCP-Base"],"type":["PhysicalPort"],"portInUse":["TRUE"],"portNum":["Hu0/2/0/35"]},{"gId":["2f4f5a3a-b88f-4915-acd5-a1d873507f11"],"isDeleted":["FALSE"],"isEntity":["TRUE"],"name":["UHN2KNGcdcttRA01_HundredGigE0/1/0/6"],"basetype":["Entity"],"source":["RCP-Base"],"type":["PhysicalPort"],"portInUse":["TRUE"],"portNum":["HundredGigE0/1/0/6"]}],"edges":[{"destName":"TotsukaCDC","srcName":"UHN2KNGcdcttRA01","gId":"1133ff0f-2f4b-4d21-b2d6-fed796ed13f9"},{"gId":"220d7d2b-8b96-4331-bdc1-50127685946a","destName":"UHN2KNGcdcttRA01","srcName":"UHN2KNGcdcttRA01_HundredGigE0/0/0/6"},{"gId":"ebd78fc0-a66c-4033-a776-f80210c02e63","destName":"UHN2KNGcdcttRA01","srcName":"UHN2KNGcdcttRA01_Hu0/2/0/35"},{"srcName":"UHN2KNGcdcttRA01_HundredGigE0/1/0/6","gId":"0df0f3d0-037a-4caa-9f81-6a6df1c22e25","destName":"UHN2KNGcdcttRA01"}]}
</code>```

Body:
Hi I'm new to gremlin and need to, basically, get everything current to return as a json file. I'm using Syndeia which has a raw query option. I'm having difficulty figuring out how to get both vertices and edges to output. This is what I have thus far:

g.V().has('sLabel','Artifact').has('_isLatest','TRUE').both()

But I also need

g.V().has('sLabel','Artifact').has('_isLatest','TRUE').bothE()

Which gives me all the edges I need, but not the vertices. I realize that g.V() gives vertices and g.E() gives edges, but am unsure how to obtain both/combine them in the one line query. My json comes back as either

         "vertices":[] 0 items
         "edges":[...] 90 items

Or

         "vertices":[...] 90 items
         "edges":[] 0 items

My next idea is to do multiple queries into java to parse, combine, and manipulate there. I would really like to avoid doing this, but will if it's the only way. Thank you for being kind and understanding and for your help. I appreciate you all.

Body:
You can do it as follows,

Just see the code below have demonstrated the following,

Vertex query

Edge query

combined query

converted combined query into valueMap

Converted the combined query valueMap into JSON (using version 3)

Converted the combined query valueMap into JSON (using version 1)

Vertex Query

    gremlin> g.V(131200).both()
    ==>v[40992]
    ==>v[12336]
    ==>v[20608]
    ==>v[180376]
    gremlin>

Edge query

    gremlin> g.V(131200).bothE()
    ==>e[7rps-2t8g-1fdh-vmo][131200-locatedin->40992]
    ==>e[3qpy-9io-1bf9-2t8g][12336-containedin->131200]
    ==>e[7rbk-fwg-1bf9-2t8g][20608-containedin->131200]
    ==>e[7l03-3v6g-1bf9-2t8g][180376-containedin->131200]
    gremlin>

Combined query

    gremlin>
    gremlin>g.V(131200).project('nodes','edges').by(both().fold()).by(bothE().fold())
    ==>[nodes:[v[40992],v[12336],v[20608],v[180376]],edges:[e[7rps-2t8g-1fdh-vmo][131200-locatedin->40992],e[3qpy-9io-1bf9-2t8g][12336-containedin->131200],e[7rbk-fwg-1bf9-2t8g][20608-containedin->131200],e[7l03-3v6g-1bf9-2t8g][180376-containedin->131200]]]
    gremlin>

converted combined query into valueMap

    gremlin>
    gremlin> output = g.V(131200).project('nodes','edges').by(both().valueMap().fold()).by(bothE().valueMap().fold()).next()
    ==>nodes=[{gId=[0b98e8d5-681d-4155-8aaf-5d86babc0cff], isDeleted=[FALSE], isEntity=[TRUE], name=[TotsukaCDC], basetype=[GeoLocation], source=[RCP-Base], type=[DC], geographyL2DisplayName=[KANAGAWA], geographyL2Name=[KANAGAWA], geographyL4Name=[KNG-TOTSUKAKU-NORTH], geographyL4DisplayName=[KNG-TOTSUKAKU-NORTH], displayName=[TotsukaCDC], latitude=[139.525166], locationType=[CDC], geographyL1Name=[KANTO], geographyL3DisplayName=[YOKOHAMA-SHI], geographyL3Name=[YOKOHAMA-SHI], geographyL1DisplayName=[KANTO], locationCode=[tt], longitude=[35.416535]}, {gId=[90e7407c-cd34-44b0-9bf9-1a8866aac429], isDeleted=[FALSE], isEntity=[TRUE], name=[UHN2KNGcdcttRA01_HundredGigE0/0/0/6], basetype=[Entity], source=[RCP-Base], type=[PhysicalPort], portInUse=[TRUE], portNum=[HundredGigE0/0/0/6]}, {gId=[d0fc7284-4cd8-4cba-8d3d-be3c4ca2ba31], isDeleted=[FALSE], isEntity=[TRUE], name=[UHN2KNGcdcttRA01_Hu0/2/0/35], basetype=[Entity], source=[RCP-Base], type=[PhysicalPort], portInUse=[TRUE], portNum=[Hu0/2/0/35]}, {gId=[2f4f5a3a-b88f-4915-acd5-a1d873507f11], isDeleted=[FALSE], isEntity=[TRUE], name=[UHN2KNGcdcttRA01_HundredGigE0/1/0/6], basetype=[Entity], source=[RCP-Base], type=[PhysicalPort], portInUse=[TRUE], portNum=[HundredGigE0/1/0/6]}]
    ==>edges=[{destName=TotsukaCDC, srcName=UHN2KNGcdcttRA01, gId=1133ff0f-2f4b-4d21-b2d6-fed796ed13f9}, {gId=220d7d2b-8b96-4331-bdc1-50127685946a, destName=UHN2KNGcdcttRA01, srcName=UHN2KNGcdcttRA01_HundredGigE0/0/0/6}, {gId=ebd78fc0-a66c-4033-a776-f80210c02e63, destName=UHN2KNGcdcttRA01, srcName=UHN2KNGcdcttRA01_Hu0/2/0/35}, {srcName=UHN2KNGcdcttRA01_HundredGigE0/1/0/6, gId=0df0f3d0-037a-4caa-9f81-6a6df1c22e25, destName=UHN2KNGcdcttRA01}]
    gremlin>

Converted the combined query valueMap into JSON (Using Version 3)

    gremlin>
    gremlin> mapper = GraphSONMapper.build().version(GraphSONVersion.V3_0).create().createMapper()
    ==>org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper@10a907ec
    gremlin>
    gremlin> mapper.writeValueAsString(output) // output is a variable in which data is collected in step 4
    ==>{"@type":"g:Map","@value":["nodes",{"@type":"g:List","@value":[{"@type":"g:Map","@value":["gId",{"@type":"g:List","@value":["0b98e8d5-681d-4155-8aaf-5d86babc0cff"]},"isDeleted",{"@type":"g:List","@value":["FALSE"]},"isEntity",{"@type":"g:List","@value":["TRUE"]},"name",{"@type":"g:List","@value":["TotsukaCDC"]},"basetype",{"@type":"g:List","@value":["GeoLocation"]},"source",{"@type":"g:List","@value":["RCP-Base"]},"type",{"@type":"g:List","@value":["DC"]},"geographyL2DisplayName",{"@type":"g:List","@value":["KANAGAWA"]},"geographyL2Name",{"@type":"g:List","@value":["KANAGAWA"]},"geographyL4Name",{"@type":"g:List","@value":["KNG-TOTSUKAKU-NORTH"]},"geographyL4DisplayName",{"@type":"g:List","@value":["KNG-TOTSUKAKU-NORTH"]},"displayName",{"@type":"g:List","@value":["TotsukaCDC"]},"latitude",{"@type":"g:List","@value":[{"@type":"g:Double","@value":139.525166}]},"locationType",{"@type":"g:List","@value":["CDC"]},"geographyL1Name",{"@type":"g:List","@value":["KANTO"]},"geographyL3DisplayName",{"@type":"g:List","@value":["YOKOHAMA-SHI"]},"geographyL3Name",{"@type":"g:List","@value":["YOKOHAMA-SHI"]},"geographyL1DisplayName",{"@type":"g:List","@value":["KANTO"]},"locationCode",{"@type":"g:List","@value":["tt"]},"longitude",{"@type":"g:List","@value":[{"@type":"g:Double","@value":35.416535}]}]},{"@type":"g:Map","@value":["gId",{"@type":"g:List","@value":["90e7407c-cd34-44b0-9bf9-1a8866aac429"]},"isDeleted",{"@type":"g:List","@value":["FALSE"]},"isEntity",{"@type":"g:List","@value":["TRUE"]},"name",{"@type":"g:List","@value":["UHN2KNGcdcttRA01_HundredGigE0/0/0/6"]},"basetype",{"@type":"g:List","@value":["Entity"]},"source",{"@type":"g:List","@value":["RCP-Base"]},"type",{"@type":"g:List","@value":["PhysicalPort"]},"portInUse",{"@type":"g:List","@value":["TRUE"]},"portNum",{"@type":"g:List","@value":["HundredGigE0/0/0/6"]}]},{"@type":"g:Map","@value":["gId",{"@type":"g:List","@value":["d0fc7284-4cd8-4cba-8d3d-be3c4ca2ba31"]},"isDeleted",{"@type":"g:List","@value":["FALSE"]},"isEntity",{"@type":"g:List","@value":["TRUE"]},"name",{"@type":"g:List","@value":["UHN2KNGcdcttRA01_Hu0/2/0/35"]},"basetype",{"@type":"g:List","@value":["Entity"]},"source",{"@type":"g:List","@value":["RCP-Base"]},"type",{"@type":"g:List","@value":["PhysicalPort"]},"portInUse",{"@type":"g:List","@value":["TRUE"]},"portNum",{"@type":"g:List","@value":["Hu0/2/0/35"]}]},{"@type":"g:Map","@value":["gId",{"@type":"g:List","@value":["2f4f5a3a-b88f-4915-acd5-a1d873507f11"]},"isDeleted",{"@type":"g:List","@value":["FALSE"]},"isEntity",{"@type":"g:List","@value":["TRUE"]},"name",{"@type":"g:List","@value":["UHN2KNGcdcttRA01_HundredGigE0/1/0/6"]},"basetype",{"@type":"g:List","@value":["Entity"]},"source",{"@type":"g:List","@value":["RCP-Base"]},"type",{"@type":"g:List","@value":["PhysicalPort"]},"portInUse",{"@type":"g:List","@value":["TRUE"]},"portNum",{"@type":"g:List","@value":["HundredGigE0/1/0/6"]}]}]},"edges",{"@type":"g:List","@value":[{"@type":"g:Map","@value":["destName","TotsukaCDC","srcName","UHN2KNGcdcttRA01","gId","1133ff0f-2f4b-4d21-b2d6-fed796ed13f9"]},{"@type":"g:Map","@value":["gId","220d7d2b-8b96-4331-bdc1-50127685946a","destName","UHN2KNGcdcttRA01","srcName","UHN2KNGcdcttRA01_HundredGigE0/0/0/6"]},{"@type":"g:Map","@value":["gId","ebd78fc0-a66c-4033-a776-f80210c02e63","destName","UHN2KNGcdcttRA01","srcName","UHN2KNGcdcttRA01_Hu0/2/0/35"]},{"@type":"g:Map","@value":["srcName","UHN2KNGcdcttRA01_HundredGigE0/1/0/6","gId","0df0f3d0-037a-4caa-9f81-6a6df1c22e25","destName","UHN2KNGcdcttRA01"]}]}]}
    gremlin>

Converted the combined query valueMap into JSON (Using Version 1)

    gremlin>
    gremlin> mapper1 = GraphSONMapper.build().version(GraphSONVersion.V1_0).create().createMapper()
    ==>org.apache.tinkerpop.shaded.jackson.databind.ObjectMapper@1a7163e3
    gremlin>
    gremlin> mapper1.writeValueAsString(output)
    ==>{"nodes":[{"gId":["0b98e8d5-681d-4155-8aaf-5d86babc0cff"],"isDeleted":["FALSE"],"isEntity":["TRUE"],"name":["TotsukaCDC"],"basetype":["GeoLocation"],"source":["RCP-Base"],"type":["DC"],"geographyL2DisplayName":["KANAGAWA"],"geographyL2Name":["KANAGAWA"],"geographyL4Name":["KNG-TOTSUKAKU-NORTH"],"geographyL4DisplayName":["KNG-TOTSUKAKU-NORTH"],"displayName":["TotsukaCDC"],"latitude":[139.525166],"locationType":["CDC"],"geographyL1Name":["KANTO"],"geographyL3DisplayName":["YOKOHAMA-SHI"],"geographyL3Name":["YOKOHAMA-SHI"],"geographyL1DisplayName":["KANTO"],"locationCode":["tt"],"longitude":[35.416535]},{"gId":["90e7407c-cd34-44b0-9bf9-1a8866aac429"],"isDeleted":["FALSE"],"isEntity":["TRUE"],"name":["UHN2KNGcdcttRA01_HundredGigE0/0/0/6"],"basetype":["Entity"],"source":["RCP-Base"],"type":["PhysicalPort"],"portInUse":["TRUE"],"portNum":["HundredGigE0/0/0/6"]},{"gId":["d0fc7284-4cd8-4cba-8d3d-be3c4ca2ba31"],"isDeleted":["FALSE"],"isEntity":["TRUE"],"name":["UHN2KNGcdcttRA01_Hu0/2/0/35"],"basetype":["Entity"],"source":["RCP-Base"],"type":["PhysicalPort"],"portInUse":["TRUE"],"portNum":["Hu0/2/0/35"]},{"gId":["2f4f5a3a-b88f-4915-acd5-a1d873507f11"],"isDeleted":["FALSE"],"isEntity":["TRUE"],"name":["UHN2KNGcdcttRA01_HundredGigE0/1/0/6"],"basetype":["Entity"],"source":["RCP-Base"],"type":["PhysicalPort"],"portInUse":["TRUE"],"portNum":["HundredGigE0/1/0/6"]}],"edges":[{"destName":"TotsukaCDC","srcName":"UHN2KNGcdcttRA01","gId":"1133ff0f-2f4b-4d21-b2d6-fed796ed13f9"},{"gId":"220d7d2b-8b96-4331-bdc1-50127685946a","destName":"UHN2KNGcdcttRA01","srcName":"UHN2KNGcdcttRA01_HundredGigE0/0/0/6"},{"gId":"ebd78fc0-a66c-4033-a776-f80210c02e63","destName":"UHN2KNGcdcttRA01","srcName":"UHN2KNGcdcttRA01_Hu0/2/0/35"},{"srcName":"UHN2KNGcdcttRA01_HundredGigE0/1/0/6","gId":"0df0f3d0-037a-4caa-9f81-6a6df1c22e25","destName":"UHN2KNGcdcttRA01"}]}


来源: stackexchange

问:
css svg filter safari not working
I am using a css filter property by applying an svg feColorMatrix to it. It works on Firefox and Chrome very well. But it does not work on safari. I have been playing with the values, indentation, vendor prefixes and have not been able to successfully apply my filter in safari.

Can anyone help me identify why my filter does not work in Safari?

You can view the demo here
https://codepen.io/Fallenstedt/pen/OvYGjV

My svg filter and video element:

```<code><svg class="defs-only">
  <filter
    id="blue-tint"
    color-interpolation-filters="sRGB"
    x="0"
    y="0"
    height="100%"
    width="100%">
    <feColorMatrix
      type="matrix"
      values="0 0 0 0 0
              0.75 0 0 0 0
              1.265 0 0 0 0
              0 0 0 1 0
              "/>
  </filter>
</svg>

<div class="background-vid">
  <video id="video"
    class="lazy"
    autoplay
    loop
    muted>
    <source src="https://storage.googleapis.com/coverr-main/mp4/Cloud_Surf.mp4" type="video/mp4">
  </video>
</div>
</code>```

My scss:

```<code>html, body {
  margin: 0;
  padding: 0;
}
.defs-only {
  position: absolute;
  height: 0;
  width: 0;
  overflow: none;
  left: -100%;
}

.background-vid {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  z-index: -1;
  -webkit-filter: grayscale(100%) url(#blue-tint);
  filter: grayscale(100%) url(#blue-tint);
  video {
    object-fit: cover;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
  }
}
</code>```

答:
If you use filters for svg elements in the css/scss file

filter: url(#filter_id);

Transfer the styles from the css/scss file into the  svg file separately into styles, and everything will work, like this:

```<code><svg>
...
<g id="group_id">
..
</g>

<filter id="filter_id" x="5.54736" y="0" width={width-11.3} height="80.0002" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood floodOpacity="0" result="BackgroundImageFix"/>
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
<feGaussianBlur stdDeviation="10" result="effect1_foregroundBlur_326_868"/>
</filter>

<style>
{`
    #group_id {
         filter: url(#filter_id);
    }
`}
</style>
</svg>
</code>```

ContentLicense: CC BY-SA 3.0

Title: css svg filter safari not working

Body:
I am using a css filter property by applying an svg feColorMatrix to it. It works on Firefox and Chrome very well. But it does not work on safari. I have been playing with the values, indentation, vendor prefixes and have not been able to successfully apply my filter in safari.

Can anyone help me identify why my filter does not work in Safari?

You can view the demo here
https://codepen.io/Fallenstedt/pen/OvYGjV

My svg filter and video element:

<svg class="defs-only">
  <filter
    id="blue-tint"
    color-interpolation-filters="sRGB"
    x="0"
    y="0"
    height="100%"
    width="100%">
    <feColorMatrix
      type="matrix"
      values="0 0 0 0 0
              0.75 0 0 0 0
              1.265 0 0 0 0
              0 0 0 1 0
              "/>
  </filter>
</svg>

  <video id="video"
    class="lazy"
    autoplay
    loop
    muted>
    <source src="https://storage.googleapis.com/coverr-main/mp4/Cloud_Surf.mp4" type="video/mp4">
  </video>

My scss:

html, body {
  margin: 0;
  padding: 0;
}
.defs-only {
  position: absolute;
  height: 0;
  width: 0;
  overflow: none;
  left: -100%;
}

.background-vid {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  z-index: -1;
  -webkit-filter: grayscale(100%) url(#blue-tint);
  filter: grayscale(100%) url(#blue-tint);
  video {
    object-fit: cover;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
  }
}

Body:
If you use filters for svg elements in the css/scss file

filter: url(#filter_id);

Transfer the styles from the css/scss file into the  svg file separately into styles, and everything will work, like this:

<svg>
...
<g id="group_id">
..
</g>

<filter id="filter_id" x="5.54736" y="0" width={width-11.3} height="80.0002" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood floodOpacity="0" result="BackgroundImageFix"/>
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape"/>
<feGaussianBlur stdDeviation="10" result="effect1_foregroundBlur_326_868"/>
</filter>

<style>
{`
    #group_id {
         filter: url(#filter_id);
    }
`}
</style>
</svg>

ContentLicense: CC BY-SA 4.0


问:
how character pointer could be used to point a string in c++?
First of all I am beginner in C++. I was trying to learn about type casting in C++ with strings and character pointer. Is it possible to point a string with a character pointer?

```<code>int main() {
    string data="LetsTry";
    cout<<(&data)<<"\n";
    cout<<data<<"\n"<<"size "<<sizeof(data)<<"\n";
    //char *ptr = static_cast<char*>(data);
    //char *ptr=(char*)data;
    char *ptr = reinterpret_cast<char*>(&data);
    cout<<(ptr)<<"\n";
    cout<<*ptr;
}
</code>```

The above code yields outcome as below:

```<code>0x7ffea4a06150
LetsTry
size 32
`a���
`
</code>```

I understand as ptr should output the address 0x7ffea4a06150

答:
Historically, in C language strings were just a memory areas filled with characters. Consequently, when a string was passed to a function, it was passed as a pointer to its very first character, of type char *, for mutable strings, or char const *, if the function had no intent to modify string's contents. Such strings were delimited with a zero-character ((char)0 a.k.a. '\0') at the end, so for a string of length 3 you had to allocate at least four bytes of memory (three characters of the string itself plus the zero terminator); and if you only had a pointer to a string's start, to know the size of the string you'd have to iterate it to find how far is the zero-char (the standard function strlen did it). Some standard functions accepted en extra parameter for a string size if you knew it in advance (those starting with strn or, more primitive and effective, those starting with mem), others did not. To concatenate two strings you first had to allocate a sufficient buffer to contain the result etc.

The standard functions that process char pointers can still be found in STL, under the <cstring> header: https://en.cppreference.com/w/cpp/header/cstring, and std::string has synonymous methods c_str() and data() that return char pointers to its contents, should you need it.

When you write a program in C++, its main function has the header of int main(int argc, char *argv[]), where argv is the array of char pointers that contains any command-line arguments your program was run with.

Ineffective as it is, this scheme could still be regarded as an advantage over strings of limited capacity or plain fixed-size character arrays, for instance in mid-nineties, when Borland introduced the PChar type in Turbo Pascal and added a unit that exported Pascal implementations of functions from C's string.h.

Body:
First of all I am beginner in C++. I was trying to learn about type casting in C++ with strings and character pointer. Is it possible to point a string with a character pointer?

int main() {
    string data="LetsTry";
    cout<<(&data)<<"\n";
    cout<<data<<"\n"<<"size "<<sizeof(data)<<"\n";
    //char *ptr = static_cast<char*>(data);
    //char *ptr=(char*)data;
    char *ptr = reinterpret_cast<char*>(&data);
    cout<<(ptr)<<"\n";
    cout<<*ptr;
}

The above code yields outcome as below:

0x7ffea4a06150
LetsTry
size 32
`a���
`

I understand as ptr should output the address 0x7ffea4a06150


问:
How to run single command within shell script, but looping just the options
suppose I want to loop over variables within shell script. However, it's not running command multiple times, but I want to run a single command, but want to avoid defining options many times.

Example is as below.

```<code>PORTS = {8080, 8081, 8082}
docker run -ti \
  for PORT in $PORTS:
    -p $PORT:$PORT
  --name sample-container
</code>```

答:
Take the whole command into the body of the loop:

for port in 8080 8081 8082
do docker run -ti -p $port --name sample-container
done
```

Body:
suppose I want to loop over variables within shell script. However, it's not running command multiple times, but I want to run a single command, but want to avoid defining options many times.

Example is as below.

PORTS = {8080, 8081, 8082}
docker run -ti \
  for PORT in $PORTS:
    -p $PORT:$PORT
  --name sample-container


问:
Is this '??' is a operator in php or what it's called? Also is it used for empty() or isset() check?
$name = $username ?? '';

I don't know actually what is this ??  called?

答:
?? is Null coalescing Let suppose

```<code>$x = expr1 ?? expr2
</code>```

Returns the value of $x.The value of $x is expr1 if expr1 exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2.Null coalescing  Introduced in PHP 7.

Other Examples

```<code><?php
   // variable $user is the value of $_GET['user']
   // and 'anonymous' if it does not exist
   echo $user = $_GET["user"] ?? "anonymous";
   echo("<br>");

   // variable $color is "red" if $color does not exist or is null
   echo $color = $color ?? "red";
?>
</code>```

Body:
?? is Null coalescing Let suppose

$x = expr1 ?? expr2

Returns the value of $x.The value of $x is expr1 if expr1 exists, and is not NULL.
If expr1 does not exist, or is NULL, the value of $x is expr2.Null coalescing  Introduced in PHP 7.

Other Examples

<?php
   // variable $user is the value of $_GET['user']
   // and 'anonymous' if it does not exist
   echo $user = $_GET["user"] ?? "anonymous";
   echo("<br>");

   // variable $color is "red" if $color does not exist or is null
   echo $color = $color ?? "red";
?>


问:
How to use Application variable like ASP in Codeigniter
I want to count the click on the each part of homepage, but not by using database. I think DB will bring some overhead.

The ASP code is:

```<code><script language="vbscript" runat="server">

Sub Application_OnStart
application("vartime")=""
application("users")=1
End Sub

</script>
</code>```

答:
Well, since PHP is stateless, you will have to write it to the hard drive some how.
you can write to a file by using, file_put_contents

or, you can user the $_SESSION variable.

but, if it gets complicated, you'll have to use database, complicated data should be in the database.

The database will handle the hard drive most likely better than you


问:
CREATE ASSEMBLY failed because it could not read from the physical file
I have a problem in SQL Server when using create assembly

CREATE ASSEMBLY failed because it could not read from the physical
  file 'D:\CLR\DLL\PersianDate.dll': 50(The request is not supported.).

This is my script :

```<code>CREATE ASSEMBLY PersianDate FROM 'D:\CLR\DLL\PersianDate.dll'
WITH PERMISSION_SET = SAFE
GO
</code>```

答:
Run your code in the server that Microsoft SQL Server installed on it.
And put your dll file in server drive.
It will work.</p>

Body:
I have a problem in SQL Server when using create assembly

CREATE ASSEMBLY failed because it could not read from the physical
  file 'D:\CLR\DLL\PersianDate.dll': 50(The request is not supported.).

This is my script :

CREATE ASSEMBLY PersianDate FROM 'D:\CLR\DLL\PersianDate.dll'
WITH PERMISSION_SET = SAFE
GO


问:
How to get the authenticated user in spring boot when authentication is externalized (azure)
If I deploy a spring boot application as a azure app, I can externalize the authentication by

using azure API management and configuring oauth2 etc

using the authentication options of azure app service.
As such I don't need to configure any authentication in my spring boot application.

All that works fine and I can find a lot of info about that. What I cannot find is: how do I retrieve the logged on user in my application in such case? How is that information passed to my application?

答: If you are using oauth2 you should be able to fetch the username from JWT token/via an api call. You can refer this link which tells you how to read jwt token. Once you have the username then you can add it to a custom header and pass to your backend application. Follow this link to understand how to add custom header to your request in api manager to be passed to your back end</p>


问:
Spring boot gradle build failing due to exception "HikariPool$PoolInitializationException" in unit test
Test cases are running fine when we run them individually it only gives this exception when we are trying to create a build.

This is the exception we are getting for every test case.

```<code>StudentReportControllerTest > testSubmittedPaperController() FAILED
    java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800
            Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658
                Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800

                    Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException at HikariPool.java:596
                        Caused by: org.postgresql.util.PSQLException at QueryExecutorImpl.java:2552
            Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658

                Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185

                    Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException at HikariPool.java:596

                        Caused by: org.postgresql.util.PSQLException at QueryExecutorImpl.java:2552
</code>```

We are using primary and replica database configuration and once we implemented that this issue occurred.

```<code>@Aspect
@Component
@Order(0)
public class ReadOnlyRouteInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(ReadOnlyRouteInterceptor.class);

    @Around("@annotation(transactional)")
    public Object proceed(ProceedingJoinPoint proceedingJoinPoint, Transactional transactional) throws Throwable {
        try {
            if (transactional.readOnly()) {
                RoutingDataSource.setReplicaRoute();
                logger.info("Routing database call to the read replica");
            }
            return proceedingJoinPoint.proceed();
        } finally {
            RoutingDataSource.clearReplicaRoute();
        }
    }
}
</code>```
```<code>public class RoutingDataSource extends AbstractRoutingDataSource {

    private static final ThreadLocal<Route> routeContext = new ThreadLocal<>();

    public enum Route {
        PRIMARY, REPLICA
    }

    public static void clearReplicaRoute() {
        routeContext.remove();
    }

    public static void setReplicaRoute() {
        routeContext.set(Route.REPLICA);
    }

    @Override
    public Object determineCurrentLookupKey() {
        return routeContext.get();
    }
}
</code>```
```<code>@Configuration
public class DataSourceConfig {

    private static final String PRIMARY_DATASOURCE_PREFIX = "spring.primary.datasource";
    private static final String REPLICA_DATASOURCE_PREFIX = "spring.replica.datasource";

    @Autowired
    private Environment environment;

    @Bean
    @Primary
    public DataSource dataSource() {
        final RoutingDataSource routingDataSource = new RoutingDataSource();

        final DataSource primaryDataSource = buildDataSource("PrimaryHikariPool", PRIMARY_DATASOURCE_PREFIX);
        final DataSource replicaDataSource = buildDataSource("ReplicaHikariPool", REPLICA_DATASOURCE_PREFIX);

        final Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(RoutingDataSource.Route.PRIMARY, primaryDataSource);
        targetDataSources.put(RoutingDataSource.Route.REPLICA, replicaDataSource);

        routingDataSource.setTargetDataSources(targetDataSources);
        routingDataSource.setDefaultTargetDataSource(primaryDataSource);

        return routingDataSource;
    }

    private DataSource buildDataSource(String poolName, String dataSourcePrefix) {
        final HikariConfig hikariConfig = new HikariConfig();

        hikariConfig.setPoolName(poolName);
        hikariConfig.setJdbcUrl(environment.getProperty(String.format("%s.url", dataSourcePrefix)));
        hikariConfig.setUsername(environment.getProperty(String.format("%s.username", dataSourcePrefix)));
        hikariConfig.setPassword(environment.getProperty(String.format("%s.password", dataSourcePrefix)));
        hikariConfig.setDriverClassName(environment.getProperty(String.format("%s.driver", dataSourcePrefix)));

        return new HikariDataSource(hikariConfig);
    }
}
</code>```

My build.gradle

```<code>plugins {
    id 'org.springframework.boot' version '2.5.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'jacoco'
    id 'org.sonarqube' version '3.0'
}

group = 'com.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}
ext {
    set('springCloudVersion', "2020.0.2")
}
dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
    implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.9'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.5.2'
    implementation group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2'
    implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
    implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '2.6.1'
    implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis'
    implementation group: 'commons-io', name: 'commons-io', version: '2.6'
    implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.1000')
    implementation 'com.amazonaws:aws-java-sdk-s3'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'org.postgresql:postgresql'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-config'
    implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-netflix-eureka-client'
}

test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}
jacocoTestReport {
    dependsOn test
    reports {
        //xml.required false
//      csv.enabled false
        html.enabled true
        xml.enabled false
        csv.enabled false
        html.enabled true
    }
    afterEvaluate {
        getClassDirectories().setFrom(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: [
                            '**/entity/**',
                            '**/request/**',
                            '**/dto/**',
                            '**/config/**',
                            '**/interceptor/**',
                            '**/mapper/**',
                            '**/utils/**',
                            '**/enums/**',
                            '**/response/**',
                            '**/filters/**',
                            '**/constants/**',
                            '**/exception/**',
                            '**/log/**',
                            '**/StudentTestReportApplication.class',
                    ]
            )
        })
    }
}
</code>```

One of my test class

```<code>@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
class StudentReportControllerTest {
    @Autowired
    StudentReportController studentReportController;

    @MockBean
    PaperReportStudentService paperReportStudentService;

    @MockBean
    PaperDetailStudentService paperDetailStudentService;

    @Autowired
    TeacherReportController teacherReportController;

    @MockBean
    PaperDetailTeacherService paperDetailTeacherService;

    @MockBean
    QuestionWiseReportStudentService questionWiseReportStudentService;

    @Autowired
    private MockMvc mockMvc;

    protected String mapToJson(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(obj);
    }

    @Test
    void getTeacherAssignmentsNegativeTest() throws Exception
        String inputJson = mapToJson(new TeacherRequest());
        final MockHttpServletResponse response =
                mockMvc
                        .perform(
                                post(REPORT_API + GET_TEACHER_ASSIGNMENTS)
                                        .content(inputJson)
                                        .contentType(MediaType.APPLICATION_JSON)
                                        .accept(MediaType.APPLICATION_JSON))
                        .andReturn()
                        .getResponse();

        assertThat(new JSONObject(response.getContentAsString()).get("status")).isEqualTo(404);
        assertThat(new JSONObject(response.getContentAsString()).get("message")).isEqualTo(Constants.RECORD_NOT_FOUND);
    }
</code>```

This is our property file

```<code>spring.cloud.config.import-check.enabled=false
spring.jpa.show-sql=true
spring.datasource.initialization-mode=always
spring.datasource.initialize=true
spring.datasource.continue-on-error=true
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.minimum-idle=1
spring.datasource.hikari.maximum-pool-size=1
spring.redis.timeout=2000
spring.jackson.property-naming-strategy=SNAKE_CASE
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Kolkata
spring.data.redis.timeout=3000
eureka.client.enabled=false
#
spring.primary.datasource.password=postgres
spring.primary.datasource.username=postgres
spring.primary.datasource.driver=org.postgresql.Driver
spring.primary.datasource.url=jdbc:postgresql://127.0.0.1/master?stringtype=unspecified
#
spring.replica.datasource.password=postgres
spring.replica.datasource.username=postgres
spring.replica.datasource.driver=org.postgresql.Driver
spring.replica.datasource.url=jdbc:postgresql://127.0.0.1/replica?stringtype=unspecified

</code>```

答: I have resolved this issue now. To get a better exception detail I have tried "Gradle check" and then I found out that this issue was due to limited connection size on our db and We are creating DB connections unknowingly in our unit test.</p>

Body:
Test cases are running fine when we run them individually it only gives this exception when we are trying to create a build.

This is the exception we are getting for every test case.

StudentReportControllerTest > testSubmittedPaperController() FAILED
    java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800
            Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658
                Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185
        Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at ConstructorResolver.java:800

                    Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException at HikariPool.java:596
                        Caused by: org.postgresql.util.PSQLException at QueryExecutorImpl.java:2552
            Caused by: org.springframework.beans.factory.BeanCreationException at ConstructorResolver.java:658

                Caused by: org.springframework.beans.BeanInstantiationException at SimpleInstantiationStrategy.java:185

                    Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException at HikariPool.java:596

                        Caused by: org.postgresql.util.PSQLException at QueryExecutorImpl.java:2552

We are using primary and replica database configuration and once we implemented that this issue occurred.

@Aspect
@Component
@Order(0)
public class ReadOnlyRouteInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(ReadOnlyRouteInterceptor.class);

    @Around("@annotation(transactional)")
    public Object proceed(ProceedingJoinPoint proceedingJoinPoint, Transactional transactional) throws Throwable {
        try {
            if (transactional.readOnly()) {
                RoutingDataSource.setReplicaRoute();
                logger.info("Routing database call to the read replica");
            }
            return proceedingJoinPoint.proceed();
        } finally {
            RoutingDataSource.clearReplicaRoute();
        }
    }
}

public class RoutingDataSource extends AbstractRoutingDataSource {

    private static final ThreadLocal<Route> routeContext = new ThreadLocal<>();

    public enum Route {
        PRIMARY, REPLICA
    }

    public static void clearReplicaRoute() {
        routeContext.remove();
    }

    public static void setReplicaRoute() {
        routeContext.set(Route.REPLICA);
    }

    @Override
    public Object determineCurrentLookupKey() {
        return routeContext.get();
    }
}

@Configuration
public class DataSourceConfig {

    private static final String PRIMARY_DATASOURCE_PREFIX = "spring.primary.datasource";
    private static final String REPLICA_DATASOURCE_PREFIX = "spring.replica.datasource";

    @Autowired
    private Environment environment;

    @Bean
    @Primary
    public DataSource dataSource() {
        final RoutingDataSource routingDataSource = new RoutingDataSource();

        final DataSource primaryDataSource = buildDataSource("PrimaryHikariPool", PRIMARY_DATASOURCE_PREFIX);
        final DataSource replicaDataSource = buildDataSource("ReplicaHikariPool", REPLICA_DATASOURCE_PREFIX);

        final Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(RoutingDataSource.Route.PRIMARY, primaryDataSource);
        targetDataSources.put(RoutingDataSource.Route.REPLICA, replicaDataSource);

        routingDataSource.setTargetDataSources(targetDataSources);
        routingDataSource.setDefaultTargetDataSource(primaryDataSource);

        return routingDataSource;
    }

    private DataSource buildDataSource(String poolName, String dataSourcePrefix) {
        final HikariConfig hikariConfig = new HikariConfig();

        hikariConfig.setPoolName(poolName);
        hikariConfig.setJdbcUrl(environment.getProperty(String.format("%s.url", dataSourcePrefix)));
        hikariConfig.setUsername(environment.getProperty(String.format("%s.username", dataSourcePrefix)));
        hikariConfig.setPassword(environment.getProperty(String.format("%s.password", dataSourcePrefix)));
        hikariConfig.setDriverClassName(environment.getProperty(String.format("%s.driver", dataSourcePrefix)));

        return new HikariDataSource(hikariConfig);
    }
}

My build.gradle

plugins {
    id 'org.springframework.boot' version '2.5.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'jacoco'
    id 'org.sonarqube' version '3.0'
}

group = 'com.demo'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}
ext {
    set('springCloudVersion', "2020.0.2")
}
dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
    implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.9'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.5.2'
    implementation group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2'
    implementation group: 'io.springfox', name: 'springfox-swagger-ui', version: '2.9.2'
    implementation group: 'io.springfox', name: 'springfox-swagger2', version: '2.9.2'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: '2.6.1'
    implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-redis'
    implementation group: 'commons-io', name: 'commons-io', version: '2.6'
    implementation platform('com.amazonaws:aws-java-sdk-bom:1.11.1000')
    implementation 'com.amazonaws:aws-java-sdk-s3'
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    compileOnly 'org.projectlombok:lombok'
    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    runtimeOnly 'org.postgresql:postgresql'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-config'
    implementation group: 'org.springframework.cloud', name: 'spring-cloud-starter-netflix-eureka-client'
}

test {
    useJUnitPlatform()
    finalizedBy jacocoTestReport
}
jacocoTestReport {
    dependsOn test
    reports {
        //xml.required false
//      csv.enabled false
        html.enabled true
        xml.enabled false
        csv.enabled false
        html.enabled true
    }
    afterEvaluate {
        getClassDirectories().setFrom(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: [
                            '**/entity/**',
                            '**/request/**',
                            '**/dto/**',
                            '**/config/**',
                            '**/interceptor/**',
                            '**/mapper/**',
                            '**/utils/**',
                            '**/enums/**',
                            '**/response/**',
                            '**/filters/**',
                            '**/constants/**',
                            '**/exception/**',
                            '**/log/**',
                            '**/StudentTestReportApplication.class',
                    ]
            )
        })
    }
}

One of my test class

@ExtendWith(SpringExtension.class)
@SpringBootTest
@AutoConfigureMockMvc
class StudentReportControllerTest {
    @Autowired
    StudentReportController studentReportController;

    @MockBean
    PaperReportStudentService paperReportStudentService;

    @MockBean
    PaperDetailStudentService paperDetailStudentService;

    @Autowired
    TeacherReportController teacherReportController;

    @MockBean
    PaperDetailTeacherService paperDetailTeacherService;

    @MockBean
    QuestionWiseReportStudentService questionWiseReportStudentService;

    @Autowired
    private MockMvc mockMvc;

    protected String mapToJson(Object obj) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(obj);
    }

    @Test
    void getTeacherAssignmentsNegativeTest() throws Exception
        String inputJson = mapToJson(new TeacherRequest());
        final MockHttpServletResponse response =
                mockMvc
                        .perform(
                                post(REPORT_API + GET_TEACHER_ASSIGNMENTS)
                                        .content(inputJson)
                                        .contentType(MediaType.APPLICATION_JSON)
                                        .accept(MediaType.APPLICATION_JSON))
                        .andReturn()
                        .getResponse();

        assertThat(new JSONObject(response.getContentAsString()).get("status")).isEqualTo(404);
        assertThat(new JSONObject(response.getContentAsString()).get("message")).isEqualTo(Constants.RECORD_NOT_FOUND);
    }

This is our property file

spring.cloud.config.import-check.enabled=false
spring.jpa.show-sql=true
spring.datasource.initialization-mode=always
spring.datasource.initialize=true
spring.datasource.continue-on-error=true
spring.datasource.hikari.connection-timeout=10000
spring.datasource.hikari.minimum-idle=1
spring.datasource.hikari.maximum-pool-size=1
spring.redis.timeout=2000
spring.jackson.property-naming-strategy=SNAKE_CASE
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=Asia/Kolkata
spring.data.redis.timeout=3000
eureka.client.enabled=false
#
spring.primary.datasource.password=postgres
spring.primary.datasource.username=postgres
spring.primary.datasource.driver=org.postgresql.Driver
spring.primary.datasource.url=jdbc:postgresql://127.0.0.1/master?stringtype=unspecified
#
spring.replica.datasource.password=postgres
spring.replica.datasource.username=postgres
spring.replica.datasource.driver=org.postgresql.Driver
spring.replica.datasource.url=jdbc:postgresql://127.0.0.1/replica?stringtype=unspecified


问:
React-S3 error: ReferenceError: Buffer is not defined
I'm trying to set up file upload to S3 with React. I use React-S3

This is my code

```<code>const handleUpload = async (e) => {
    e.preventDefault();
    S3FileUpload
    .uploadFile(selectedFile, awsConfig)
    .then(data => console.log(data))
    .catch(err => console.error(err))
  };
</code>```

I have the error ReferenceError: Buffer is not defined in my console. Can you help me please?

答:
npm i buffer

Then import it at the top of your file like so:

window.Buffer = window.Buffer || require("buffer").Buffer;

source: https://github.com/Fausto95/aws-s3/issues/88#issuecomment-1000511145

Body:
I'm trying to set up file upload to S3 with React. I use React-S3

This is my code

const handleUpload = async (e) => {
    e.preventDefault();
    S3FileUpload
    .uploadFile(selectedFile, awsConfig)
    .then(data => console.log(data))
    .catch(err => console.error(err))
  };

I have the error ReferenceError: Buffer is not defined in my console. Can you help me please?


问:
aws ecr saying "Cannot perform an interactive login from a non TTY device" after copied cmd from "Amazon Container Services"
I am trying to set up docker image of amazon ECR on ubuntu18.04 machine of AWS,using commands provided by view push commands of Amazon Container Services

,please note i have already set up docker on my ubuntu18.04 and also output of docker -v is as below

```<code>ubuntu@ip-172-31-0-143:~$ docker -v
Docker version 19.03.7, build 7141c199a2
</code>```

When i execute the command provided by amazon container services on aws cli on ubuntu18.04 i get error as
    Error: Cannot perform an interactive login from a non TTY device

The command which i am using is

```<code>aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 8233251134332.dkr.ecr.us-east-2.amazonaws.com/gatling-lots
</code>```

please note i have successfully configured awscli and i can see the
detailed  from aws s3 ls

Here is detailed error log

```<code>ubuntu@ip-172-31-0-143:~$ aws ecr get-login-password --region us-
east-2 | docker login --username AWS --password-stdin
823443336.dkr.ecr.us-west-2.amazonaws.com/gatling-lots
usage: aws [options] <command> <subcommand> [<subcommand> ...]
[parameters]
 To see help text, you can run:

aws help
aws <command> help
aws <command> <subcommand> help
aws: error: argument operation: Invalid choice, valid choices are:

 batch-check-layer-availability           | batch-delete-image
 batch-get-image                          | complete-layer-upload
create-repository                        | delete-lifecycle-policy
delete-repository                        | delete-repository-policy
 describe-images                          | describe-repositories
 get-authorization-token                  | get-download-url-for-layer
 get-lifecycle-policy                     | get-lifecycle-policy-preview
 get-repository-policy                    | initiate-layer-upload
 list-images                              | put-image
 put-lifecycle-policy                     | set-repository-policy
 start-lifecycle-policy-preview           | upload-layer-part
 get-login                                | help
 Error: Cannot perform an interactive login from a non TTY device
</code>```

output of

```<code>ubuntu@ip-172-31-0-143:~$ (aws ecr get-login --no-include-email  --region us-east-2)

docker login -u AWS -p

MzQxL2c0Yks4RjVxeDg9IiwidmVyc2lvbiI6IjIiLCJ0eXBlIjoiREFUQV9LRVkiLCJleHBpcmF0aW9uIjoxNTgzNjgzNDY5fQ== https://825251119036.dkr.ecr.us- east-2.amazonaws.com
</code>```

答:
I know this question is answered already, but, this was my experience.

This didn't work for me initially.

aws ecr get-login-password --region <your-region>| docker login --username AWS --password-stdin <your-container>

I had the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY saved under variables in GitLab.

But the solution was to uncheck the Protected flag from the variables saved on GitLab. I don't know how secure this approach is, but, it did work for me.

I hope this would help someone one day.

Body:
I am trying to set up docker image of amazon ECR on ubuntu18.04 machine of AWS,using commands provided by view push commands of Amazon Container Services

,please note i have already set up docker on my ubuntu18.04 and also output of docker -v is as below

ubuntu@ip-172-31-0-143:~$ docker -v
Docker version 19.03.7, build 7141c199a2

When i execute the command provided by amazon container services on aws cli on ubuntu18.04 i get error as
    Error: Cannot perform an interactive login from a non TTY device

The command which i am using is

aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 8233251134332.dkr.ecr.us-east-2.amazonaws.com/gatling-lots

please note i have successfully configured awscli and i can see the
detailed  from aws s3 ls

Here is detailed error log

ubuntu@ip-172-31-0-143:~$ aws ecr get-login-password --region us-
east-2 | docker login --username AWS --password-stdin
823443336.dkr.ecr.us-west-2.amazonaws.com/gatling-lots
usage: aws [options] <command> <subcommand> [<subcommand> ...]
[parameters]
 To see help text, you can run:

aws help
aws <command> help
aws <command> <subcommand> help
aws: error: argument operation: Invalid choice, valid choices are:

 batch-check-layer-availability           | batch-delete-image
 batch-get-image                          | complete-layer-upload
create-repository                        | delete-lifecycle-policy
delete-repository                        | delete-repository-policy
 describe-images                          | describe-repositories
 get-authorization-token                  | get-download-url-for-layer
 get-lifecycle-policy                     | get-lifecycle-policy-preview
 get-repository-policy                    | initiate-layer-upload
 list-images                              | put-image
 put-lifecycle-policy                     | set-repository-policy
 start-lifecycle-policy-preview           | upload-layer-part
 get-login                                | help
 Error: Cannot perform an interactive login from a non TTY device

output of

ubuntu@ip-172-31-0-143:~$ (aws ecr get-login --no-include-email  --region us-east-2)

docker login -u AWS -p

MzQxL2c0Yks4RjVxeDg9IiwidmVyc2lvbiI6IjIiLCJ0eXBlIjoiREFUQV9LRVkiLCJleHBpcmF0aW9uIjoxNTgzNjgzNDY5fQ== https://825251119036.dkr.ecr.us- east-2.amazonaws.com


问:
Find distance to middle of line
So I have a line, connecting two points, and I want to give this line a visual name in my canvas. I want this name to be positioned right at the middle of the line but with an offset so that the text doesn't go through the line. Determining the middle of the line isn't that hard you can just find it out like that:

And the line equation of the normal to the line can be determined pretty easy too:

Where you can find out n just by inserting P into the equation.

Now to the problem: For a given distance to the line, I want to find a point P(xn, yn) that is on that normal to the line through the middle of the line. After inserting the linear function into the distance formula I end up with this:

Not only am I not able to transform this equation to get a valid value for xn, I believe there has to be an mathematically easier way to achieve this.

答:
Line middle is

```<code>mx = (x1 + x2)/2
my = (y1 + y2)/2
</code>```

Line length is

```<code>len = sqrt((x1 - x2)^2 + (y1 - y2)^2)
</code>```

Normalized direction vector of the line is

```<code>dx = (x2-x1) / len
dy = (y2-y1) / len
</code>```

Perpendicular vector is

```<code>nx = -dy
ny = dx
</code>```

Point at offset d from middle is

```<code>px = mx + d * nx
py = mx + d * ny
</code>```

or for other side

```<code>px = mx - d * nx
py = mx - d * ny
</code>```

Title: Find distance to middle of line

Body:
Line middle is

mx = (x1 + x2)/2
my = (y1 + y2)/2

Line length is

len = sqrt((x1 - x2)^2 + (y1 - y2)^2)

Normalized direction vector of the line is

dx = (x2-x1) / len
dy = (y2-y1) / len

Perpendicular vector is

nx = -dy
ny = dx

Point at offset d from middle is

px = mx + d * nx
py = mx + d * ny

or for other side

px = mx - d * nx
py = mx - d * ny


问:
How to use Vuex mapGetters with Vue 3 SFC Script Setup syntax?
I'm refactoring component from regular Vue 3 Composition API to Script Setup syntax. Starting point:

```<code><script lang="ts">
import { defineComponent, computed } from 'vue';
import { mapGetters } from 'vuex';

export default defineComponent({
  name: 'MyCoolBareComponent',
  computed: {
    ...mapGetters('auth', ['isAdmin']),
  },
});
</script>
</code>```

Current Vue v3 migration documentation, SFC Composition API Syntax Sugar (< script setup >), links to this RFC page: https://github.com/vuejs/rfcs/pull/182

There is only one example for using computed reactive property:

```<code>export const computedMsg = computed(() => props.msg + '!!!')
</code>```

As there is no current Vuex 4 documentation available that is mentioning <scrip setup>, it remains unclear to me how I should be using mapGetters when using this syntax? Or what is the correct way of going about this with Vuex 4?

答:
You can do something like this</p>
```<code>import { mapGetters } from "vuex"
setup() {
  return {
    ...mapGetters("myModule", ["doSomething"])
  }
}
</code>```

Body:
I'm refactoring component from regular Vue 3 Composition API to Script Setup syntax. Starting point:

Current Vue v3 migration documentation, SFC Composition API Syntax Sugar (< script setup >), links to this RFC page: https://github.com/vuejs/rfcs/pull/182

There is only one example for using computed reactive property:

export const computedMsg = computed(() => props.msg + '!!!')

As there is no current Vuex 4 documentation available that is mentioning <scrip setup>, it remains unclear to me how I should be using mapGetters when using this syntax? Or what is the correct way of going about this with Vuex 4?

Body:
You can do something like this

import { mapGetters } from "vuex"
setup() {
  return {
    ...mapGetters("myModule", ["doSomething"])
  }
}


问:
oracle tablespace storage option
If the extent of the Oracle tablespace is local, the value seems to be ignored even when the query below is executed.

Is this normal?

```<code>CREATE TABLESPACE TS1_FIXED2
DATAFILE
    '\df1_fixed2.dbf'
        SIZE 1024000
DEFAULT  NOCOMPRESS STORAGE (
    INITIAL 10240
    NEXT 10240
    MINEXTENTS 2
    MAXEXTENTS 50
    PCTINCREASE 50
)
SEGMENT SPACE MANAGEMENT MANUAL
</code>```

TABLESPACE_NAME
INITIAL
NEXT
MINEXTENTS
MAXEXTENTS
PCTINCREASE

TS1_FIXED2
65536
null
1
2147483645
2147483645

答:
This is expected.
The extents of a locally managed tablespace are managed efficiently in the tablespace by the Oracle database server.
However, if it was dictionary-managed tablespace, you could manage extents more
actively. And remember, Oracle does not recommend their use!

Title: oracle tablespace storage option

Body:
If the extent of the Oracle tablespace is local, the value seems to be ignored even when the query below is executed.

Is this normal?

CREATE TABLESPACE TS1_FIXED2
DATAFILE
    '\df1_fixed2.dbf'
        SIZE 1024000
DEFAULT  NOCOMPRESS STORAGE (
    INITIAL 10240
    NEXT 10240
    MINEXTENTS 2
    MAXEXTENTS 50
    PCTINCREASE 50
)
SEGMENT SPACE MANAGEMENT MANUAL

TABLESPACE_NAME
INITIAL
NEXT
MINEXTENTS
MAXEXTENTS
PCTINCREASE

TS1_FIXED2
65536
null
1
2147483645
2147483645


问:
Reset local repository branch to be just like remote repository HEAD
How do I reset my local branch to be just like the branch on the remote repository?

I tried:

```<code>git reset --hard HEAD
</code>```

But git status claims I have modified files:

```<code>On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
      modified:   java/com/mycompany/TestContacts.java
      modified:   java/com/mycompany/TestParser.java
</code>```

答:
Throwing error because it has uncomitted changes.

So, You can use git stash

This saves uncomitted changes away for later use, and then reverts them from your working copy.

If you want these changes again, you can use git stash apply

Then You can use git pull

This takes the recent code from remote repo.

Body:
How do I reset my local branch to be just like the branch on the remote repository?

I tried:

git reset --hard HEAD

But git status claims I have modified files:

On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
      modified:   java/com/mycompany/TestContacts.java
      modified:   java/com/mycompany/TestParser.java


问:
How to make this Vue Composable for Firebase Storage awaitable?
I'm trying to create a composable in my Vue TypeScript project that uploads something to Firebase 9 Storage and returns the url.

Currently having two problems:

When calling the uploadImage function I want it to be "awaitable" so I can wait for the storage url before continuing. But I'm not sure how to configure the composable to make that happen.

I'm getting this Eslint error I would like to resolve on the uploadTask success callback: Promise returned in function argument where a void return was expected.

Most of the code is a modified version of this Firebase code example.

This is the calling function:

```<code>import { ref, Ref } from 'vue';
import useStorage from 'src/composables/useStorage';

const { url, uploadImage } = useStorage();
const profilePicFile: Ref<File | null> = ref(null);

const handleProfilePicUpdate = async () => {
  if (profilePicFile.value) {
    await uploadImage(profilePicFile.value); // <-- Calling the "uploadImage" composable here. But the "await" is currently uselss.
    profilePicUrl.value = url.value;
    userStore.setPhotoURL(profilePicUrl.value);
  }
};
</code>```

This is the composable:

```<code>import {
  ref as storageRef,
  uploadBytesResumable,
  getDownloadURL,
} from 'firebase/storage';
import { store } from 'src/firebase/config';
import { ref } from 'vue';
import getUser from './getUser';
import { uid } from 'quasar';

const { user } = getUser();

const useStorage = () => {
  const error = ref<string | null>(null);
  const url = ref<string | null>(null);
  const progress = ref<number | null>(null);

  const uploadImage = async (file: File) => { // <-- Marked the function as async, but I'm not sure which part should be awaited. Or failing that, maybe I should shomehow make the function return a promise with the url?
    if (user.value) {
      const filePath = `user_images/${user.value.uid}/${
        file.name + '_' + uid()
      }`;
      const storageReference = storageRef(store, filePath);
      try {
        const uploadTask = uploadBytesResumable(storageReference, file);
        uploadTask.on(
          'state_changed',
          // Observe state change events such as progress, pause, and resume
          (snapshot) => {
            progress.value =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          },
          // Handle unsuccessful uploads
          (err) => {
            if (err instanceof Error) {
              console.log(err.message);
              error.value = err.message;
            } else {
              throw err;
            }
          },
          // Handle successful uploads
          async () => { // <-- Eslint error on this entire function
            try {
              url.value = await getDownloadURL(storageReference);
            } catch (err) {
              if (err instanceof Error) {
                console.log(err.message);
                error.value = err.message;
              } else {
                throw err;
              }
            }
          }
        );
      } catch (err) {
        if (err instanceof Error) {
          console.log(err.message);
          error.value = err.message;
        } else {
          throw err;
        }
      }
    }
  };

  return { url, error, progress, uploadImage };
};

export default useStorage;
</code>```

答:
The first problem is caused by the fact that uploadImage() does not actually await anything at the "top level" of the function. While the function does call uploadBytesResumable(), passing async/await arguments, the result of the call itself (an UploadTask) is not await-ed, which leads to the problem you observed.

To make uploadImage() pause for the upload, you can either 1⃣ await the UploadTask result, or 2⃣ return the UploadTask itself:

const uploadImage = async (file: File) => {
  if (user.value) {
    ⋮
    try {
      const uploadTask = uploadBytesResumable(storageReference, file)
      uploadTask.on(⋯)

      await uploadTask 1⃣
      // or...
      return uploadTask 2⃣
    }
  }
}
```
<p>The difference is the latter allows the caller access to the Firebase snapshot data:</p>
<pre class="lang-js prettyprint-override"><code>const snapshot = await uploadImage()
</code>```

Body:
I'm trying to create a composable in my Vue TypeScript project that uploads something to Firebase 9 Storage and returns the url.

Currently having two problems:

When calling the uploadImage function I want it to be "awaitable" so I can wait for the storage url before continuing. But I'm not sure how to configure the composable to make that happen.

I'm getting this Eslint error I would like to resolve on the uploadTask success callback: Promise returned in function argument where a void return was expected.

Most of the code is a modified version of this Firebase code example.

This is the calling function:

import { ref, Ref } from 'vue';
import useStorage from 'src/composables/useStorage';

const { url, uploadImage } = useStorage();
const profilePicFile: Ref<File | null> = ref(null);

const handleProfilePicUpdate = async () => {
  if (profilePicFile.value) {
    await uploadImage(profilePicFile.value); // <-- Calling the "uploadImage" composable here. But the "await" is currently uselss.
    profilePicUrl.value = url.value;
    userStore.setPhotoURL(profilePicUrl.value);
  }
};

This is the composable:

import {
  ref as storageRef,
  uploadBytesResumable,
  getDownloadURL,
} from 'firebase/storage';
import { store } from 'src/firebase/config';
import { ref } from 'vue';
import getUser from './getUser';
import { uid } from 'quasar';

const { user } = getUser();

const useStorage = () => {
  const error = ref<string | null>(null);
  const url = ref<string | null>(null);
  const progress = ref<number | null>(null);

  const uploadImage = async (file: File) => { // <-- Marked the function as async, but I'm not sure which part should be awaited. Or failing that, maybe I should shomehow make the function return a promise with the url?
    if (user.value) {
      const filePath = `user_images/${user.value.uid}/${
        file.name + '_' + uid()
      }`;
      const storageReference = storageRef(store, filePath);
      try {
        const uploadTask = uploadBytesResumable(storageReference, file);
        uploadTask.on(
          'state_changed',
          // Observe state change events such as progress, pause, and resume
          (snapshot) => {
            progress.value =
              (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
          },
          // Handle unsuccessful uploads
          (err) => {
            if (err instanceof Error) {
              console.log(err.message);
              error.value = err.message;
            } else {
              throw err;
            }
          },
          // Handle successful uploads
          async () => { // <-- Eslint error on this entire function
            try {
              url.value = await getDownloadURL(storageReference);
            } catch (err) {
              if (err instanceof Error) {
                console.log(err.message);
                error.value = err.message;
              } else {
                throw err;
              }
            }
          }
        );
      } catch (err) {
        if (err instanceof Error) {
          console.log(err.message);
          error.value = err.message;
        } else {
          throw err;
        }
      }
    }
  };

  return { url, error, progress, uploadImage };
};

export default useStorage;

Body:
The first problem is caused by the fact that uploadImage() does not actually await anything at the "top level" of the function. While the function does call uploadBytesResumable(), passing async/await arguments, the result of the call itself (an UploadTask) is not await-ed, which leads to the problem you observed.

To make uploadImage() pause for the upload, you can either 1⃣ await the UploadTask result, or 2⃣ return the UploadTask itself:

const uploadImage = async (file: File) => {
  if (user.value) {
    ⋮
    try {
      const uploadTask = uploadBytesResumable(storageReference, file)
      uploadTask.on(⋯)

      await uploadTask 1⃣
      // or...
      return uploadTask 2⃣
    }
  }
}

The difference is the latter allows the caller access to the Firebase snapshot data:

const snapshot = await uploadImage()


问:
Identify Isotonic list or not
I am working on identifying if the list is Isotonic or not.

I have this:

```<code>true_list = [5,4,3,1,1]
true_list1=list[::-1]

f_list = [5,4,9,1,1]
f_list1=f_list[::-1]

def isMonotonic(item):
  if len(item)==1:
    return True
  else:
    if all(item[x]<=item[x+1]  for x in range(0,len(item)-1) or
           item[x]>=item[x+1] for x in range(0,len(item)-1) ):
        return True
    else:
      return False

print(true_list)
print(isMonotonic(true_list))
print(true_list1)
print(isMonotonic(true_list1))
print(f_list)
print(isMonotonic(f_list))
print(f_list1)
print(isMonotonic(f_list1))
</code>```

I don't understand why for true_list it returns False

For f_list and f_list1 : It should be False and it is False.

Please advise.

Thank You

答:
This is happening because your if condition is incorrect. The all would return True if all conditions in it are True.

What you need is "(all numbers are decreasing monotonically) OR (all numbers are increasing monotonically)"

```<code>true_list = [5,4,3,1,1]
true_list1=true_list[::-1]

f_list = [5,4,9,1,1]
f_list1=f_list[::-1]

def isMonotonic(item):
  if len(item)==1:
    return True
  else:
    if (all(item[x]<=item[x+1]  for x in range(0,len(item)-1)) or
           all(item[x]>=item[x+1] for x in range(0,len(item)-1))) :
        return True
    else:
      return False

print(true_list)
print(isMonotonic(true_list))
print(true_list1)
print(isMonotonic(true_list1))
print(f_list)
print(isMonotonic(f_list))
print(f_list1)
print(isMonotonic(f_list1))
</code>```

outputs -

```<code>[5, 4, 3, 1, 1]
True
[1, 1, 3, 4, 5]
True
[5, 4, 9, 1, 1]
False
[1, 1, 9, 4, 5]
False
</code>```

Title: Identify Isotonic list or not

Body:
I am working on identifying if the list is Isotonic or not.

I have this:

true_list = [5,4,3,1,1]
true_list1=list[::-1]

f_list = [5,4,9,1,1]
f_list1=f_list[::-1]

def isMonotonic(item):
  if len(item)==1:
    return True
  else:
    if all(item[x]<=item[x+1]  for x in range(0,len(item)-1) or
           item[x]>=item[x+1] for x in range(0,len(item)-1) ):
        return True
    else:
      return False

print(true_list)
print(isMonotonic(true_list))
print(true_list1)
print(isMonotonic(true_list1))
print(f_list)
print(isMonotonic(f_list))
print(f_list1)
print(isMonotonic(f_list1))

I don't understand why for true_list it returns False

For f_list and f_list1 : It should be False and it is False.

Please advise.

Thank You

Body:
This is happening because your if condition is incorrect. The all would return True if all conditions in it are True.

What you need is "(all numbers are decreasing monotonically) OR (all numbers are increasing monotonically)"

true_list = [5,4,3,1,1]
true_list1=true_list[::-1]

f_list = [5,4,9,1,1]
f_list1=f_list[::-1]

def isMonotonic(item):
  if len(item)==1:
    return True
  else:
    if (all(item[x]<=item[x+1]  for x in range(0,len(item)-1)) or
           all(item[x]>=item[x+1] for x in range(0,len(item)-1))) :
        return True
    else:
      return False

print(true_list)
print(isMonotonic(true_list))
print(true_list1)
print(isMonotonic(true_list1))
print(f_list)
print(isMonotonic(f_list))
print(f_list1)
print(isMonotonic(f_list1))

outputs -

[5, 4, 3, 1, 1]
True
[1, 1, 3, 4, 5]
True
[5, 4, 9, 1, 1]
False
[1, 1, 9, 4, 5]
False


问:
how to get cpu stats every 15 seconds ? python
see i am using

```<code>    import psutil
    d =  psutil.cpu_percent(1.5)
    e =  psutil.cpu_percent(1.5)
    f  =  psutil.cpu_percent(1.5)
    g  =  psutil.cpu_percent(1.5)

    val = (d + e +f+g)/4
    print(d , e , f, g)
    print(val)

</code>```

when I used interval's my import psutil was unreachable

答:
Just use a while loop with 15 seconds time gap using time module.

So, it should look like this:

try:
    import psutil, time
    while True:
        d = psutil.cpu_percent(1.5)
        e = psutil.cpu_percent(1.5)
        f = psutil.cpu_percent(1.5)
        g = psutil.cpu_percent(1.5)

        val = (d + e + f + g)/4
        print(d, e, f, g)
        print(val)

        time.sleep(15)
except Exception as e:
    print(str(e).capitalize())
except KeyboardInterrupt:
    print("Finished!")
```

Body:
see i am using

    import psutil
    d =  psutil.cpu_percent(1.5)
    e =  psutil.cpu_percent(1.5)
    f  =  psutil.cpu_percent(1.5)
    g  =  psutil.cpu_percent(1.5)

    val = (d + e +f+g)/4
    print(d , e , f, g)
    print(val)

when I used interval's my import psutil was unreachable


问:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured
I am working on a Spring Boot Batch example with MongoDB and I have already started the mongod server.

When I launch my application, I am getting the error below.

Any pointers for this issue?

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
</code>```

application.properties:

```<code># Mongo database URI. Cannot be set with host, port and credentials.
spring.data.mongodb.uri=mongodb://localhost/test
</code>```

pom.xml

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</code>```

I have started mongod with the following output:

```<code>C:\Users\pc>mongod
2018-07-07T14:39:39.223+0530 I JOURNAL  [initandlisten] journal dir=C:\data\db\journal
2018-07-07T14:39:39.230+0530 I JOURNAL  [initandlisten] recover : no journal files present, no recovery needed
2018-07-07T14:39:39.478+0530 I JOURNAL  [durability] Durability thread started
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] MongoDB starting : pid=11992 port=27017 dbpath=C:\data\db\ 64-bit host=DESKTOP-NQ639DU
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2018-07-07T14:39:39.591+0530 I CONTROL  [initandlisten] db version v3.0.5
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] git version: 8bc4ae20708dbb493cb09338d9e7be6698e4a3a3
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2018-07-07T14:39:39.593+0530 I CONTROL  [initandlisten] options: {}
2018-07-07T14:39:39.595+0530 I JOURNAL  [journal writer] Journal writer thread started
2018-07-07T14:39:40.485+0530 I NETWORK  [initandlisten] waiting for connections on port 27017
2018-07-07T14:40:39.140+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51340 #1 (1 connection now open)
2018-07-07T14:40:41.663+0530 I NETWORK  [conn1] end connection 127.0.0.1:51340 (0 connections now open)
2018-07-07T14:45:12.421+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51578 #2 (1 connection now open)
2018-07-07T14:45:12.870+0530 I NETWORK  [conn2] end connection 127.0.0.1:51578 (0 connections now open)
2018-07-07T14:46:21.734+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51591 #3 (1 connection now open)
2018-07-07T14:46:22.041+0530 I NETWORK  [conn3] end connection 127.0.0.1:51591 (0 connections now open)
2018-07-07T14:57:47.523+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:52534 #4 (1 connection now open)
2018-07-07T14:57:47.910+0530 I NETWORK  [conn4] end connection 127.0.0.1:52534 (0 connections now open)
</code>```

答:
Check spring profile also, by default it goes for 'default' profile, if your application properties have different profiles like the test, prod, etc then you need to set up it. for eclipse set environment variable as
name=spring.profiles.default, value=test</p>

Body:
I am working on a Spring Boot Batch example with MongoDB and I have already started the mongod server.

When I launch my application, I am getting the error below.

Any pointers for this issue?

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

application.properties:

# Mongo database URI. Cannot be set with host, port and credentials.
spring.data.mongodb.uri=mongodb://localhost/test

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-batch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

I have started mongod with the following output:

C:\Users\pc>mongod
2018-07-07T14:39:39.223+0530 I JOURNAL  [initandlisten] journal dir=C:\data\db\journal
2018-07-07T14:39:39.230+0530 I JOURNAL  [initandlisten] recover : no journal files present, no recovery needed
2018-07-07T14:39:39.478+0530 I JOURNAL  [durability] Durability thread started
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] MongoDB starting : pid=11992 port=27017 dbpath=C:\data\db\ 64-bit host=DESKTOP-NQ639DU
2018-07-07T14:39:39.589+0530 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2018-07-07T14:39:39.591+0530 I CONTROL  [initandlisten] db version v3.0.5
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] git version: 8bc4ae20708dbb493cb09338d9e7be6698e4a3a3
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] build info: windows sys.getwindowsversion(major=6, minor=1, build=7601, platform=2, service_pack='Service Pack 1') BOOST_LIB_VERSION=1_49
2018-07-07T14:39:39.592+0530 I CONTROL  [initandlisten] allocator: tcmalloc
2018-07-07T14:39:39.593+0530 I CONTROL  [initandlisten] options: {}
2018-07-07T14:39:39.595+0530 I JOURNAL  [journal writer] Journal writer thread started
2018-07-07T14:39:40.485+0530 I NETWORK  [initandlisten] waiting for connections on port 27017
2018-07-07T14:40:39.140+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51340 #1 (1 connection now open)
2018-07-07T14:40:41.663+0530 I NETWORK  [conn1] end connection 127.0.0.1:51340 (0 connections now open)
2018-07-07T14:45:12.421+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51578 #2 (1 connection now open)
2018-07-07T14:45:12.870+0530 I NETWORK  [conn2] end connection 127.0.0.1:51578 (0 connections now open)
2018-07-07T14:46:21.734+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:51591 #3 (1 connection now open)
2018-07-07T14:46:22.041+0530 I NETWORK  [conn3] end connection 127.0.0.1:51591 (0 connections now open)
2018-07-07T14:57:47.523+0530 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:52534 #4 (1 connection now open)
2018-07-07T14:57:47.910+0530 I NETWORK  [conn4] end connection 127.0.0.1:52534 (0 connections now open)


问:
Alternative to Eclipse PDT for exporting and generating PHAR archives
I want to create some PHAR Archives but did not find any good alternative to Eclipse for this purpose. Need a solution for maybe Aptana or a standalone solution.

Do yu know some programs for this?

Need it as a program for windows on my laptop.

答: PHP ships with a command line tool called .. phar, which allows you to create, inspect and modify .phar archives.