问:
How to reference stylesheet from subfolder express and ejs
I am having a problem referencing a stylesheet from a subfolder in views.
Here is my folder structure:

-Nattcup_git
  -index.js
  -views
    -control.ejs
    -index.ejs
    -brukere.ejs
    -404.ejs
    -oppsett
      -index.ejs
      -cup.ejs
    -partials
      -head.ejs
  -public
    -style.css
```
<p>Here is the (important) code in the app (index.js):</p>
```if (process.env.NODE_ENV !== 'production') {
    require('dotenv').config()
}
const path = require('path');
const methodOverride = require('method-override');
const express = require("express");
const oppsettRoute = require('./routes/oppsett');
const bcrypt = require('bcrypt')
const {JsonDB} = require("node-json-db");
const {Config} = require("node-json-db/dist/lib/JsonDBConfig")
const flash = require('express-flash')
const session = require('express-session')

const PORT = process.env.PORT || 5000;
const app = express();

let db = new JsonDB(new Config("db",true,false,'/'));
let tilgangDB = new JsonDB(new Config('tilgangsnivåer.json', true, false, '/'))

const passport = require('passport')

const initializePassport = require('./passport-config')
initializePassport(
    passport,
    brukernavn => db.getData('/brukere').find(user => user.brukernavn === brukernavn),
    id => db.getData('/brukere').find(user => user.id === id)
)

app.listen(PORT, () => console.log("Listening at " + PORT));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride('_method'));

app.set('view engine', 'ejs');

app.use(flash())
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())

app.use(express.urlencoded({ extended: false }));

app.get('/', (req, res) => {
    res.render('index', {tittel: "Hjem", tilgang: typeTilgang(req), brukernavn: brukernavn(req)});
})

app.get('/index', (req, res) => {
    res.render('index', {tittel: "Hjem", tilgang: typeTilgang(req), brukernavn: brukernavn(req)});
})

app.get('/tabell', (req, res) => {
    res.render('tabell', {tittel: "Tabell", tilgang: typeTilgang(req), brukernavn: brukernavn(req), kamper: db.getData('/cuper/Nattcup2022/kamper')})
})

app.get('/control', harTilgang, (req, res) => {
    res.render('control', {tittel: "Kontrollpanel", tilgang: typeTilgang(req), brukernavn: req.user.brukernavn, status: db.getData('/cuper/Nattcup2022/status')});
})

app.get('/live', (req, res) => {
    res.render('live', {tittel: "Live"})
})

app.get('/login', notAuthenticated, (req, res) => {
    res.render('login', {tittel: "Logg inn", tilgang: typeTilgang(req)})
})

app.get('/registrer', harTilgang, (req, res) => {
    res.render('registrer', {tittel: "Registrer bruker", tilgang: typeTilgang(req), brukernavn: brukernavn(req), roller: tilgangDB.getData('/roller')})
})

app.get('/brukere', harTilgang, (req, res) => {
    res.render('brukere', {tittel: "Brukere", tilgang: typeTilgang(req), brukernavn: brukernavn(req), brukere: hentBrukere()})
})

app.use('/oppsett', oppsettRoute);

app.get("/data", (req, res) => {
    try {
        let path = req.header("path");
        let data = db.getData("/cuper/Nattcup2022/" + path);
        res.json(data);
    } catch(error) {
        console.error(error);
    }
})

app.post("/data/endre", forwardAuthenticated, (request, response) => {
     if (request.body.type === "mal"){
        let lag = request.body["lag"];
        let operator = request.body["operator"];
        let kampid = request.body["kampid"];
        let path = `/cuper/Nattcup2022/mal/${kampid}/mal${lag}`
        db.push(path, db.getData(path) + Number(operator + 1));
        oppdaterStatus();

    } else if (request.body.type === "endre"){
        let nr = db.getData("/cuper/Nattcup2022/status/livekamp/kampnr") + request.body.nr;
        oppdaterStatus(nr);
    } else if(request.body.type === "innstilling"){
        db.push('/cuper/Nattcup2022/status/innstillinger/' + request.body["innstilling"], request.body["status"]);
    }
})

app.post('/registrer', harTilgang, async (req, res) => {
    try {
        let brukernavn = req.body.brukernavn;
        let passord = req.body.passord;
        if(brukernavn === ""){
            req.flash('error', 'Brukernavn kan ikke være tomt');
            res.redirect('/registrer');
        }
        else if(db.getData('/brukere').find(bruker => bruker.brukernavn === brukernavn)) {
            req.flash("error", "Brukernavnet er allerede i bruk");
            res.redirect('/registrer');
        }
        else if(passord === ""){
            req.flash('error', 'Passordfeltet kan ikke være tomt');
            res.redirect('/registrer');
        }
        else if(passord.length < 8){
            req.flash('error', 'Passord må være minst 8 tegn langt');
            res.redirect('/registrer');
        }
        else {
            const hash = await bcrypt.hash(passord, 10)
            db.push('/brukere[]', {
                id: Date.now().toString(),
                brukernavn: req.body.brukernavn,
                passord: hash,
                tilgang: req.body.rolle
            })
            res.redirect('/brukere');
        }
    } catch (e) {
        req.flash('error', "Noe gikk galt ved registrering. /n Vennligst prøv på nytt /n(" + e + ")")
        res.redirect('/registrer')

    }
})

app.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/login',
    failureFlash: true
}))

app.delete('/logout', (req, res) => {
    req.logOut();
    res.redirect('/');
})

app.delete('/slett_bruker', harTilgang, (req, res) => {
    let brukere = db.getData('/brukere')
    let id = req.body.id;
    if(brukere.find(bruker => bruker.id === id)){
        let bruker = brukere.find(bruker => bruker.id === id);
        let index = brukere.indexOf(bruker)
        db.delete('/brukere[' + index + ']')
    }
})

app.use((req, res) => {
    res.status(404).render('404', {tittel: "404", tilgang: typeTilgang(req), brukernavn: brukernavn(req)})
})
```
<p>Then in cup.ejs:</p>
```<!doctype html>

<%- include('../partials/head')%>

<%- include('../partials/meny')%>

<%- include('../partials/footer')%>

```
<p>The file head.ejs that i am including above looks like this:</p>
```
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Cup | <%= tittel %></title>

```

Why won't style.css be applied to cup.ejs?

Thanks

.............................................................................................................................................................................................................................................................................................................................................................................

答:
Either index.js must contain

app.use("/oppsett/cuper", express.static(path.join(__dirname, "public")));
```
<p>or, better, <code>routes/oppsett/index.js</code> (the file that contains the <code>oppsettRoute</code>, which you have not given) must contain</p>
<pre class="lang-js prettyprint-override"><code>app.use("/cuper", express.static("relative path from /routes to /public"));
</code>```

The latter is better because the stylesheet belongs to the cup.ejs HTML page, and that also comes from the oppsettRoute.

Body:
I am having a problem referencing a stylesheet from a subfolder in views.
Here is my folder structure:

-Nattcup_git
  -index.js
  -views
    -control.ejs
    -index.ejs
    -brukere.ejs
    -404.ejs
    -oppsett
      -index.ejs
      -cup.ejs
    -partials
      -head.ejs
  -public
    -style.css

Here is the (important) code in the app (index.js):

if (process.env.NODE_ENV !== 'production') {
    require('dotenv').config()
}
const path = require('path');
const methodOverride = require('method-override');
const express = require("express");
const oppsettRoute = require('./routes/oppsett');
const bcrypt = require('bcrypt')
const {JsonDB} = require("node-json-db");
const {Config} = require("node-json-db/dist/lib/JsonDBConfig")
const flash = require('express-flash')
const session = require('express-session')

const PORT = process.env.PORT || 5000;
const app = express();

let db = new JsonDB(new Config("db",true,false,'/'));
let tilgangDB = new JsonDB(new Config('tilgangsnivåer.json', true, false, '/'))

const passport = require('passport')

const initializePassport = require('./passport-config')
initializePassport(
    passport,
    brukernavn => db.getData('/brukere').find(user => user.brukernavn === brukernavn),
    id => db.getData('/brukere').find(user => user.id === id)
)

app.listen(PORT, () => console.log("Listening at " + PORT));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride('_method'));

app.set('view engine', 'ejs');

app.use(flash())
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())

app.use(express.urlencoded({ extended: false }));

app.get('/', (req, res) => {
    res.render('index', {tittel: "Hjem", tilgang: typeTilgang(req), brukernavn: brukernavn(req)});
})

app.get('/index', (req, res) => {
    res.render('index', {tittel: "Hjem", tilgang: typeTilgang(req), brukernavn: brukernavn(req)});
})

app.get('/tabell', (req, res) => {
    res.render('tabell', {tittel: "Tabell", tilgang: typeTilgang(req), brukernavn: brukernavn(req), kamper: db.getData('/cuper/Nattcup2022/kamper')})
})

app.get('/control', harTilgang, (req, res) => {
    res.render('control', {tittel: "Kontrollpanel", tilgang: typeTilgang(req), brukernavn: req.user.brukernavn, status: db.getData('/cuper/Nattcup2022/status')});
})

app.get('/live', (req, res) => {
    res.render('live', {tittel: "Live"})
})

app.get('/login', notAuthenticated, (req, res) => {
    res.render('login', {tittel: "Logg inn", tilgang: typeTilgang(req)})
})

app.get('/registrer', harTilgang, (req, res) => {
    res.render('registrer', {tittel: "Registrer bruker", tilgang: typeTilgang(req), brukernavn: brukernavn(req), roller: tilgangDB.getData('/roller')})
})

app.get('/brukere', harTilgang, (req, res) => {
    res.render('brukere', {tittel: "Brukere", tilgang: typeTilgang(req), brukernavn: brukernavn(req), brukere: hentBrukere()})
})

app.use('/oppsett', oppsettRoute);

app.get("/data", (req, res) => {
    try {
        let path = req.header("path");
        let data = db.getData("/cuper/Nattcup2022/" + path);
        res.json(data);
    } catch(error) {
        console.error(error);
    }
})

app.post("/data/endre", forwardAuthenticated, (request, response) => {
     if (request.body.type === "mal"){
        let lag = request.body["lag"];
        let operator = request.body["operator"];
        let kampid = request.body["kampid"];
        let path = `/cuper/Nattcup2022/mal/${kampid}/mal${lag}`
        db.push(path, db.getData(path) + Number(operator + 1));
        oppdaterStatus();

    } else if (request.body.type === "endre"){
        let nr = db.getData("/cuper/Nattcup2022/status/livekamp/kampnr") + request.body.nr;
        oppdaterStatus(nr);
    } else if(request.body.type === "innstilling"){
        db.push('/cuper/Nattcup2022/status/innstillinger/' + request.body["innstilling"], request.body["status"]);
    }
})

app.post('/registrer', harTilgang, async (req, res) => {
    try {
        let brukernavn = req.body.brukernavn;
        let passord = req.body.passord;
        if(brukernavn === ""){
            req.flash('error', 'Brukernavn kan ikke være tomt');
            res.redirect('/registrer');
        }
        else if(db.getData('/brukere').find(bruker => bruker.brukernavn === brukernavn)) {
            req.flash("error", "Brukernavnet er allerede i bruk");
            res.redirect('/registrer');
        }
        else if(passord === ""){
            req.flash('error', 'Passordfeltet kan ikke være tomt');
            res.redirect('/registrer');
        }
        else if(passord.length < 8){
            req.flash('error', 'Passord må være minst 8 tegn langt');
            res.redirect('/registrer');
        }
        else {
            const hash = await bcrypt.hash(passord, 10)
            db.push('/brukere[]', {
                id: Date.now().toString(),
                brukernavn: req.body.brukernavn,
                passord: hash,
                tilgang: req.body.rolle
            })
            res.redirect('/brukere');
        }
    } catch (e) {
        req.flash('error', "Noe gikk galt ved registrering. /n Vennligst prøv på nytt /n(" + e + ")")
        res.redirect('/registrer')

    }
})

app.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/login',
    failureFlash: true
}))

app.delete('/logout', (req, res) => {
    req.logOut();
    res.redirect('/');
})

app.delete('/slett_bruker', harTilgang, (req, res) => {
    let brukere = db.getData('/brukere')
    let id = req.body.id;
    if(brukere.find(bruker => bruker.id === id)){
        let bruker = brukere.find(bruker => bruker.id === id);
        let index = brukere.indexOf(bruker)
        db.delete('/brukere[' + index + ']')
    }
})

app.use((req, res) => {
    res.status(404).render('404', {tittel: "404", tilgang: typeTilgang(req), brukernavn: brukernavn(req)})
})

Then in cup.ejs:

<!doctype html>

<%- include('../partials/head')%>

<%- include('../partials/meny')%>

<%- include('../partials/footer')%>

The file head.ejs that i am including above looks like this:

    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Cup | <%= tittel %></title>

Why won't style.css be applied to cup.ejs?

Thanks

.............................................................................................................................................................................................................................................................................................................................................................................

Body:
Either index.js must contain

app.use("/oppsett/cuper", express.static(path.join(__dirname, "public")));

or, better, routes/oppsett/index.js (the file that contains the oppsettRoute, which you have not given) must contain

app.use("/cuper", express.static("relative path from /routes to /public"));

The latter is better because the stylesheet belongs to the cup.ejs HTML page, and that also comes from the oppsettRoute.


来源: stackexchange

问:
How to use camelize function for CAPITAL case payload/string
Sample Request:

```<code>{
    "message": "HELLO world!"
}
</code>```

DataWeave script:

```<code>%dw 2.0
output application/json
import * from dw::core::Strings
---
camelize(payload.message)
</code>```

Output Received:

```<code>"hELLO world!"
</code>```

Expected Output:

```<code>"hello world!"
</code>```

答:
as per your requirement you need all letters of a given string in lowercase, for that use "lower()" funciton that returns the provided string in lowercase characters as in below code

```<code>%dw 2.0
output application/json
---
lower(payload.message)
</code>```

the output will be as you are expecting.

This is the screen shot for input, dw script and ouput

below are the official Mulesoft documents link

Camelize:  https://docs.mulesoft.com/dataweave/2.2/dw-strings-functions-camelize

Lower : https://docs.mulesoft.com/dataweave/2.4/dw-core-functions-lower

ContentLicense: CC BY-SA 4.0

Body:
Sample Request:

{
    "message": "HELLO world!"
}

DataWeave script:

%dw 2.0
output application/json
import * from dw::core::Strings
---
camelize(payload.message)

Output Received:

"hELLO world!"

Expected Output:

"hello world!"

Body:
as per your requirement you need all letters of a given string in lowercase, for that use "lower()" funciton that returns the provided string in lowercase characters as in below code

%dw 2.0
output application/json
---
lower(payload.message)

the output will be as you are expecting.

This is the screen shot for input, dw script and ouput

below are the official Mulesoft documents link

Camelize:  https://docs.mulesoft.com/dataweave/2.2/dw-strings-functions-camelize

Lower : https://docs.mulesoft.com/dataweave/2.4/dw-core-functions-lower


问:
Is it possible to simulate a browser version update?
I'm developing an add-on and I want to test how code that gets executed during the onInstalled event behaves after a browser version update.

Is there a way to simulate the browser update event, without waiting when an actual newer version of the browser will be out?

答:
I don't find any way to simulate browser update event. Here I use Edge as an example. As a workaround, you can download Edge Canary version to test which updates everyday.

Besides, if your device is Microsoft AD domain joined, you can also configure this policy to roll back Edge version, then update it when you test.


问:
How do I add a custom scale line in openlayers?
I am developing a geographic web app and want to add a scale line into it. The default openlayers scale line does not fit my design nor does it look professional. So I would like to add a classic scale line like this one for example:

What is the best way to do this? Adding a SVG, get current zoom and calculate the SVGs proper size?

I tried styling the scale line with CSS, that's working, but i can only change its color and so on, while I want to change the whole design.

This is the code in my Map component but all in all its just the classic declaration:

```<code>const me = this;

const scalelineControl = new ScaleLine({
    minWidth: 64,
    units: 'metric',
});
me.currentView = new View({
    center: proj.transform(this.mapCenter, 'EPSG:4326', 'EPSG:3857'),
    zoom: this.mapZoom,
    projection: 'EPSG:3857',
});
Vue.prototype.$currentView = me.currentView;
me.map = new Map({
    layers: [
    new TileLayer({
        source: new OsmSource(),
    }),
    new Vector({ source: this.srLayerSource }),
    ],
    view: me.currentView,
    loadTilesWhileAnimating: true,
    controls: [scalelineControl],
});
</code>```

I am using Vue.js to create the web app. The map gets declared in its component's created() part and is added in mounted(), but that does not really matter in this topic. Just for notice.

答: Check this open layer document this really helped me</p>

Body:
I am developing a geographic web app and want to add a scale line into it. The default openlayers scale line does not fit my design nor does it look professional. So I would like to add a classic scale line like this one for example:

What is the best way to do this? Adding a SVG, get current zoom and calculate the SVGs proper size?

I tried styling the scale line with CSS, that's working, but i can only change its color and so on, while I want to change the whole design.

This is the code in my Map component but all in all its just the classic declaration:

const me = this;

const scalelineControl = new ScaleLine({
    minWidth: 64,
    units: 'metric',
});
me.currentView = new View({
    center: proj.transform(this.mapCenter, 'EPSG:4326', 'EPSG:3857'),
    zoom: this.mapZoom,
    projection: 'EPSG:3857',
});
Vue.prototype.$currentView = me.currentView;
me.map = new Map({
    layers: [
    new TileLayer({
        source: new OsmSource(),
    }),
    new Vector({ source: this.srLayerSource }),
    ],
    view: me.currentView,
    loadTilesWhileAnimating: true,
    controls: [scalelineControl],
});

I am using Vue.js to create the web app. The map gets declared in its component's created() part and is added in mounted(), but that does not really matter in this topic. Just for notice.


问:
Error NETSDK1045: The current .NET SDK does not support targeting .NET 6.0
I spent 2 hours trying to figure out what's wrong with my pipeline for Azure Functions .NET6 (on Windows).</p>
```<code>Error NETSDK1045: The current .NET SDK does not support targeting .NET 6.0.  Either target .NET 5.0 or lower, or use a version of the .NET SDK that supports .NET 6.0.
</code>```

答: I had this error when running a project, and installing the .Net 6.0 SDK solved my issue. https://dotnet.microsoft.com/en-us/download/dotnet/thank-you/sdk-6.0.102-windows-x64-installer</p>

Body:
I spent 2 hours trying to figure out what's wrong with my pipeline for Azure Functions .NET6 (on Windows).

Error NETSDK1045: The current .NET SDK does not support targeting .NET 6.0.  Either target .NET 5.0 or lower, or use a version of the .NET SDK that supports .NET 6.0.


问:
Should virtual dispatch happen when a virtual method is called within a virtual method using object?
```<code>struct B
{
  virtual void bar () {}
  virtual void foo () { bar(); }
};

struct D : B
{
  virtual void bar () {}
  virtual void foo () {}
};
</code>```

Now we call foo() using an object of B as,

```<code>B obj;
obj.foo();  // calls B::bar()
</code>```

Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the static type of the object (i.e. B).

答:
In this case:

```<code>B obj;
obj.foo();  // calls B::bar()
</code>```

the compiler can optimize away the virtual dispatch since it knows that type of the actual object is B.

However, inside of B::foo() the call to bar() needs to use virtual dispatch generally (though the compiler might be able to inline the call and for that particular call instance could possibly optimize the virtual dispatch away again). Specifically, this statement you proposed:

Irrespective of foo() is called using object or pointer/reference, all the calls inside any virtual B::foo() should be statically resolved. Because, once you are inside B::foo(), it's sure that this is of type B* and not D*

is not true.

Consider:

```<code>struct D2 : B
{
    // D2 does not override bar()
    virtual void foo () {
        cout << "hello from D2::bar()" << endl;
    }
};
</code>```

Now if you had the following somewhere:

```<code>D2 test;

B& bref = test;

bref.foo();
</code>```

That call to foo() would end up in B::foo(), but when B::foo() calls bar(), it needs to dispatch to D2::bar().

Actually, now that I've typed this out, the B& is completely unnecessary for this example.

Body:
struct B
{
  virtual void bar () {}
  virtual void foo () { bar(); }
};

struct D : B
{
  virtual void bar () {}
  virtual void foo () {}
};

Now we call foo() using an object of B as,

B obj;
obj.foo();  // calls B::bar()

Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the static type of the object (i.e. B).

Body:
In this case:

B obj;
obj.foo();  // calls B::bar()

the compiler can optimize away the virtual dispatch since it knows that type of the actual object is B.

However, inside of B::foo() the call to bar() needs to use virtual dispatch generally (though the compiler might be able to inline the call and for that particular call instance could possibly optimize the virtual dispatch away again). Specifically, this statement you proposed:

Irrespective of foo() is called using object or pointer/reference, all the calls inside any virtual B::foo() should be statically resolved. Because, once you are inside B::foo(), it's sure that this is of type B* and not D*

is not true.

Consider:

struct D2 : B
{
    // D2 does not override bar()
    virtual void foo () {
        cout << "hello from D2::bar()" << endl;
    }
};

Now if you had the following somewhere:

D2 test;

B& bref = test;

bref.foo();

That call to foo() would end up in B::foo(), but when B::foo() calls bar(), it needs to dispatch to D2::bar().

Actually, now that I've typed this out, the B& is completely unnecessary for this example.

ContentLicense: CC BY-SA 3.0


问:
How to implement a themed monochrome icon for Material You
How would I implement a monochrome icon like other google apps so that it matches the dynamic colours picked by Material You?</p>

答:
Open your app icon and add the monochrome android:drawable attribute to the <adaptive-icon> element. For example, in res/mipmap-anydpi-v26/ic_launcher.xml:

```<code><adaptive-icon >
    <background android:drawable="..." />
    <foreground android:drawable="..." />
    <monochrome android:drawable="@drawable/mymonochromeicon" />
</adaptive-icon>
</code>```

If your try this and it does not work then you need to remove the android:roundIcon element from your AndroidManifest.xml, or, alternatively, also add the <monochrome android:drawable="@drawable/mymonochromeicon"/> tag to your round icon.

Android Studio might give a warning saying Element monochrome is not allowed here however we can ignore this.

Body:
Open your app icon and add the monochrome android:drawable attribute to the <adaptive-icon> element. For example, in res/mipmap-anydpi-v26/ic_launcher.xml:

<adaptive-icon >
    <background android:drawable="..." />
    <foreground android:drawable="..." />
    <monochrome android:drawable="@drawable/mymonochromeicon" />
</adaptive-icon>

If your try this and it does not work then you need to remove the android:roundIcon element from your AndroidManifest.xml, or, alternatively, also add the <monochrome android:drawable="@drawable/mymonochromeicon"/> tag to your round icon.

Android Studio might give a warning saying Element monochrome is not allowed here however we can ignore this.


问:
spark.readstream and writestream for json issue in databricks
I have a json

```<code>{
"name": "John",
"age": 30,
"car": "testing"}
</code>```

I have a code in databricks

```<code>struct2 = StructType([StructField("name", StringType(), True), \
StructField("age", IntegerType(), True, None), \
                  StructField("car", StringType(), True, None)])
df2 = spark.readStream.schema(struct2).format('json') \
  .load("abfss://i**********.dfs.core.windows.net/streamjson/")
</code>```

and the next step I start the writestream to another folder

```<code>df2.select("name","age","car").writeStream.format('json')\
  .option("checkpointLocation", "abfss://****@*****.dfs.core.windows.net/outputstream/jsoncheckpoint3") \
  .start("abfss://***@******.dfs.core.windows.net/streamjsonoutput/")
</code>```

I put new files there , and I check the files in streamjsonoutput , the files are like in the following

anyone can point out what I done wrongly ?

答:
You need to add .option("multiLine", "true") to your spark.readStream, because by default, Spark expects that JSON file consists of individual JSON objects per each line, not spanning multiple lines (see docs):

df2 = spark.readStream.schema(struct2).option("multiLine", "true") \
  .json("abfss://...")
```

Body:
I have a json

{
"name": "John",
"age": 30,
"car": "testing"}

I have a code in databricks

struct2 = StructType([StructField("name", StringType(), True), \
StructField("age", IntegerType(), True, None), \
                  StructField("car", StringType(), True, None)])
df2 = spark.readStream.schema(struct2).format('json') \
  .load("abfss://i**********.dfs.core.windows.net/streamjson/")

and the next step I start the writestream to another folder

df2.select("name","age","car").writeStream.format('json')\
  .option("checkpointLocation", "abfss://****@*****.dfs.core.windows.net/outputstream/jsoncheckpoint3") \
  .start("abfss://***@******.dfs.core.windows.net/streamjsonoutput/")

I put new files there , and I check the files in streamjsonoutput , the files are like in the following

anyone can point out what I done wrongly ?


问:
How to select all data before current_state in history data in Oracle SQL?
So I have data look like in Picture.
Column name Track is to show the step of the state.
Column name Current_state is the status of the app right now.
Column name Current_state_hist is the history of the status.

So right now the current status now is AP.
I want to Select all the status before the last status right now (AP in Track 13 & 14) without remove the status AP in track 5 - 8.

Can somebody help me for this case? Thank you
Example of the data

答:
You can use EXISTS for that:

Schema and insert statements:

```<code> create table table1(id int, track int, current_state varchar(10), current_state_hist varchar(10), total_unit int);

 insert into table1 values(1,1,'AP','OD',1)
 insert into table1 values(1,2,'AP','OD',1)
 insert into table1 values(1,3,'AP','OD',1)
 insert into table1 values(1,4,'AP','OD',1)
 insert into table1 values(1,5,'AP','AP',1)
 insert into table1 values(1,6,'AP','AP',1)
 insert into table1 values(1,7,'AP','AP',1)
 insert into table1 values(1,8,'AP','AP',1)
 insert into table1 values(1,9,'AP','OD',1)
 insert into table1 values(1,10,'AP','OD',1)
 insert into table1 values(1,11,'AP','OD',1)
 insert into table1 values(1,12,'AP','OD',1)
 insert into table1 values(1,13,'AP','AP',1)
 insert into table1 values(1,14,'AP','AP',1)
</code>```

Query:

```<code> SELECT ID,TRACK,CURRENT_STATE,CURRENT_STATE_HIST,TOTAL_UNIT
 FROM TABLE1  T1
 WHERE EXISTS
            (
                SELECT 1 FROM TABLE1 T2
                WHERE CURRENT_STATE<>CURRENT_STATE_HIST
                AND T1.TRACK<=T2.TRACK
            )
</code>```

Output:

ID
TRACK
CURRENT_STATE
CURRENT_STATE_HIST
TOTAL_UNIT

1
1
AP
OD
1

1
2
AP
OD
1

1
3
AP
OD
1

1
4
AP
OD
1

1
5
AP
AP
1

1
6
AP
AP
1

1
7
AP
AP
1

1
8
AP
AP
1

1
9
AP
OD
1

1
10
AP
OD
1

1
11
AP
OD
1

1
12
AP
OD
1

db<>fiddle here

Body:
You can use EXISTS for that:

Schema and insert statements:

 create table table1(id int, track int, current_state varchar(10), current_state_hist varchar(10), total_unit int);

 insert into table1 values(1,1,'AP','OD',1)
 insert into table1 values(1,2,'AP','OD',1)
 insert into table1 values(1,3,'AP','OD',1)
 insert into table1 values(1,4,'AP','OD',1)
 insert into table1 values(1,5,'AP','AP',1)
 insert into table1 values(1,6,'AP','AP',1)
 insert into table1 values(1,7,'AP','AP',1)
 insert into table1 values(1,8,'AP','AP',1)
 insert into table1 values(1,9,'AP','OD',1)
 insert into table1 values(1,10,'AP','OD',1)
 insert into table1 values(1,11,'AP','OD',1)
 insert into table1 values(1,12,'AP','OD',1)
 insert into table1 values(1,13,'AP','AP',1)
 insert into table1 values(1,14,'AP','AP',1)

Query:

 SELECT ID,TRACK,CURRENT_STATE,CURRENT_STATE_HIST,TOTAL_UNIT
 FROM TABLE1  T1
 WHERE EXISTS
            (
                SELECT 1 FROM TABLE1 T2
                WHERE CURRENT_STATE<>CURRENT_STATE_HIST
                AND T1.TRACK<=T2.TRACK
            )

Output:

ID
TRACK
CURRENT_STATE
CURRENT_STATE_HIST
TOTAL_UNIT

1
1
AP
OD
1

1
2
AP
OD
1

1
3
AP
OD
1

1
4
AP
OD
1

1
5
AP
AP
1

1
6
AP
AP
1

1
7
AP
AP
1

1
8
AP
AP
1

1
9
AP
OD
1

1
10
AP
OD
1

1
11
AP
OD
1

1
12
AP
OD
1

db<>fiddle here


问:
Cannot set Picker Default value
I have a picker on my Xamarin form, bound to a list, and I would like that it has the first item of that list already selected when the form is opening.

My list looks like this

```<code>Languages = new List<string>();
Languages.Add("English");
Languages.Add("Nederlands");
Languages.Add("русский");
</code>```

I tried like this

```<code><Picker x:Name="PickerLanguage" Title=""
        TitleColor="#004973"
        FontSize="24"
        ItemsSource="{Binding Languages}"
        SelectedIndex="0"
        SelectedItem="English">
</Picker>
</code>```

and like this

```<code><Picker x:Name="PickerLanguage" Title=""
        TitleColor="#004973"
        FontSize="24"
        ItemsSource="{Binding Languages}"
        SelectedIndex="0"
        SelectedItem="0">
</Picker>
</code>```

Both attemps above are based on the answer of this question

But is does not works.

How can I have it so that when the form opens, English is set as selected item/index already ?

答:
create a property for your selected item in your c# then bind it to your picker :

```<code>private string selectedObj;
public string SelectedObj
{
  get{ return selectedObj;}
  set{ selectedObj= value ;
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedObj"));}

}

</code>```

then you can set your value to the selected object any place in your code:

```<code>SelectedObj = "English";
</code>```

then bind it to picker in xaml:

```<code><Picker x:Name="PickerLanguage" Title=""
        TitleColor="#004973"
        FontSize="24"
        ItemsSource="{Binding Languages}"

        SelectedItem="{Binding SelectedObj}">
</Picker>
</code>```

Title: Cannot set Picker Default value

Body:
I have a picker on my Xamarin form, bound to a list, and I would like that it has the first item of that list already selected when the form is opening.

My list looks like this

Languages = new List<string>();
Languages.Add("English");
Languages.Add("Nederlands");
Languages.Add("русский");

I tried like this

<Picker x:Name="PickerLanguage" Title=""
        TitleColor="#004973"
        FontSize="24"
        ItemsSource="{Binding Languages}"
        SelectedIndex="0"
        SelectedItem="English">
</Picker>

and like this

<Picker x:Name="PickerLanguage" Title=""
        TitleColor="#004973"
        FontSize="24"
        ItemsSource="{Binding Languages}"
        SelectedIndex="0"
        SelectedItem="0">
</Picker>

Both attemps above are based on the answer of this question

But is does not works.

How can I have it so that when the form opens, English is set as selected item/index already ?

Body:
create a property for your selected item in your c# then bind it to your picker :

private string selectedObj;
public string SelectedObj
{
  get{ return selectedObj;}
  set{ selectedObj= value ;
     PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedObj"));}

}

then you can set your value to the selected object any place in your code:

SelectedObj = "English";

then bind it to picker in xaml:

<Picker x:Name="PickerLanguage" Title=""
        TitleColor="#004973"
        FontSize="24"
        ItemsSource="{Binding Languages}"

        SelectedItem="{Binding SelectedObj}">
</Picker>


问:
how to chose over set_false_path, set_multicylce_path, set_max_skew
This problem has been bothering me for a long time， based on my understanding:

set_false_path is a timing constraints which is not required to be optimized for timing. we can use it for two flop synchronizer since it is not required to get captured in a limited time.

set_clock_groups It saves us from defining too many false paths.

set_multicylce_path used to relax the path requirement when the default worst requirement is too restrictive. we can set the set/hold clk to fix the timing. we can use it in cross domain

set_max_skew/set_max_delay -datapath_only used on asynchronous FIFO style that does the whole convert read/write pointers from binary to gray. Looks like set_max_skew help with control the skew between the multiple bits of the gray code to the double-flop synchronizers. Why do you need the "datapath_only"? Just using set_multicycle_path will also pass the timing check.

So in summary, all those methods can be used in async fifo right?
And the set_false_path is the most simple way. No need to worry about the mcp cycle or max delay. I guess we use it only when the logic between 2 FF is "combinational"? Can we use it when there are sequence logic between 2 cross domain FF?

If ignoring all timing calculations using FP is bad, when is it a good time to use it? In theory I can replace all the FP with MCP.

What factors do you need to consider in order to choose the most suitable constraints?

答:
So apparently there are 4 following questions in your post:

Question 1: So in summary, all those methods can be used in async fifo right?

Question 2: And the set_false_path is the most simple way. No need to worry about the mcp cycle or max delay. I guess we use it only when the logic between 2 FF is "combinational"? Can we use it when there are sequence logic between 2 cross domain FF?

Question 3: If ignoring all timing calculations using FP is bad, when is it a good time to use it? In theory I can replace all the FP with MCP.

Question 4: What factors do you need to consider in order to choose the most suitable constraints?

Following are the 4 answers to aforementioned questions:

Answer 1: As shown below in figure, with an asynchronous FIFO, data can arrive at arbitrary time intervals on the transmission side, and the receiving side pulls data out of the queue as it has the bandwidth to process it.

Therefore, Yes, you can use all those optimizations/constraints/methods for asynchronous FIFO.

Answer 2: Yes set_false_path can be considered as one of the most simplest. And as the following figure shows, you are right we use when the logic between 2 FF is "combinational"?

Furthermore, based on my understanding, we do not use for sequence logic.

Answer 3: A false path is similar to the multicycle path in that it is not required to propagate signals within a single clock period. The difference is that a false path is not logically possible as dictated by the design. In other words, even though the timing analysis tool sees a physical path from one point to the other through a series of logic gates, it is not logically possible for a signal to propagate between those two points during normal operation. The main difference between a multicycle path with many available cycles (large n) versus a false path is that the multicycle path will still be checked against setup and hold requirements and will still be included in the timing analysis. It is possible for a multicycle path to still
fail timing, but a false path will never have any associated timing violations.

Hence use a multicycle path in place of a false path constraint when:

your intent is only to relax the timing requirements on a synchronous path;
but

the path still must be timed, verified and optimized.

Answer 4:
Although a very valid question yet too broad. It all depends on the underlying design. Most implementation tools for FPGA layout have a plenty of optimization options. And obviously not all constraints are used by all steps
in the compilation flow. Based on my experience and citing from Reference 1 the constraints that must be included in every design include all clock definitions,
I/O delays, pin placements, and any relaxed constraints including multicycle
and false paths.

Following two main references can further explain you to understand the the use of constraints:

Reference 1

Reference 2


问:
Extract the data from array_buffer and stored in the variable
I am receiving data continuously using UART and stored in the buffer in the following form::

```<code> $GNRMC,114811.00,A,3558.94849,N,14008.90158,E,0.076,,141115,,,A*69
 $GNVTG,,T,,M,0.076,N,0.141,K,A*38
 $GNGSA,A,3,,,,,,,,,,,,,3.03,1.18,2.80*1E
 $GPGSV,3,2,09,20,04,163,,22,49,280,29,24,45,048,33,25,53,183,28*75
 $GNGLL,3558.94849,N,14008.90158,E,114811.00,A,A*70*
</code>```

I want to extract only the $GNRMCdata and store it on some variable  year, mon, day, hour, min, sec so that I can display that in 16*2LCD. The value right after $GNRMC 114811 is the time. But I am not getting the data on those variables. Where I am wrong?

```<code>void gps_getinfo(unsigned char rx2_id_buff[]);
void uart2_rx_int(void);
#define MAX_LINEBUF 70
char gps_linebuf[MAX_LINEBUF];
unsigned char time_flag;
unsigned char rx2_id_buff[70];
unsigned char rx2_id_pointer;
unsigned char year[4]={0},mon[4]={0},day[4]={0};
unsigned char hour[4]={0},min[4]={0},sec[4]={0};
#pragma interrupt uart2_rx_int  (vect=0x16)

void uart2_rx_int(void)
{
    unsigned char error;
    error = SSR11 & 0x07;
    rx2_id = SDR11;
    if (error == 0) {
        if(rx2_id ==  '$' ) rx2_id_pointer = 0;
             rx2_id_buff[rx2_id_pointer] = rx2_id;        //storing data in the buffer received form UART
             gps_getinfo(rx2_id_buff[rx2_id_pointer]);
          }
        else
             rx2_id_buff[rx2_id_pointer] = err | 0xF0;
             rx2_id_pointer++;
        if (rx2_id_pointer > 69) rx2_id_pointer = 0;
}

void gps_getinfo(unsigned char rx2_id_buff[]) {
    short i,j,len;
    char *ptr,*ptrTop;
    unsigned char j1,j2;
    unsigned char comma[20]={0};

    if (rx2_id_buff != '\n') {
        gps_linebuf[idx++] = rx2_id_buff;
        if(idx >= MAX_LINEBUF)idx=0;
    }
    else {
        gps_linebuf[idx++] = '\n';
        gps_linebuf[idx] = '\0';
        i = MAX_LINEBUF;
        j = idx - 1;
        while(1) {
            if(gps_linebuf[j] == '$') break;
            j--;
            if(j < 0) j = MAX_LINEBUF - 1;
            if(i-- == 0) {
                gps_linebuf[0] = 0; idx=0;
                return;
            }
        }
        gps_linebuf[idx] = 0; idx=0;
        ptrTop = (char *)&gps_linebuf[j];
        ptr = (char *)&gps_linebuf[j];
        //$GNRMC,114811.00,A,3558.94849,N,14008.90158,E,0.076,,141115,,,A*69
        if(strstr(ptrTop,"GNRMC")!=0) {
            len=strlen(ptr);
            j=0;
            for(i=0; i<len; ++i,ptr++) {
                if(*ptr == ',') {
                    comma[j++] = i+1;
                }
            }
            ptr = ptrTop;
            j1=comma[0];
            j2=comma[1] - comma[0];
            time_flag = 0;
            if(j2>=4) {
                strncpy((char *)hour,ptr+j1  ,2);
                strncpy((char *)min, ptr+j1+2,2);
                strncpy((char *)sec, ptr+j1+4,2);
                time_flag |=0x01;
            }
            j1=comma[1];
            j2=comma[2] - comma[1];
            if(j2>=1) {
                if(*(ptr + j1) == 'A') {
                    time_flag |=0x04;
                }
            }
            j1=comma[8];
            j2=comma[9] - comma[8];
            if(j2>=4) {
                strncpy((char *)day,  ptr+j1  ,2);
                strncpy((char *)mon,  ptr+j1+2,2);
                strncpy((char *)year, ptr+j1+4,2);
                time_flag |=0x02;
                year = atoi((char *)year);
                mon  = atoi((char *)mon);
                day  = atoi((char *)day);
                hour = atoi((char *)hour);
                min  = atoi((char *)min);
                sec  = atoi((char *)sec);
            }
        }
    }
}

</code>```

答:
There are a few errors in your code.  I have tested it, and with some smaller changes it works as expected.

Add the correct header files:

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
</code>```

Please change

```<code>if (rx2_id_buff != '\n') {
    gps_linebuf[idx++] = rx2_id_buff;
</code>```

to

```<code>if (rx2_id_buff[0] != '\n') {
    gps_linebuf[idx++] = rx2_id_buff[0];
</code>```

The integer output variables need to have different names than the corresponding string variables:

```<code>int i_year,i_mon,i_day;
int i_hour,i_min,i_sec;

i_year = atoi((char *)year);
i_mon  = atoi((char *)mon);
i_day  = atoi((char *)day);
i_hour = atoi((char *)hour);
i_min  = atoi((char *)min);
i_sec  = atoi((char *)sec);
</code>```

Body:
I am receiving data continuously using UART and stored in the buffer in the following form::

 $GNRMC,114811.00,A,3558.94849,N,14008.90158,E,0.076,,141115,,,A*69
 $GNVTG,,T,,M,0.076,N,0.141,K,A*38
 $GNGSA,A,3,,,,,,,,,,,,,3.03,1.18,2.80*1E
 $GPGSV,3,2,09,20,04,163,,22,49,280,29,24,45,048,33,25,53,183,28*75
 $GNGLL,3558.94849,N,14008.90158,E,114811.00,A,A*70*

I want to extract only the $GNRMCdata and store it on some variable  year, mon, day, hour, min, sec so that I can display that in 16*2LCD. The value right after $GNRMC 114811 is the time. But I am not getting the data on those variables. Where I am wrong?

void gps_getinfo(unsigned char rx2_id_buff[]);
void uart2_rx_int(void);
#define MAX_LINEBUF 70
char gps_linebuf[MAX_LINEBUF];
unsigned char time_flag;
unsigned char rx2_id_buff[70];
unsigned char rx2_id_pointer;
unsigned char year[4]={0},mon[4]={0},day[4]={0};
unsigned char hour[4]={0},min[4]={0},sec[4]={0};
#pragma interrupt uart2_rx_int  (vect=0x16)

void uart2_rx_int(void)
{
    unsigned char error;
    error = SSR11 & 0x07;
    rx2_id = SDR11;
    if (error == 0) {
        if(rx2_id ==  '$' ) rx2_id_pointer = 0;
             rx2_id_buff[rx2_id_pointer] = rx2_id;        //storing data in the buffer received form UART
             gps_getinfo(rx2_id_buff[rx2_id_pointer]);
          }
        else
             rx2_id_buff[rx2_id_pointer] = err | 0xF0;
             rx2_id_pointer++;
        if (rx2_id_pointer > 69) rx2_id_pointer = 0;
}

void gps_getinfo(unsigned char rx2_id_buff[]) {
    short i,j,len;
    char *ptr,*ptrTop;
    unsigned char j1,j2;
    unsigned char comma[20]={0};

    if (rx2_id_buff != '\n') {
        gps_linebuf[idx++] = rx2_id_buff;
        if(idx >= MAX_LINEBUF)idx=0;
    }
    else {
        gps_linebuf[idx++] = '\n';
        gps_linebuf[idx] = '\0';
        i = MAX_LINEBUF;
        j = idx - 1;
        while(1) {
            if(gps_linebuf[j] == '$') break;
            j--;
            if(j < 0) j = MAX_LINEBUF - 1;
            if(i-- == 0) {
                gps_linebuf[0] = 0; idx=0;
                return;
            }
        }
        gps_linebuf[idx] = 0; idx=0;
        ptrTop = (char *)&gps_linebuf[j];
        ptr = (char *)&gps_linebuf[j];
        //$GNRMC,114811.00,A,3558.94849,N,14008.90158,E,0.076,,141115,,,A*69
        if(strstr(ptrTop,"GNRMC")!=0) {
            len=strlen(ptr);
            j=0;
            for(i=0; i<len; ++i,ptr++) {
                if(*ptr == ',') {
                    comma[j++] = i+1;
                }
            }
            ptr = ptrTop;
            j1=comma[0];
            j2=comma[1] - comma[0];
            time_flag = 0;
            if(j2>=4) {
                strncpy((char *)hour,ptr+j1  ,2);
                strncpy((char *)min, ptr+j1+2,2);
                strncpy((char *)sec, ptr+j1+4,2);
                time_flag |=0x01;
            }
            j1=comma[1];
            j2=comma[2] - comma[1];
            if(j2>=1) {
                if(*(ptr + j1) == 'A') {
                    time_flag |=0x04;
                }
            }
            j1=comma[8];
            j2=comma[9] - comma[8];
            if(j2>=4) {
                strncpy((char *)day,  ptr+j1  ,2);
                strncpy((char *)mon,  ptr+j1+2,2);
                strncpy((char *)year, ptr+j1+4,2);
                time_flag |=0x02;
                year = atoi((char *)year);
                mon  = atoi((char *)mon);
                day  = atoi((char *)day);
                hour = atoi((char *)hour);
                min  = atoi((char *)min);
                sec  = atoi((char *)sec);
            }
        }
    }
}

Body:
There are a few errors in your code.  I have tested it, and with some smaller changes it works as expected.

Add the correct header files:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

Please change

if (rx2_id_buff != '\n') {
    gps_linebuf[idx++] = rx2_id_buff;

to

if (rx2_id_buff[0] != '\n') {
    gps_linebuf[idx++] = rx2_id_buff[0];

The integer output variables need to have different names than the corresponding string variables:

int i_year,i_mon,i_day;
int i_hour,i_min,i_sec;

i_year = atoi((char *)year);
i_mon  = atoi((char *)mon);
i_day  = atoi((char *)day);
i_hour = atoi((char *)hour);
i_min  = atoi((char *)min);
i_sec  = atoi((char *)sec);


问:
What is annotations? In simple terms?
In Groovy++ I often hear of the term Annotations. Can anyone explain me what is that in simple terms?</p>

答:
Some basic info to get you started.

http://groovy.codehaus.org/Annotations+with+Groovy

Title: What is annotations? In simple terms?


问:
gcloud crashed HTTPSConnectionPool
gcloud auth login not coming back to terminal on macos:

ERROR: gcloud crashed (ConnectionError):

HTTPSConnectionPool(host='oauth2.googleapis.com', port=443): Max retries exceeded with url: /token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x105347130>:

Failed to establish a new connection: [Errno 60] Operation timed out'))

gcloud auth login working fine on my other PC windows bash terminal with same Wifi.

Given read & write permissions to everyone of folder google-cloud-sdk

答:
on MacOS goto your icloud settings and enable Private Relay(Beta)
which resolved my problem</p>

Title: gcloud crashed HTTPSConnectionPool


问:
Why can't read a .json?
I want to read a .json using library json-simple, my json file is:

```<code>{
    "Subjects": {
    "subject1": "MIS",
    "subject2": "DBMS",
    "subject3": "UML"
    }
}

</code>```

And my code is:

```<code>import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try{
            Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
            JSONObject jsonObject = (JSONObject)obj;
            JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
            Iterator iterator = subjects.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
</code>```

I would like to get in console:

```<code>subject1: MIS
subject2: DBMS
subject3: UML
</code>```

But instead of that, I just get the next error:

```<code>java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
    at project.Main(Main.java:11)
</code>```

But I searched in internet, and I found that if I change sintaxys of the .json in the next way:

```<code>{
    "Subjects": [
    "subject1: MIS",
    "subject2: DBMS",
    "subject3: UML"
    ]
}
</code>```

I get in console what I want:

```<code>subject1: MIS
subject2: DBMS
subject3: UML
</code>```

And you may think my problem is solved, but not yet, because I want to read the json file in the first way.
I hope someone can help me. Thanks in advance.

答:
Square brackets represent an array, which you've casted the getter into.

The second json shown is more correct for the code you've written, however, arrays cannot hold key-value pairs, so that's why you've made second JSON have an array of strings

To parse the first file, you'd need to start with

```<code>JSONObject subjects = (JSONObject)jsonObject.get("Subjects")
</code>```

If you have full control over the file, I'd suggest just storing ["MIS", "DBMS", "UML"]  then write a simple loop

```<code>for (int i = 0; i < jsonArray.length; i++) {
  System.out.printf("subject%d: %s%n", i+1, jsonArray.get(i));
}
</code>```

Title: Why can't read a .json?

Body:
I want to read a .json using library json-simple, my json file is:

{
    "Subjects": {
    "subject1": "MIS",
    "subject2": "DBMS",
    "subject3": "UML"
    }
}

And my code is:

import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try{
            Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
            JSONObject jsonObject = (JSONObject)obj;
            JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
            Iterator iterator = subjects.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

I would like to get in console:

subject1: MIS
subject2: DBMS
subject3: UML

But instead of that, I just get the next error:

java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
    at project.Main(Main.java:11)

But I searched in internet, and I found that if I change sintaxys of the .json in the next way:

{
    "Subjects": [
    "subject1: MIS",
    "subject2: DBMS",
    "subject3: UML"
    ]
}

I get in console what I want:

subject1: MIS
subject2: DBMS
subject3: UML

And you may think my problem is solved, but not yet, because I want to read the json file in the first way.
I hope someone can help me. Thanks in advance.

Body:
Square brackets represent an array, which you've casted the getter into.

The second json shown is more correct for the code you've written, however, arrays cannot hold key-value pairs, so that's why you've made second JSON have an array of strings

To parse the first file, you'd need to start with

JSONObject subjects = (JSONObject)jsonObject.get("Subjects")

If you have full control over the file, I'd suggest just storing ["MIS", "DBMS", "UML"]  then write a simple loop

for (int i = 0; i < jsonArray.length; i++) {
  System.out.printf("subject%d: %s%n", i+1, jsonArray.get(i));
}


答:
The first example shows a Subjects key containing a single object with several properties (subject1, subject2, etc).

Consider those properties like the member variables of a class.
In order to let you better understand if the class is Person those variables could be name and surname.

What you try to achieve in your code is extracting a JSONArray from the JSON you are providing.
Going back to the example for Person the array could be - sorry for the silly example - an Array containing phone numbers.
So what you are expecting is that one of the member properties of the class is an array.

This is not possible in the first example because the first example does not contain a json array.

This line extracts the whole json object:

JSONObject jsonObject = (JSONObject)obj;

This one tries to get an array out but no array is there in the first example:

JSONArray subjects = (JSONArray)jsonObject.get("Subjects");

Title: Why can't read a .json?


问:
How to get pid of the process that run in background exec by shell in php
I'm working on a shell in php, and I want to display the same output as bash. When in bash you execute sleep 10 & you'll get [1] <PID>. How can I do the same in php, when I call shell using:

```<code>    if (preg_match("/&\s*$/", $command)) {
        $this->$shell_fn($token, '/bin/bash -c ' . escapeshellarg($command) .
                         " > /dev/null");
        return array(
            'output' => '',
            'cwd' => $path
        );
    }
</code>```

$shell_fn is variable that point to wrapper over shell_exec, exec or cgi script called by curl. Is it even possible to get the pid from php or using a shell?

答:
I use this functions to manage process:</p>
```<code>function ProcessStart($cmdline) // return pid
{
    exec( "nohup $cmdline >/dev/null 2>&1 & echo $!", $output) ;
    // print_r ($output);
    return (int)$output[0];
}

function ProcessStatus($pid) // return TRUE (live) o FALSE (dead)
{
    exec("ps -p $pid",$output);
    // print_r($output);
    return ( isset($output[1]) ? TRUE : FALSE ) ;
}

function ProcessStop($pid)
{
    exec("kill $pid",$output); // kill -9 ??
}
</code>```

Body:
I'm working on a shell in php, and I want to display the same output as bash. When in bash you execute sleep 10 & you'll get [1] <PID>. How can I do the same in php, when I call shell using:

    if (preg_match("/&\s*$/", $command)) {
        $this->$shell_fn($token, '/bin/bash -c ' . escapeshellarg($command) .
                         " > /dev/null");
        return array(
            'output' => '',
            'cwd' => $path
        );
    }

$shell_fn is variable that point to wrapper over shell_exec, exec or cgi script called by curl. Is it even possible to get the pid from php or using a shell?

Body:
I use this functions to manage process:

function ProcessStart($cmdline) // return pid
{
    exec( "nohup $cmdline >/dev/null 2>&1 & echo $!", $output) ;
    // print_r ($output);
    return (int)$output[0];
}

function ProcessStatus($pid) // return TRUE (live) o FALSE (dead)
{
    exec("ps -p $pid",$output);
    // print_r($output);
    return ( isset($output[1]) ? TRUE : FALSE ) ;
}

function ProcessStop($pid)
{
    exec("kill $pid",$output); // kill -9 ??
}


问:
How to Start and Stop systemd services through dbus package in nodejs?
I want to control systemd services and daemons through dbus in nodejs

each time I want to connect to the system bus and run a command the program hangs in an infinite loop

I used node-dbus

const dbus = require("dbus");

const someBus = dbus.getBus('system');

someBus.getInterface('org.freedesktop.systemd1',
  '/org/freedesktop/systemd1',
  (err, interface) => {
  if (err) throw new Error(err)
  console.log(interface)
})
```

答:
The documentation says getInterface takes four parameters:

```<code>Bus.prototype.getInterface(serviceName, objectPath, interfaceName, callback)
</code>```

You appear to have missed the interfaceName parameter. Looking at the interfaces available at that serviceName and objectPath it seems that you want org.freedesktop.systemd1.Manager

$ busctl introspect org.freedesktop.systemd1 /org/freedesktop/systemd1 | grep interface
org.freedesktop.DBus.Introspectable       interface -                -                                        -
org.freedesktop.DBus.Peer                 interface -                -                                        -
org.freedesktop.DBus.Properties           interface -                -                                        -
org.freedesktop.systemd1.Manager          interface -                -                                        -
```
<p>So it should look like this:</p>
<pre class="lang-js prettyprint-override"><code>const dbus = require("dbus");

const someBus = dbus.getBus('system');

someBus.getInterface('org.freedesktop.systemd1',
  '/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager',
  (err, interface) => {
  if (err) throw new Error(err)
  console.log(interface)
})
</code>```

The list of methods on that interface are:

```<code>$ busctl introspect org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager | grep method
.AbandonScope                             method    s                -                                        -
.AddDependencyUnitFiles                   method    asssbb           a(sss)                                   -
.AttachProcessesToUnit                    method    ssau             -                                        -
.CancelJob                                method    u                -                                        -
.ClearJobs                                method    -                -                                        -
.DisableUnitFiles                         method    asb              a(sss)                                   -
.Dump                                     method    -                s                                        -
.DumpByFileDescriptor                     method    -                h                                        -
.EnableUnitFiles                          method    asbb             ba(sss)                                  -
.Exit                                     method    -                -                                        -
.GetDefaultTarget                         method    -                s                                        -
.GetDynamicUsers                          method    -                a(us)                                    -
.GetJob                                   method    u                o                                        -
.GetJobAfter                              method    u                a(usssoo)                                -
.GetJobBefore                             method    u                a(usssoo)                                -
.GetUnit                                  method    s                o                                        -
.GetUnitByControlGroup                    method    s                o                                        -
.GetUnitByInvocationID                    method    ay               o                                        -
.GetUnitByPID                             method    u                o                                        -
.GetUnitFileLinks                         method    sb               as                                       -
.GetUnitFileState                         method    s                s                                        -
.GetUnitProcesses                         method    s                a(sus)                                   -
.Halt                                     method    -                -                                        -
.KExec                                    method    -                -                                        -
.KillUnit                                 method    ssi              -                                        -
.LinkUnitFiles                            method    asbb             a(sss)                                   -
.ListJobs                                 method    -                a(usssoo)                                -
.ListUnitFiles                            method    -                a(ss)                                    -
.ListUnitFilesByPatterns                  method    asas             a(ss)                                    -
.ListUnits                                method    -                a(ssssssouso)                            -
.ListUnitsByNames                         method    as               a(ssssssouso)                            -
.ListUnitsByPatterns                      method    asas             a(ssssssouso)                            -
.ListUnitsFiltered                        method    as               a(ssssssouso)                            -
.LoadUnit                                 method    s                o                                        -
.LookupDynamicUserByName                  method    s                u                                        -
.LookupDynamicUserByUID                   method    u                s                                        -
.MaskUnitFiles                            method    asbb             a(sss)                                   -
.PowerOff                                 method    -                -                                        -
.PresetAllUnitFiles                       method    sbb              a(sss)                                   -
.PresetUnitFiles                          method    asbb             ba(sss)                                  -
.PresetUnitFilesWithMode                  method    assbb            ba(sss)                                  -
.Reboot                                   method    -                -                                        -
.ReenableUnitFiles                        method    asbb             ba(sss)                                  -
.Reexecute                                method    -                -                                        -
.RefUnit                                  method    s                -                                        -
.Reload                                   method    -                -                                        -
.ReloadOrRestartUnit                      method    ss               o                                        -
.ReloadOrTryRestartUnit                   method    ss               o                                        -
.ReloadUnit                               method    ss               o                                        -
.ResetFailed                              method    -                -                                        -
.ResetFailedUnit                          method    s                -                                        -
.RestartUnit                              method    ss               o                                        -
.RevertUnitFiles                          method    as               a(sss)                                   -
.SetDefaultTarget                         method    sb               a(sss)                                   -
.SetEnvironment                           method    as               -                                        -
.SetExitCode                              method    y                -                                        -
.SetUnitProperties                        method    sba(sv)          -                                        -
.StartTransientUnit                       method    ssa(sv)a(sa(sv)) o                                        -
.StartUnit                                method    ss               o                                        -
.StartUnitReplace                         method    sss              o                                        -
.StopUnit                                 method    ss               o                                        -
.Subscribe                                method    -                -                                        -
.SwitchRoot                               method    ss               -                                        -
.TryRestartUnit                           method    ss               o                                        -
.UnmaskUnitFiles                          method    asb              a(sss)                                   -
.UnrefUnit                                method    s                -                                        -
.UnsetAndSetEnvironment                   method    asas             -                                        -
.UnsetEnvironment                         method    as               -                                        -
.Unsubscribe                              method    -                -                                        -
</code>```

Body:
The documentation says getInterface takes four parameters:

Bus.prototype.getInterface(serviceName, objectPath, interfaceName, callback)

You appear to have missed the interfaceName parameter. Looking at the interfaces available at that serviceName and objectPath it seems that you want org.freedesktop.systemd1.Manager

$ busctl introspect org.freedesktop.systemd1 /org/freedesktop/systemd1 | grep interface
org.freedesktop.DBus.Introspectable       interface -                -                                        -
org.freedesktop.DBus.Peer                 interface -                -                                        -
org.freedesktop.DBus.Properties           interface -                -                                        -
org.freedesktop.systemd1.Manager          interface -                -                                        -

So it should look like this:

const dbus = require("dbus");

const someBus = dbus.getBus('system');

someBus.getInterface('org.freedesktop.systemd1',
  '/org/freedesktop/systemd1', 'org.freedesktop.systemd1.Manager',
  (err, interface) => {
  if (err) throw new Error(err)
  console.log(interface)
})

The list of methods on that interface are:

$ busctl introspect org.freedesktop.systemd1 /org/freedesktop/systemd1 org.freedesktop.systemd1.Manager | grep method
.AbandonScope                             method    s                -                                        -
.AddDependencyUnitFiles                   method    asssbb           a(sss)                                   -
.AttachProcessesToUnit                    method    ssau             -                                        -
.CancelJob                                method    u                -                                        -
.ClearJobs                                method    -                -                                        -
.DisableUnitFiles                         method    asb              a(sss)                                   -
.Dump                                     method    -                s                                        -
.DumpByFileDescriptor                     method    -                h                                        -
.EnableUnitFiles                          method    asbb             ba(sss)                                  -
.Exit                                     method    -                -                                        -
.GetDefaultTarget                         method    -                s                                        -
.GetDynamicUsers                          method    -                a(us)                                    -
.GetJob                                   method    u                o                                        -
.GetJobAfter                              method    u                a(usssoo)                                -
.GetJobBefore                             method    u                a(usssoo)                                -
.GetUnit                                  method    s                o                                        -
.GetUnitByControlGroup                    method    s                o                                        -
.GetUnitByInvocationID                    method    ay               o                                        -
.GetUnitByPID                             method    u                o                                        -
.GetUnitFileLinks                         method    sb               as                                       -
.GetUnitFileState                         method    s                s                                        -
.GetUnitProcesses                         method    s                a(sus)                                   -
.Halt                                     method    -                -                                        -
.KExec                                    method    -                -                                        -
.KillUnit                                 method    ssi              -                                        -
.LinkUnitFiles                            method    asbb             a(sss)                                   -
.ListJobs                                 method    -                a(usssoo)                                -
.ListUnitFiles                            method    -                a(ss)                                    -
.ListUnitFilesByPatterns                  method    asas             a(ss)                                    -
.ListUnits                                method    -                a(ssssssouso)                            -
.ListUnitsByNames                         method    as               a(ssssssouso)                            -
.ListUnitsByPatterns                      method    asas             a(ssssssouso)                            -
.ListUnitsFiltered                        method    as               a(ssssssouso)                            -
.LoadUnit                                 method    s                o                                        -
.LookupDynamicUserByName                  method    s                u                                        -
.LookupDynamicUserByUID                   method    u                s                                        -
.MaskUnitFiles                            method    asbb             a(sss)                                   -
.PowerOff                                 method    -                -                                        -
.PresetAllUnitFiles                       method    sbb              a(sss)                                   -
.PresetUnitFiles                          method    asbb             ba(sss)                                  -
.PresetUnitFilesWithMode                  method    assbb            ba(sss)                                  -
.Reboot                                   method    -                -                                        -
.ReenableUnitFiles                        method    asbb             ba(sss)                                  -
.Reexecute                                method    -                -                                        -
.RefUnit                                  method    s                -                                        -
.Reload                                   method    -                -                                        -
.ReloadOrRestartUnit                      method    ss               o                                        -
.ReloadOrTryRestartUnit                   method    ss               o                                        -
.ReloadUnit                               method    ss               o                                        -
.ResetFailed                              method    -                -                                        -
.ResetFailedUnit                          method    s                -                                        -
.RestartUnit                              method    ss               o                                        -
.RevertUnitFiles                          method    as               a(sss)                                   -
.SetDefaultTarget                         method    sb               a(sss)                                   -
.SetEnvironment                           method    as               -                                        -
.SetExitCode                              method    y                -                                        -
.SetUnitProperties                        method    sba(sv)          -                                        -
.StartTransientUnit                       method    ssa(sv)a(sa(sv)) o                                        -
.StartUnit                                method    ss               o                                        -
.StartUnitReplace                         method    sss              o                                        -
.StopUnit                                 method    ss               o                                        -
.Subscribe                                method    -                -                                        -
.SwitchRoot                               method    ss               -                                        -
.TryRestartUnit                           method    ss               o                                        -
.UnmaskUnitFiles                          method    asb              a(sss)                                   -
.UnrefUnit                                method    s                -                                        -
.UnsetAndSetEnvironment                   method    asas             -                                        -
.UnsetEnvironment                         method    as               -                                        -
.Unsubscribe                              method    -                -                                        -


问:
@XmlElement does not work when used in kotlin
When I serialize an instance of class ReturnValue, I found that @XmlElement doesn't work. the generated xml still had a tag of , not <comment>.

the ReturnValue class:

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
data class ReturnValue(val type: String,
                       @XmlElement(name="comment")
                       val summary: String){
    constructor(): this(type="java.lang.Object", summary="no summary")
}
</code>```

the test program:

```<code>fun main(args: Array<String>) {
    val jaxbContext = JAXBContext.newInstance(ReturnValue::class.java)
    val marshaller = jaxbContext.createMarshaller()
    marshaller.marshal(
        ReturnValue(type = "java.lang.Object",summary = "hello"),
        System.out)
}
</code>```

and the output:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?><returnValue><type>type2</type><summary>hello</summary></returnValue>
</code>```

So, I want to change  to <comment>. How can I do that?

答: Faced the same problem, but my solution was that @XmlElement needs namespace param to be specified, if at least one upper tag has custom one. Even if this namespace is specified in @XmlRootElement

Body:
When I serialize an instance of class ReturnValue, I found that @XmlElement doesn't work. the generated xml still had a tag of , not <comment>.

the ReturnValue class:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
data class ReturnValue(val type: String,
                       @XmlElement(name="comment")
                       val summary: String){
    constructor(): this(type="java.lang.Object", summary="no summary")
}

the test program:

fun main(args: Array<String>) {
    val jaxbContext = JAXBContext.newInstance(ReturnValue::class.java)
    val marshaller = jaxbContext.createMarshaller()
    marshaller.marshal(
        ReturnValue(type = "java.lang.Object",summary = "hello"),
        System.out)
}

and the output:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><returnValue><type>type2</type>hello</returnValue>

So, I want to change  to <comment>. How can I do that?


问:
What is the proper way to take an item from a BlockingCollection?
When calling BlockingCollection.Take() it is possible for the IsCompleted status of the collection to change between the check of IsCompleted and the call to Take().

The MSDN Documentation that shows an example just catches the invalid operation exception, but it seems like there must be a proper way to do such a call without catching the exception (since this incurs a decent amount of overhead and doesn't look clean in code).  What is the proper way to call .Take() and to avoid an invalid operation exception?

A simplified version of my specific issue:

```<code>If (!blockingCollection.IsCompleted)
{
//do some stuff
value = blockingCollection.Take();  //Throws Exception, IsCompleted = True;
}
</code>```

There is a TryTake method available, but I am under the impression that it is so that a timeout and cancelation token can be passed in, not to deal with the IsCompleted becoming true in between the time it is checked and when Take() is called.

答: You can use the TryTake overload with no timeout/cancelation.  It will return false if the BlockingCollection is empty or has been marked completed, and handles the synchronization issue you're facing correctly.

Body:
When calling BlockingCollection.Take() it is possible for the IsCompleted status of the collection to change between the check of IsCompleted and the call to Take().

The MSDN Documentation that shows an example just catches the invalid operation exception, but it seems like there must be a proper way to do such a call without catching the exception (since this incurs a decent amount of overhead and doesn't look clean in code).  What is the proper way to call .Take() and to avoid an invalid operation exception?

A simplified version of my specific issue:

If (!blockingCollection.IsCompleted)
{
//do some stuff
value = blockingCollection.Take();  //Throws Exception, IsCompleted = True;
}

There is a TryTake method available, but I am under the impression that it is so that a timeout and cancelation token can be passed in, not to deal with the IsCompleted becoming true in between the time it is checked and when Take() is called.


问:
Window docker is not picking cuda on WSL2
I have installed Ubuntu 20.04.2 LTS on windows 11 (OS build 22000.100) using WSL2.
When I do nvidia-smi, it shows me GPU.
But when I run the docker image it gave the following error

```<code>RuntimeError: Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx
</code>```

I am using docker windows on wsl2. When I do uname -r i got 5.10.43.3-microsoft-standard-WSL2

Is there any solution?

答: Ensure you have the supported driver (https://developer.nvidia.com/cuda/wsl/download, free registration required), update Docker Desktop to the latest version, and then run docker run --rm -it --gpus=all nvcr.io/nvidia/k8s/cuda-sample:nbody to test it out. You then have to run your containers with --gpus=all.

Body:
I have installed Ubuntu 20.04.2 LTS on windows 11 (OS build 22000.100) using WSL2.
When I do nvidia-smi, it shows me GPU.
But when I run the docker image it gave the following error

RuntimeError: Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx

I am using docker windows on wsl2. When I do uname -r i got 5.10.43.3-microsoft-standard-WSL2

Is there any solution?


问:
Compare two array of objects and remove objects from first array if a property value is matched
I have 2 array of objects like

```<code>    const arrayOne = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
    const arrayTwo = [{id: 2, name: 'two'}, {id: 3, name: 'three'}];
</code>```

Here, I need to compare both these arrays and remove matching objects from arrayOne, which should finally give

```<code> this.arrayOne = [{id: 1, name: 'one'}];
</code>```

I tried like below but it is removing all objects from the array

```<code>this.arrayOne = this.arrayOne.filter(o1 => this.arrayTwo.some(o2 => o1.id === o2.id));
</code>```

What I am doing wrong here? Please suggest. Thanks

答:
Your way is correct. but you miss the not operation (!) before arrayTwo.some.
So the correct way is this:

const arrayOne = [
  {id: 1, name: 'one'},
  {id: 2, name: 'two'},
  {id: 3, name: 'three'}
];
const arrayTwo = [
  {id: 2, name: 'two'},
  {id: 3, name: 'three'}
];

// Shared Items between arrayOne and arrayTwo (this what you done)
const sharedObjects = arrayOne.filter(o1 => arrayTwo.some(o2 => o1.id === o2.id));

console.log(sharedObjects);

// arrayOne - arrayTwo (this is what you want)
const arrayOneUniqueObjects = arrayOne.filter(o1 => !arrayTwo.some(o2 => o1.id === o2.id));

console.log(arrayOneUniqueObjects);```

Also, You can find more details here:

bobbyhadz.com/blog/javascript-get-difference-between-two-arrays-of-objects

Body:
I have 2 array of objects like

    const arrayOne = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
    const arrayTwo = [{id: 2, name: 'two'}, {id: 3, name: 'three'}];

Here, I need to compare both these arrays and remove matching objects from arrayOne, which should finally give

 this.arrayOne = [{id: 1, name: 'one'}];

I tried like below but it is removing all objects from the array

this.arrayOne = this.arrayOne.filter(o1 => this.arrayTwo.some(o2 => o1.id === o2.id));

What I am doing wrong here? Please suggest. Thanks

Body:
Your way is correct. but you miss the not operation (!) before arrayTwo.some.
So the correct way is this:

const arrayOne = [
  {id: 1, name: 'one'},
  {id: 2, name: 'two'},
  {id: 3, name: 'three'}
];
const arrayTwo = [
  {id: 2, name: 'two'},
  {id: 3, name: 'three'}
];

// Shared Items between arrayOne and arrayTwo (this what you done)
const sharedObjects = arrayOne.filter(o1 => arrayTwo.some(o2 => o1.id === o2.id));

console.log(sharedObjects);

// arrayOne - arrayTwo (this is what you want)
const arrayOneUniqueObjects = arrayOne.filter(o1 => !arrayTwo.some(o2 => o1.id === o2.id));

console.log(arrayOneUniqueObjects);

Also, You can find more details here:

bobbyhadz.com/blog/javascript-get-difference-between-two-arrays-of-objects


问:
Invoking a Hibernate REST @POST method from Dropwizard application run() does not work, but method works when invoked normally from frontend
I am writing my first web-application as practice learning different frameworks. Please forgive me if I make any very obvious mistakes as I am new to this.

I am using Dropwizard and Kotlin to write the backend of my application. I am running 2 docker containers: one with the application.jar file and another with a PostgreSQL database. As I am learning the process and individual frameworks step-by-step, I am writing certain code snippets to help me work out what is actually happening.

I am using Hibernate as my ORM to map my Kotlin objects to the database. I tried creating a random object using a @POST method in my resources class, as shown below.

```<code>@POST
@UnitOfWork
fun createNote(@Valid noteRequest : Note){
    println("adding new note")
    val note = createNoteToSave(noteRequest)
    notesDAO.save(note)
}

private fun createNoteToSave(noteRequest: Note) : Note{
    val note = Note()
    note.data = noteRequest.data
    note.type = noteRequest.type
    return note
}
</code>```

I don't have my frontend created yet so I wasn't sure the best way to access this method's URL to test whether the creation was working (but I believe I can curl from the cmd line now). In order to test the creation, I simply invoked the method notesResource.createNote(note) from the .run() method of my Dropwizard main application class and I got the following error:

```<code>org.hibernate.HibernateException: No session currently bound to execution context

at org.hibernate.context.internal.ManagedSessionContext.currentSession(ManagedSessionContext.java:58)

at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:508)

at io.dropwizard.hibernate.AbstractDAO.currentSession(AbstractDAO.java:44)

at com.ac.notetaker.dao.HibernateDAO.save(HibernateDAO.kt:34)

at com.ac.notetaker.resources.NotesResource.createNote(NotesResource.kt:34)

at com.ac.notetaker.NotetakerApplication.run(NotetakerApplication.kt:95)

at com.ac.notetaker.NotetakerApplication.run(NotetakerApplication.kt:22)
</code>```

It says the Hibernate session has not started, but shouldn't the @UnitOfWork annotation signify that whenever the method is invoked, a session should begin?

Instead, as I don't have a frontend, I created a @GET method to then in turn invoke the @POST method, as below. When I visit this URL, the @POST method is successively invoked and an object is created and added to the database.

```<code>@GET
@Path("add")
@UnitOfWork
fun addRandomNote(){
    this.createNote(Note(
        UUID.randomUUID(),
        "{\"question\":\"answer\"}",
        Note.Type.QuestionAndAnswer.toString(),
    ))
}
</code>```

Why, when I access the method with the @GET url, is the method successfully creating the Hibernate session and creating the object, but when I invoke the method directly from my backend code, it isn't? I appreciate any insight you guys can provide here, I am just trying to learn :)

答:
This makes sense - if you invoke your method directly then you are just executing your method's code - the annotation doesn't cause any extra behaviour.

The way frameworks like Spring and JAX-RS work is that on startup, the code that actually handles http requests is given a reference not to your class but to a dynamically generated subclass (this is what cglib is for) - if you hit a breakpoint in your method you will see that the object is not an instance of your class but something with a generated name.

The subclass overrides your method to decorate it with additional code - in this case to create the Session. This wrapper code is commonly defined in aspects with join points based on the annotation, and cglib pulls that aspect code into the compiled subclass. (if the annotated method is on an interface then a Java dynamic proxy is used rather than cglib and it just implements the interface rather than having to extend a class).

You can indeed call your post from curl - try something like curl -X POST localhost:8080/the_path -H 'Content-type:application/json' -d '{"question":"answer"}'

Body:
I am writing my first web-application as practice learning different frameworks. Please forgive me if I make any very obvious mistakes as I am new to this.

I am using Dropwizard and Kotlin to write the backend of my application. I am running 2 docker containers: one with the application.jar file and another with a PostgreSQL database. As I am learning the process and individual frameworks step-by-step, I am writing certain code snippets to help me work out what is actually happening.

I am using Hibernate as my ORM to map my Kotlin objects to the database. I tried creating a random object using a @POST method in my resources class, as shown below.

@POST
@UnitOfWork
fun createNote(@Valid noteRequest : Note){
    println("adding new note")
    val note = createNoteToSave(noteRequest)
    notesDAO.save(note)
}

private fun createNoteToSave(noteRequest: Note) : Note{
    val note = Note()
    note.data = noteRequest.data
    note.type = noteRequest.type
    return note
}

I don't have my frontend created yet so I wasn't sure the best way to access this method's URL to test whether the creation was working (but I believe I can curl from the cmd line now). In order to test the creation, I simply invoked the method notesResource.createNote(note) from the .run() method of my Dropwizard main application class and I got the following error:

org.hibernate.HibernateException: No session currently bound to execution context

at org.hibernate.context.internal.ManagedSessionContext.currentSession(ManagedSessionContext.java:58)

at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:508)

at io.dropwizard.hibernate.AbstractDAO.currentSession(AbstractDAO.java:44)

at com.ac.notetaker.dao.HibernateDAO.save(HibernateDAO.kt:34)

at com.ac.notetaker.resources.NotesResource.createNote(NotesResource.kt:34)

at com.ac.notetaker.NotetakerApplication.run(NotetakerApplication.kt:95)

at com.ac.notetaker.NotetakerApplication.run(NotetakerApplication.kt:22)

It says the Hibernate session has not started, but shouldn't the @UnitOfWork annotation signify that whenever the method is invoked, a session should begin?

Instead, as I don't have a frontend, I created a @GET method to then in turn invoke the @POST method, as below. When I visit this URL, the @POST method is successively invoked and an object is created and added to the database.

@GET
@Path("add")
@UnitOfWork
fun addRandomNote(){
    this.createNote(Note(
        UUID.randomUUID(),
        "{\"question\":\"answer\"}",
        Note.Type.QuestionAndAnswer.toString(),
    ))
}

Why, when I access the method with the @GET url, is the method successfully creating the Hibernate session and creating the object, but when I invoke the method directly from my backend code, it isn't? I appreciate any insight you guys can provide here, I am just trying to learn :)


问:
How to setup snappy compression for a file using flink job running locally
```<code>native snappy library not available: this version of lib hadoop was built without snappy support.
</code>```

What are all the mandatory files need to be avaiable in hadoo libe folder.

It is saying snappy library is not on the class path

答:
You'll see this error message if the shared library (.so) for snappy is not located on the hadoop lib path. If you have the libraries installed in the correct location then you shouldn't see the above error messages.

If you do have the .so installed in the same folder as the hadoop native lib (libhadoop.so), then the above 'error' could be related to the node you are submitting your jobs from (like you say, your job doesn't error and this looks like a message on the client side).

may be youo can refer to https://code.google.com/archive/p/hadoop-snappy/

Body:
native snappy library not available: this version of lib hadoop was built without snappy support.

What are all the mandatory files need to be avaiable in hadoo libe folder.

It is saying snappy library is not on the class path


问:
What is Sqlite used for?
I don't know how authoritative this is but I found this:

http://www.sqlite.org/cvstrac/wiki?p=PerformanceConsiderations

and it doesn't seem good to have a lot of connections to sqlite.  This seems to be bad for the web and most applications that have more than a few users.  I'm having a hard time thinking of what sqlite would be used for when you don't need that many connections.  Every program I can think of needs users, lots of them sometimes, so what would I use a database for that doesn't allow that many connections?  I thought about prototypes but why would I use that when I can just connect to a larger database?  Embedded apps maybe?

Thank you.

EDIT:  Thanks everyone.  I look at the page recommended below but an confused about something:

Under appropriate uses for sqlite it has:

Situations Where SQLite Works Well

•Websites

SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

Situations Where Another RDBMS May Work Better

•Client/Server Applications

If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it.

A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.

The Question:

I'm going to show my ignorance here but what is the difference between these two?

答:
I also find that using SQLite is good for getting a prototype application together pretty quickly without the overhead of having a seperate DB server or bogging a development environment with an instance of MySQL/Oracle/Whatever.

Also easy to pick up and move the database to a different machine if you need to.

OwnerDisplayName: johnny

ContentLicense: CC BY-SA 2.5

Title: What is Sqlite used for?

LastEditorDisplayName: johnny

OwnerDisplayName: Owen


问:
How to delete a Front Door resource locked by a domain I don't own
Azure Front Door does not allow frontend endpoint deletion if the endpoint's domain still points to the Front Door using a CNAME record. The same holds even when there is just the verification domain (afdverify).

409 Conflict

Cannot delete frontend endpoint "www.example.com" because it is still directly or indirectly (using "afdverify" prefix) CNAMEd to front door "example.azurefd.net". Please remove the DNS CNAME records and try again.

While I hate that there is no way to delete such a frontend, there is a way to deal with that even if the DNS zone cannot be changed by the Front Door owner -- just don't assign the frontend endpoint to any routing rule and don't mind it; it consumes just a bit of developer's attention, which makes it somewhat bearable.

The problem comes with the fact that such a frontend prevents even the deletion of the whole Front Door, which in turn prevents deletion of the whole resource group.

Why is that a problem? Consider that a single subscription is shared by the whole dev team and someone creates a Front Door instance for experiments, uses his own domain and later leaves the team. Now the resource consumes money as there has to be at least one routing rule for the default frontend endpoint and routing rules are paid per time unit, and there is no obvious way to get rid of it.

Is there a way to delete such a Front Door instance besides contacting Microsoft support or asking the owner of the domain to pretty please delete the records pointing to the Front Door?

答:
We had the same issue. While checking the Microsoft documentation we found that Microsoft has introduced this breaking change (Terraform provider for ARM issue #11231).

But it seems like the CNAME check can be disabled for a subscription via Azure CLI az feature:

```<code>az feature register --namespace Microsoft.Network --name BypassCnameCheckForCustomDomainDeletion
</code>```

First, run the above command and then go to the Front Door resource and try deleting it.

If you need to enable the CNAME check again:

```<code>az feature unregister --namespace Microsoft.Network --name BypassCnameCheckForCustomDomainDeletion
</code>```

If you need to check the status of the feature:

```<code>az feature list -o table --query "[?contains(name, 'Microsoft.Network/BypassCnameCheckForCustomDomainDeletion')].{Name:name,State:properties.state}"
</code>```

Body:
We had the same issue. While checking the Microsoft documentation we found that Microsoft has introduced this breaking change (Terraform provider for ARM issue #11231).

But it seems like the CNAME check can be disabled for a subscription via Azure CLI az feature:

az feature register --namespace Microsoft.Network --name BypassCnameCheckForCustomDomainDeletion

First, run the above command and then go to the Front Door resource and try deleting it.

If you need to enable the CNAME check again:

az feature unregister --namespace Microsoft.Network --name BypassCnameCheckForCustomDomainDeletion

If you need to check the status of the feature:

az feature list -o table --query "[?contains(name, 'Microsoft.Network/BypassCnameCheckForCustomDomainDeletion')].{Name:name,State:properties.state}"


问:
Google Sheet: Identify if the specific ID has already been printed
I'm just wondering if there's a way for me to determine if data with a specific ID has already been printed. I'm collecting data with Google Forms. On Google Sheets, I have a separate sheet called "TEMPLATE" where I can view all of the data for a specific ID at once.

TEMPLATE:

FORM RESPONSES:

For example, on the Form Reponses sheet, I want to print the data of  STUDENT ID: 4028451. So, after printing, I'd like the 'F2' cell to be updated with the letter "P." Is that even possible?

Here's the sample template: SAMPLE

答:
If I understood your question correctly, you want to programmatically modify the Sheet after an event, and that event is printing a sheet. You could develop an
installable trigger based on events, but sadly there is no event object for printing actions.</p>