问:
System.MissingMethodException: Method not found for Bigquery
I'm using Google BigQuery to transfer data from file to BigQuery. I'm using BigQuery Google.Cloud.BigQuery.V2 version="1.3.0" and it's dependent dlls. My C# code works fine in ConsoleApplication VS2019 but when I'm using SSIS task, I'm getting the error:

System.MissingMethodException: Method not found: 'Google.Apis.Auth.OAuth2.GoogleCredential Google.Api.Gax.Rest.ScopedCredentialProvider.GetCredentials(Google.Apis.Auth.OAuth2.GoogleCredential)'.
     at Google.Cloud.BigQuery.V2.BigQueryClient.Create(String projectId, GoogleCredential credential)

```<code>var googlecredential = new GoogleCredentials()
                {
                    private_key = "",
                    client_email = "",
                    type = ""
                };
var credentials = GoogleCredential.FromJson(JsonConvert.SerializeObject(googlecredential));
BigQueryClient client = BigQueryClient.Create(projectId, credentials); -> this line throws error if I'm referencing dll Google.Cloud.BigQuery.V2 version 1.3 or 1.4 and it works if for 1.2 version.
</code>```

Note: This error is only happening in script task. All the Dlls are registered in GAC.

答:
I had the same problem. Finally I've solved it by using BigqueryService instead of BigQueryClient.

```<code>var service = new BigqueryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "CS Bigquery"
            });
</code>```

Full sample I've used is here: https://www.codeproject.com/Tips/785554/Google-BigQuery-API-Client-Sample-Code-for-Csharp

Body:
I'm using Google BigQuery to transfer data from file to BigQuery. I'm using BigQuery Google.Cloud.BigQuery.V2 version="1.3.0" and it's dependent dlls. My C# code works fine in ConsoleApplication VS2019 but when I'm using SSIS task, I'm getting the error:

System.MissingMethodException: Method not found: 'Google.Apis.Auth.OAuth2.GoogleCredential Google.Api.Gax.Rest.ScopedCredentialProvider.GetCredentials(Google.Apis.Auth.OAuth2.GoogleCredential)'.
     at Google.Cloud.BigQuery.V2.BigQueryClient.Create(String projectId, GoogleCredential credential)

var googlecredential = new GoogleCredentials()
                {
                    private_key = "",
                    client_email = "",
                    type = ""
                };
var credentials = GoogleCredential.FromJson(JsonConvert.SerializeObject(googlecredential));
BigQueryClient client = BigQueryClient.Create(projectId, credentials); -> this line throws error if I'm referencing dll Google.Cloud.BigQuery.V2 version 1.3 or 1.4 and it works if for 1.2 version.

Note: This error is only happening in script task. All the Dlls are registered in GAC.

Body:
I had the same problem. Finally I've solved it by using BigqueryService instead of BigQueryClient.

var service = new BigqueryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "CS Bigquery"
            });

Full sample I've used is here: https://www.codeproject.com/Tips/785554/Google-BigQuery-API-Client-Sample-Code-for-Csharp


来源: stackexchange

问:
Reading Local Entry (XML,URL) in WSO2 ESB
I have configured below two local entry in WSO2 WSB4.9.0 how can I read the node values in proxy or sequence.

In-Line XML Local Entry

```<code><?xml version="1.0" encoding="UTF-8"?>
    <localEntry key="test" xmlns="http://ws.apache.org/ns/synapse">
      <list>
        <flag>a</flag>
        <path>b</path>
      </list>
    </localEntry>
</code>```

and

Source URL Entry

```<code><?xml version="1.0" encoding="UTF-8"?>
<localEntry key="sample" src="file:/C:/Apache24/bin/ApacheMonitor" xmlns="http://ws.apache.org/ns/synapse"/>
</code>```

Please help.

答: For me get-property does not work for local entries, while xslt mediator works well . ie6.4</p>

ContentLicense: CC BY-SA 3.0

Body:
I have configured below two local entry in WSO2 WSB4.9.0 how can I read the node values in proxy or sequence.

In-Line XML Local Entry

<?xml version="1.0" encoding="UTF-8"?>
    <localEntry key="test" xmlns="http://ws.apache.org/ns/synapse">
      <list>
        <flag>a</flag>
        <path>b</path>
      </list>
    </localEntry>

and

Source URL Entry

<?xml version="1.0" encoding="UTF-8"?>
<localEntry key="sample" src="file:/C:/Apache24/bin/ApacheMonitor" xmlns="http://ws.apache.org/ns/synapse"/>

Please help.

ContentLicense: CC BY-SA 4.0


问:
Apply class on element inside ng-container with [ngTemplateOutlet]
I have a PARENT component which has a CHILD component.
This PARENT component holds ng-template which will be bound into the CHILD component.

In order to style the ng-container's element (svg), I used ng-deep and it worked.

What I want now is to dynamically add a class to the ng-container's element (svg) from the CHILD component (like ngClass);

Please see my code below for better understading.

PARENT

HTML:

...

<app-input [icon]="userIcon"></app-input>

...

<ng-template #userIcon>
    <svg>...</svg>
</ng-template>
```

<hr>

<h2>CHILD</h2>

<p>HTML:</p>

<pre class="lang-html prettyprint-override"><code><ng-container *ngIf="$icon" [ngTemplateOutlet]="$icon"></ng-container>

...
</code>```

TYPESCRIPT:

export class InputComponent implements ControlValueAccessor {
  ...

  @Input('icon') public $icon: TemplateRef<any>;
  private color: boolean = false; // --> When this is true, apply a new class

  public onFocus(): void {
    this.color = true;
  }

  ...
```

<p>SCSS:</p>

<pre class="lang-css prettyprint-override"><code>::ng-deep {
    svg {
        transition: .3s fill;
        fill: map-get($colors, placeholder);
    }
}
</code>```

答:
with ng-container you can pass context like

```<code><ng-container [ngTemplateOutlet]="user;context: {color: className}></ng-container>
</code>```

then you can use it like in template

```<code><ng-template let-color="color">
    <div [class]="color"></div>
</ng-template>
</code>```

Body:
I have a PARENT component which has a CHILD component.
This PARENT component holds ng-template which will be bound into the CHILD component.

In order to style the ng-container's element (svg), I used ng-deep and it worked.

What I want now is to dynamically add a class to the ng-container's element (svg) from the CHILD component (like ngClass);

Please see my code below for better understading.

PARENT

HTML:

...

<app-input [icon]="userIcon"></app-input>

...

<ng-template #userIcon>
    <svg>...</svg>
</ng-template>

CHILD

HTML:

<ng-container *ngIf="$icon" [ngTemplateOutlet]="$icon"></ng-container>

...

TYPESCRIPT:

export class InputComponent implements ControlValueAccessor {
  ...

  @Input('icon') public $icon: TemplateRef<any>;
  private color: boolean = false; // --> When this is true, apply a new class

  public onFocus(): void {
    this.color = true;
  }

  ...

SCSS:

::ng-deep {
    svg {
        transition: .3s fill;
        fill: map-get($colors, placeholder);
    }
}

Body:
with ng-container you can pass context like

<ng-container [ngTemplateOutlet]="user;context: {color: className}></ng-container>

then you can use it like in template

<ng-template let-color="color">
    <div [class]="color"></div>
</ng-template>


问:
How to resolve MissingSchemaError in mongodb using mongoose
I am creating a schema model dynamically. So I am not able to use this model for other events like a record save, update, remove, etc. If I use that I am getting this error:

Error:  MissingSchemaError: Schema hasn't been registered for model
  "XYZ".  Use mongoose.model(name, schema)

I do not know why it is coming to this error. I have tried many times but not working. Please help to resolve this issue?

schemamodel.js:

```<code>    /* model.js */
 'use strict';
 var mongoose = require('mongoose'),
     Schema = mongoose.Schema;

 function dynamicModel(suffix) {
     var collsName = suffix.charAt(0).toUpperCase() + suffix.slice(1);
     var newSchema = new Schema({
         product_name: {
             type: String
         }
     }, {
         versionKey: false
     });
     try {
         if (mongoose.model(collsName)) return mongoose.model(collsName);
     } catch (e) {
         if (e.name === 'MissingSchemaError') {
             return mongoose.model(collsName, newSchema, suffix);
         }
     }
 }
 module.exports = dynamicModel;
</code>```

data.controller.js:

```<code>module.exports.newCollection = (req, res, next) => {
    var collectionName = req.query.collectionName;
    var NewModel;
    mongoose.connection.db.listCollections().toArray(function(err, names) {
        if (err) {
            console.log(err);
        } else {
            names.forEach(function(e, i, a) {
                if (e.name == collectionName.toLowerCase()) {
                    console.log("The collection already exists");
                } else {
                    console.log("The collection not exists");
                    NewModel = require(path.resolve('./models/schemamodel.js'))(collectionName);
                    NewModel.create({}, function(err, doc) {});
                }
            });
        }
    });
}
//get data collection from collection
module.exports.getCollectionData = (req, res, next) => {
    let collection = req.query.collection;
    let data = mongoose.model(collection); // here getting MissingSchemaError
    data.find({}, function(err, docs) {
        if (err) {
            console.log('ss' + err);
            return;
        } else {
            console.log("Successful loaded");
        }
    });
}
</code>```

api call:

```<code>http://localhost:3000/api/getCollectionData?collection=Apply
</code>```

答:
Instead of mongoose.model(...) you need the DB connection db.model(...)

```<code> /* model.js */
 'use strict';
 var mongoose = require('mongoose'),
     Schema = mongoose.Schema;
 const db = mongoose.createConnection(
      "mongodb://localhost:27017/datadetails",
      {
        useNewUrlParser: true,
        useUnifiedTopology: true
      }
  );
 function dynamicModel(suffix) {
     var collsName = suffix.charAt(0).toUpperCase() + suffix.slice(1);
     var newSchema = new Schema({
         product_name: {
             type: String
         }
     }, {
         versionKey: false
     });
     try {
         if (db.model(collsName)) return db.model(collsName);
     } catch (e) {
         if (e.name === 'MissingSchemaError') {
             return db.model(collsName, newSchema, suffix);
         }
     }
 }
 module.exports = dynamicModel;
</code>```

Body:
I am creating a schema model dynamically. So I am not able to use this model for other events like a record save, update, remove, etc. If I use that I am getting this error:

Error:  MissingSchemaError: Schema hasn't been registered for model
  "XYZ".  Use mongoose.model(name, schema)

I do not know why it is coming to this error. I have tried many times but not working. Please help to resolve this issue?

schemamodel.js:

    /* model.js */
 'use strict';
 var mongoose = require('mongoose'),
     Schema = mongoose.Schema;

 function dynamicModel(suffix) {
     var collsName = suffix.charAt(0).toUpperCase() + suffix.slice(1);
     var newSchema = new Schema({
         product_name: {
             type: String
         }
     }, {
         versionKey: false
     });
     try {
         if (mongoose.model(collsName)) return mongoose.model(collsName);
     } catch (e) {
         if (e.name === 'MissingSchemaError') {
             return mongoose.model(collsName, newSchema, suffix);
         }
     }
 }
 module.exports = dynamicModel;

data.controller.js:

module.exports.newCollection = (req, res, next) => {
    var collectionName = req.query.collectionName;
    var NewModel;
    mongoose.connection.db.listCollections().toArray(function(err, names) {
        if (err) {
            console.log(err);
        } else {
            names.forEach(function(e, i, a) {
                if (e.name == collectionName.toLowerCase()) {
                    console.log("The collection already exists");
                } else {
                    console.log("The collection not exists");
                    NewModel = require(path.resolve('./models/schemamodel.js'))(collectionName);
                    NewModel.create({}, function(err, doc) {});
                }
            });
        }
    });
}
//get data collection from collection
module.exports.getCollectionData = (req, res, next) => {
    let collection = req.query.collection;
    let data = mongoose.model(collection); // here getting MissingSchemaError
    data.find({}, function(err, docs) {
        if (err) {
            console.log('ss' + err);
            return;
        } else {
            console.log("Successful loaded");
        }
    });
}

api call:

http://localhost:3000/api/getCollectionData?collection=Apply

Body:
Instead of mongoose.model(...) you need the DB connection db.model(...)

 /* model.js */
 'use strict';
 var mongoose = require('mongoose'),
     Schema = mongoose.Schema;
 const db = mongoose.createConnection(
      "mongodb://localhost:27017/datadetails",
      {
        useNewUrlParser: true,
        useUnifiedTopology: true
      }
  );
 function dynamicModel(suffix) {
     var collsName = suffix.charAt(0).toUpperCase() + suffix.slice(1);
     var newSchema = new Schema({
         product_name: {
             type: String
         }
     }, {
         versionKey: false
     });
     try {
         if (db.model(collsName)) return db.model(collsName);
     } catch (e) {
         if (e.name === 'MissingSchemaError') {
             return db.model(collsName, newSchema, suffix);
         }
     }
 }
 module.exports = dynamicModel;


问:
Nextjs- api routes , How to remove a cookie from header?
I have two API routes which I want to set two cookies in /api/login.js and remove them in /api/logout.js.

so this is my login API:

```<code>import { serialize } from 'cookie';

export default async (req, res) => {
  res.setHeader('Set-Cookie', [
    serialize('mytoken1', 'mytoken1Value', {
      path: '/',
    }),
    serialize('mytoken2', 'mytoken2Value', {
      path: '/',
    }),
  ]);

  res.writeHead(302, { Location: '/' });
  res.end();
}
</code>```

and this is my logout API:

```<code>export default async (req, res) => {
  res.removeHeader('Set-Cookie')

  res.writeHead(302, { Location: '/api/login' });
  res.end();
}
</code>```

but the logout doesn't remove the cookies so I still can see them in _app.js ---console.log(req.headers.cookie)--- when I reload the page. Do you know how to remove a cookie in this situation?

答:
So, after challenging too much with every solution I ended up with this and it works fine:

(I had multiple cookies and I had to use nodejs methods cause I was coding in nextjs API routes without any middleware)

```<code>export default async (req, res) => {
  /* remove cookies from request header */
  res.setHeader('Set-Cookie', [
    serialize('mytoken1', '', {
      maxAge: -1,
      path: '/',
    }),
    serialize('mytoken2', '', {
      maxAge: -1,
      path: '/',
    }),
  ]);

  res.writeHead(302, { Location: '/api/login' });
  res.end();
}
</code>```

The point was the maxAge which should be -1 to make it expire. I tried it with Date.now(). And when you have multiple cookies you have to end the response after manipulating both of them.

Body:
I have two API routes which I want to set two cookies in /api/login.js and remove them in /api/logout.js.

so this is my login API:

import { serialize } from 'cookie';

export default async (req, res) => {
  res.setHeader('Set-Cookie', [
    serialize('mytoken1', 'mytoken1Value', {
      path: '/',
    }),
    serialize('mytoken2', 'mytoken2Value', {
      path: '/',
    }),
  ]);

  res.writeHead(302, { Location: '/' });
  res.end();
}

and this is my logout API:

export default async (req, res) => {
  res.removeHeader('Set-Cookie')

  res.writeHead(302, { Location: '/api/login' });
  res.end();
}

but the logout doesn't remove the cookies so I still can see them in _app.js ---console.log(req.headers.cookie)--- when I reload the page. Do you know how to remove a cookie in this situation?

Body:
So, after challenging too much with every solution I ended up with this and it works fine:

(I had multiple cookies and I had to use nodejs methods cause I was coding in nextjs API routes without any middleware)

export default async (req, res) => {
  /* remove cookies from request header */
  res.setHeader('Set-Cookie', [
    serialize('mytoken1', '', {
      maxAge: -1,
      path: '/',
    }),
    serialize('mytoken2', '', {
      maxAge: -1,
      path: '/',
    }),
  ]);

  res.writeHead(302, { Location: '/api/login' });
  res.end();
}

The point was the maxAge which should be -1 to make it expire. I tried it with Date.now(). And when you have multiple cookies you have to end the response after manipulating both of them.


问:
Need to first ssh and ping using ansible-playbook
Suppose I have 100 hosts and I want to perform a ssh connection where the  result should print "YES" or "NO"

Then perform a ping that should print  "YES" or "NO"

if ssh make then print Y other No

if ssh make Y then try to perform Ping and print Y along with uptime

if ping getting not access then print N

For example

```<code>SL.No. Server       Ping SSH     Uptime(hrs)
1      Linux-test     y   y      2020-26-05 17:17:44
2      linux-test1    n   -      -
3      linux-test3    y   y      2020-26-05 17:17:44
</code>```

答:
here is a possible way to achieve it.</p>

```<code>- hosts: all
  gather_facts: False
  ignore_errors: True
  ignore_unreachable: True
  tasks:
  - name: ping server
    ping:
    register: ping_status

  - debug:
      msg: "{{ inventory_hostname }} - YES"
    with_items:
      - "{{ inventory_hostname }}"
    when: ping_status.ping is defined

  - name: get uptime
    shell: uptime > /root/uptime.out

  - name: read uptime
    command: cat /root/uptime.out
    register: uptime_server

  - debug:
      msg: "{{ inventory_hostname }} - YES - {{ uptime_server.stdout }}"
    with_items:
      - "{{ inventory_hostname }}"
    when: ping_status.ping is defined

  - debug:
      msg: "{{ inventory_hostname }} - NO"
    with_items:
      - "{{ inventory_hostname }}"
    when: ping_status.ping is undefined
</code>```

Body:
Suppose I have 100 hosts and I want to perform a ssh connection where the  result should print "YES" or "NO"

Then perform a ping that should print  "YES" or "NO"

if ssh make then print Y other No

if ssh make Y then try to perform Ping and print Y along with uptime

if ping getting not access then print N

For example

SL.No. Server       Ping SSH     Uptime(hrs)
1      Linux-test     y   y      2020-26-05 17:17:44
2      linux-test1    n   -      -
3      linux-test3    y   y      2020-26-05 17:17:44

Body:
here is a possible way to achieve it.

- hosts: all
  gather_facts: False
  ignore_errors: True
  ignore_unreachable: True
  tasks:
  - name: ping server
    ping:
    register: ping_status

  - debug:
      msg: "{{ inventory_hostname }} - YES"
    with_items:
      - "{{ inventory_hostname }}"
    when: ping_status.ping is defined

  - name: get uptime
    shell: uptime > /root/uptime.out

  - name: read uptime
    command: cat /root/uptime.out
    register: uptime_server

  - debug:
      msg: "{{ inventory_hostname }} - YES - {{ uptime_server.stdout }}"
    with_items:
      - "{{ inventory_hostname }}"
    when: ping_status.ping is defined

  - debug:
      msg: "{{ inventory_hostname }} - NO"
    with_items:
      - "{{ inventory_hostname }}"
    when: ping_status.ping is undefined


问:
How to get the aliases of all data nodes in DolphinDB
I deploy a DolphinDB cluster the config is as bellow,

```<code>mode=controller
localSite=192.168.1.12:19100:master

localSite,mode
192.168.1.12:19110:agent_c1,agent
192.168.1.13:19110:agent_c2,agent
192.168.1.12:19111:DFS_NODE1,datanode
192.168.1.12:19112:DFS_NODE2,datanode
192.168.1.13:19111:DFS_NODE3,datanode
192.168.1.13:19112:DFS_NODE4,datanode
</code>```

I connect 192.168.1.13:19111using dolphindb GUI, then execute the following code,

```<code>getNodeAlias()
</code>```

Then get the alias of the local node,namely DFS_NODE3. Next, I want to get the aliases of  all the other data nodes. Is there an function such as getNodeAlias for getting the aliases of  all data nodes?

答:
There are two ways to do this

1) On controller node, running function getClusterPerf() will return a table with all details. The "name" field in particular is what you are looking for.

2) On any data node, run pnodeRun(getNodeAlias), which basically runs getNodeAlias on each node and returns all results as a table.

Body:
I deploy a DolphinDB cluster the config is as bellow,

mode=controller
localSite=192.168.1.12:19100:master

localSite,mode
192.168.1.12:19110:agent_c1,agent
192.168.1.13:19110:agent_c2,agent
192.168.1.12:19111:DFS_NODE1,datanode
192.168.1.12:19112:DFS_NODE2,datanode
192.168.1.13:19111:DFS_NODE3,datanode
192.168.1.13:19112:DFS_NODE4,datanode

I connect 192.168.1.13:19111using dolphindb GUI, then execute the following code,

getNodeAlias()

Then get the alias of the local node,namely DFS_NODE3. Next, I want to get the aliases of  all the other data nodes. Is there an function such as getNodeAlias for getting the aliases of  all data nodes?


问:
Build React component from string with placeholders
I need to dynamically build a React component based on consistently structured text in an unknown order. How do I replace the placeholder numbers (identified in some consistent way, see below) with corresponding components that consume the placeholder as props?

```<code>const text = "some (1) arbitrary amount of [2] text";

return (
  <div>
    some
    <Component1 var={1} />
    arbitrary amount of
    <Component2 var={2} />
    text
   </div>
)
</code>```

The placement and order of [] and () is not consistent, so that:

```<code>const text = "[2] some arbitrary amount (1) of text";

return (
  <div>
    <Component2 var={2} />
    some arbitrary amount
    <Component1 var={1} />
    of text
   </div>
)
</code>```

答:
Its a bit tricky, to simplify we replace only one placeholder (1):

```<code>const App = () => {
  return <div>{splitAndRender(text, `(1)`, Component1)}</div>;
};
</code>```

Where splitAndRender can be implemented like:

```<code>const splitAndRender = (text, regex, Component) => {
  const splitByRegex = text.split(regex);
  return splitByRegex.reduce((acc, curr, index) => {
    const isLastItem = index === splitByRegex.length - 1;
    return [...acc, curr, isLastItem ? null : <Component key={index} />];
  }, []);
};
</code>```

For an unknown number of placeholders, it should be done by resursing the returned array from splitAndRender, looking for strings, and calling splitAndRender on such strings.

Body:
I need to dynamically build a React component based on consistently structured text in an unknown order. How do I replace the placeholder numbers (identified in some consistent way, see below) with corresponding components that consume the placeholder as props?

const text = "some (1) arbitrary amount of [2] text";

return (

    some
    <Component1 var={1} />
    arbitrary amount of
    <Component2 var={2} />
    text

)

The placement and order of [] and () is not consistent, so that:

const text = "[2] some arbitrary amount (1) of text";

return (

    <Component2 var={2} />
    some arbitrary amount
    <Component1 var={1} />
    of text

)

Body:
Its a bit tricky, to simplify we replace only one placeholder (1):

const App = () => {
  return <div>{splitAndRender(text, `(1)`, Component1)}</div>;
};

Where splitAndRender can be implemented like:

const splitAndRender = (text, regex, Component) => {
  const splitByRegex = text.split(regex);
  return splitByRegex.reduce((acc, curr, index) => {
    const isLastItem = index === splitByRegex.length - 1;
    return [...acc, curr, isLastItem ? null : <Component key={index} />];
  }, []);
};

For an unknown number of placeholders, it should be done by resursing the returned array from splitAndRender, looking for strings, and calling splitAndRender on such strings.


问:
Combine AND OR and NOT?
I seem to be stuck searching for a solution:

I have this SQL query:

```<code>SELECT
    c.CompanyName AS Kunde,
    c.IsActiveClient AS "Aktiv i CV",
    c.ssn AS CVR, cf.CustomFieldDefinitionFk,
    cf.Value
FROM
    Person AS c
INNER JOIN
    CustomFields AS cf ON  c.Id = cf.PersonFk
WHERE
    cf.Value = 'Visma'
ORDER BY
    Kunde;
</code>```

This works fine I get this output:

But in the same column (customFields->Value) I have some "kunde/Customers" that I want to exclude from my list.

They have both Visma and the "1850..." in "Value" (in 2 rows)

But if they have the "1850" row, they should not be in my list at all even though they have the "Visma" Value.

I have tried a lot of NOT like and other basics. No luck.

答:
Use NOT EXISTS:</p>

```<code>SELECT
  c.CompanyName AS Kunde, c.IsActiveClient AS "Aktiv i CV", c.ssn AS CVR,
  cf.CustomFieldDefinitionFk, cf.Value
FROM Person AS c INNER JOIN CustomFields AS cf
ON  c.Id = cf.PersonFk
WHERE cf.Value = 'Visma'
AND NOT EXISTS (
  SELECT 1 FROM CustomFields
  WHERE PersonFk = cf.PersonFk AND Value LIKE '1850%'
)
ORDER BY Kunde;
</code>```

Title: Combine AND OR and NOT?

Body:
I seem to be stuck searching for a solution:

I have this SQL query:

SELECT
    c.CompanyName AS Kunde,
    c.IsActiveClient AS "Aktiv i CV",
    c.ssn AS CVR, cf.CustomFieldDefinitionFk,
    cf.Value
FROM
    Person AS c
INNER JOIN
    CustomFields AS cf ON  c.Id = cf.PersonFk
WHERE
    cf.Value = 'Visma'
ORDER BY
    Kunde;

This works fine I get this output:

But in the same column (customFields->Value) I have some "kunde/Customers" that I want to exclude from my list.

They have both Visma and the "1850..." in "Value" (in 2 rows)

But if they have the "1850" row, they should not be in my list at all even though they have the "Visma" Value.

I have tried a lot of NOT like and other basics. No luck.

Body:
Use NOT EXISTS:

SELECT
  c.CompanyName AS Kunde, c.IsActiveClient AS "Aktiv i CV", c.ssn AS CVR,
  cf.CustomFieldDefinitionFk, cf.Value
FROM Person AS c INNER JOIN CustomFields AS cf
ON  c.Id = cf.PersonFk
WHERE cf.Value = 'Visma'
AND NOT EXISTS (
  SELECT 1 FROM CustomFields
  WHERE PersonFk = cf.PersonFk AND Value LIKE '1850%'
)
ORDER BY Kunde;


问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答: In 20 years people will probably not consider it a high level language, but at the moment it certainly is.  It's all relative to your basis of comparison.  Compared to Assembler, it is a very high level language.  Compared to a hypothetical computer program that writes the code for you (as Brian called a 5GL), then I guess it isn't.</p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: LuckyLindy


问:
Vertical gallery in android
i am developing an app, for which I need a gallery to be set in vertical mode instead of horizontal mode. my question is, is there any possibilities for me to show a vertical gallery kind of widget?
Any help is appreciated.</p>

答: Ok. so i came to know that vertical gallery in android is not possible with the normal gallery widget. So I tried using Custom Listview with some modifications to change the look of the listview. Now my listview looks exactly like a vertical scrollable gallery. </p>

Title: Vertical gallery in android


问:
Use cookieless or session-cookie in ASP.NET MVC 5's UseCookieAuthentication()
I have an ASP.NET MVC 5 application, which using the cookie authetication. However, after running penetration tests, it was vulnerable to MITM attack, where this cookie can be re-used if is stolen.

```<code>// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Authentication/Login")
});
</code>```

My question is: how to invalidate / expire this cookie upon logout? (not the cookie itself, but the value of the cookie uses by ASP.NET)

This cookie appears to be not under the control of web.config's sessionState, where it can be stored in memory. Can cookie above be configured to store as session cookie?

```<code><sessionState mode="InProc" ... />
</code>```

Any better way?

答:
You could implement your own ITicketStore to keep the value in session. Your implementation goes into the SessionStore of the CookieOptions. Although I wouldn't use InProc. This will enable you to kill it upon logout. The other thing is you should set the ExpireTimeSpan.

The MITM attack would technically still work, but this makes it slightly harder. To mitigate it further you should be doing other things such as using https and tls 1.3.

Body:
I have an ASP.NET MVC 5 application, which using the cookie authetication. However, after running penetration tests, it was vulnerable to MITM attack, where this cookie can be re-used if is stolen.

// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Authentication/Login")
});

My question is: how to invalidate / expire this cookie upon logout? (not the cookie itself, but the value of the cookie uses by ASP.NET)

This cookie appears to be not under the control of web.config's sessionState, where it can be stored in memory. Can cookie above be configured to store as session cookie?

<sessionState mode="InProc" ... />

Any better way?


问:
Not able to access JSON in EJS template inside script
I am trying to build a webapp which renders dynamic charts based on JSON passed from node to client side.

However I am not able to access json variable inside

Results Page

    <script>
    var specimenDate = <%= data.areaCode %>
    var cases = <%= data.dailyLabConfirmedCases %>
    var data1 = [
            {
                x: specimenDate,
                y: cases,
                type: 'bar'
            }
        ];
        Plotly.newPlot('myDiv', data);
    </script>

```

I am new to node and ejs. End goal is to pass array of JSON (two fields) in x and y variable of plotly object.

答:
I see two issues here:

1) You are passing the data incorrectly to the frontend javascript. <%= is always wrong because it encodes HTML entities, but we are in a JS script tag and not in regular HTML. Instead, you want to pass it as JSON using JSON.stringify, and use <%- to prevent HTML-encoding:

var specimenDate = <%- JSON.stringify(data.areaCode) %>
```

<p>This still has two issues though: Firstly, <code>JSON.stringify(undefined)</code> will produce <code>undefined</code> (and not a string) which becomes an empty output after <code><%-</code>, so you will get a syntax error in case the value was undefined. Secondly, a string containing <code></script></code> will escape the script block and wreak havoc. I'd recommend using something like <code>devalue</code> instead of <code>JSON.stringify</code>.</p>

<p>2) You are accessing <code>data.areaCode</code>, but I see that <code>data</code> actually comes from <code>filtered</code>, and <code>filtered</code> is the result of an <code>Array.prototype.filter</code> call, which returns <em>an array</em> of all matching elements. Yet, you are accessing the <code>areaCode</code> property as if <code>data</code> was directly one of the matching elements, not an array of all matching elements.</p>

<p>If it is intended that you have an array there, you have to loop over its entries, or access one directly, for example <code>data[0].areaCode</code> (but also you have to make sure <code>data[0]</code> is always existing).</p>

<p>If this is not intended, then you just used the wrong array method. You can use <code>Array.prototype.find</code> to return the first match or <code>undefined</code> otherwise.</p>

<p>Example:</p>

<pre class="lang-js prettyprint-override"><code>const db = [
  { areaCode: 1, text: 'A' },
  { areaCode: 2, text: 'B' },
  { areaCode: 2, text: 'C' }
]

console.log(db.filter(el => el.areaCode === 1)) // [{ areaCode: 1, text: 'A' }]
console.log(db.filter(el => el.areaCode === 2)) // [{ areaCode: 2, text: 'B' },
                                                //  { areaCode: 2, text: 'C' }]
console.log(db.filter(el => el.areaCode === 3)) // []

console.log(db.find(el => el.areaCode === 1)) // { areaCode: 1, text: 'A' }
console.log(db.find(el => el.areaCode === 2)) // { areaCode: 2, text: 'B' }
console.log(db.find(el => el.areaCode === 3)) // undefined
</code>```

Body:
I am trying to build a webapp which renders dynamic charts based on JSON passed from node to client side.

However I am not able to access json variable inside

Results Page

I am new to node and ejs. End goal is to pass array of JSON (two fields) in x and y variable of plotly object.

Body:
I see two issues here:

1) You are passing the data incorrectly to the frontend javascript. <%= is always wrong because it encodes HTML entities, but we are in a JS script tag and not in regular HTML. Instead, you want to pass it as JSON using JSON.stringify, and use <%- to prevent HTML-encoding:

var specimenDate = <%- JSON.stringify(data.areaCode) %>

This still has two issues though: Firstly, JSON.stringify(undefined) will produce undefined (and not a string) which becomes an empty output after <%-, so you will get a syntax error in case the value was undefined. Secondly, a string containing </script> will escape the script block and wreak havoc. I'd recommend using something like devalue instead of JSON.stringify.

2) You are accessing data.areaCode, but I see that data actually comes from filtered, and filtered is the result of an Array.prototype.filter call, which returns an array of all matching elements. Yet, you are accessing the areaCode property as if data was directly one of the matching elements, not an array of all matching elements.

If it is intended that you have an array there, you have to loop over its entries, or access one directly, for example data[0].areaCode (but also you have to make sure data[0] is always existing).

If this is not intended, then you just used the wrong array method. You can use Array.prototype.find to return the first match or undefined otherwise.

Example:

const db = [
  { areaCode: 1, text: 'A' },
  { areaCode: 2, text: 'B' },
  { areaCode: 2, text: 'C' }
]

console.log(db.filter(el => el.areaCode === 1)) // [{ areaCode: 1, text: 'A' }]
console.log(db.filter(el => el.areaCode === 2)) // [{ areaCode: 2, text: 'B' },
                                                //  { areaCode: 2, text: 'C' }]
console.log(db.filter(el => el.areaCode === 3)) // []

console.log(db.find(el => el.areaCode === 1)) // { areaCode: 1, text: 'A' }
console.log(db.find(el => el.areaCode === 2)) // { areaCode: 2, text: 'B' }
console.log(db.find(el => el.areaCode === 3)) // undefined


问:
Firefox scroll bars but not on Chrome while loading a video in iframe
I'm having trouble finding while loading a remote video in Iframe . On Firefox, it's showing side scrolling to the right but on Chrome its working fine
css for video is as follows

remoteVideo { right: 0; bottom: 0; min-width: 100%; min-height: 100%; }

答: Overflow should be set to hidden, not auto</p>


问:
HDFS File Compaction with continuous ingestion
We have few tables in HDFS which are getting approx. 40k new files per day. We need to compact these tables every two weeks and for that we need to stop ingestion.

We have spark ingestion getting data from kafka and adding to HDFS (Hive external tables) every 30 mins. The data is queried as soon as it is ingested, our SLA is less than an hour so we can not increase the batch interval.

The tables are partition on two fields, we get older data constantly so most of the partitions are updated during each injection batch

eg:
/user/head/warehouse/main_table/state=CA/store=macys/part-00000-017258f8-aaa-bbb-ccc-wefdsds.c000.snappy.parquet

We are looking into ways to reduce number of file creations but even with that we will have to do compaction every 3/4 weeks if not two.

As most of the partitions are updated constantly, we need to stop the injection (~ 1 day) before starting compaction which is impacting our users.

I am looking for ways to compact automatically with out stopping the ingestion?

答:
The chosen partitioning scheme is somewhat unfortunate. Still there are a couple of things you can do. I'm relying on the fact that you can change partition's location atomically in Hive (alter table ... partition ... set location):

Copy a partition's hdfs directory to a different location

Compact copied data

Copy new files that were ingested since step 1

do "alter table ... partition ... set location" to point Hive to a new compacted location.

Start ingesting to this new location (in case if this step is tricky you can just as well replace the "small" files in the original partition location with their compacted version and do "alter table ... partition ... set location" again to point Hive back to the original partition location.

You'll have to keep this process running iterating partition-by-partition on a continuous basis.


问:
Last layer of CNN with SVM in the loss function
How are you? I am trying to implement an SVM within of the keras cost function using
sklearn.svm. However, I always get errors. I believe the problem is to convert the y_true and y_pred tensor into a numpy array to be used in sklearn.svm. Then I need to convert the predicted results to tensor to be used in the cost function of keras (categorical_hinge).

Can anybody help me?

```<code>model_input = Input(shape = (img_width, img_height, channel_axis))
x = Convolution2D_bn(model_input, 32, 3, 3, strides=(2, 2), padding='valid')
x = Convolution2D_bn(x, 32, 3, 3, padding='valid')
x = Convolution2D_bn(x, 64, 3, 3)
x = MaxPooling2D((3, 3), strides=(2, 2))(x)

x = Convolution2D_bn(x, 80, 1, 1, padding='valid')
x = Convolution2D_bn(x, 192, 3, 3, padding='valid')
more model
# Classification block
x = GlobalAveragePooling2D()(x)
x = Dense(4096, kernel_regularizer=l2(1e-4), name='Dense_1')(x)
x = Activation('relu', name='relu1')(x)
x = Dropout(DROPOUT)(x)
x = Dense(4096, kernel_regularizer=l2(1e-4), name='Dense_2')(x)
x = Activation('relu', name='relu2')(x)
model_output = Dropout(DROPOUT)(x)
model = Model(model_input, model_output)
model.summary()

import tensorflow as tf
from keras import backend as K
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from keras.losses import categorical_hinge
def custom_loss_value(y_true, y_pred):
    X = K.eval(y_pred)
    print(X)
    Y = np.ravel(K.eval(y_true))
    Predict = []
    Prob = []
    scaler = StandardScaler()
    X = scaler.fit_transform(X)
    param_grid = {'C': [0.1, 1, 8, 10], 'gamma': [0.001, 0.01, 0.1, 1]}
    SVM = GridSearchCV(SVC(kernel='rbf',probability=True), cv=3, param_grid=param_grid, scoring='auc', verbose=1)
    SVM.fit(X, Y)
    Final_Model = SVM.best_estimator_
    Predict = Final_Model.predict(X)
    Prob = Final_Model.predict_proba(X)
    return categorical_hinge(tf.convert_to_tensor(Y, dtype=tf.float32), tf.convert_to_tensor(Predict, dtype=tf.float32))

sgd = SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss=custom_loss_value, optimizer=sgd, metrics=['accuracy'])
</code>```

答:
Try this</p>

```<code>y_test = np.argmax(y_test , axis=1)
y_pred = np.argmax(y_pred , axis=1)
</code>```

Body:
How are you? I am trying to implement an SVM within of the keras cost function using
sklearn.svm. However, I always get errors. I believe the problem is to convert the y_true and y_pred tensor into a numpy array to be used in sklearn.svm. Then I need to convert the predicted results to tensor to be used in the cost function of keras (categorical_hinge).

Can anybody help me?

model_input = Input(shape = (img_width, img_height, channel_axis))
x = Convolution2D_bn(model_input, 32, 3, 3, strides=(2, 2), padding='valid')
x = Convolution2D_bn(x, 32, 3, 3, padding='valid')
x = Convolution2D_bn(x, 64, 3, 3)
x = MaxPooling2D((3, 3), strides=(2, 2))(x)

x = Convolution2D_bn(x, 80, 1, 1, padding='valid')
x = Convolution2D_bn(x, 192, 3, 3, padding='valid')
more model
# Classification block
x = GlobalAveragePooling2D()(x)
x = Dense(4096, kernel_regularizer=l2(1e-4), name='Dense_1')(x)
x = Activation('relu', name='relu1')(x)
x = Dropout(DROPOUT)(x)
x = Dense(4096, kernel_regularizer=l2(1e-4), name='Dense_2')(x)
x = Activation('relu', name='relu2')(x)
model_output = Dropout(DROPOUT)(x)
model = Model(model_input, model_output)
model.summary()

import tensorflow as tf
from keras import backend as K
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from keras.losses import categorical_hinge
def custom_loss_value(y_true, y_pred):
    X = K.eval(y_pred)
    print(X)
    Y = np.ravel(K.eval(y_true))
    Predict = []
    Prob = []
    scaler = StandardScaler()
    X = scaler.fit_transform(X)
    param_grid = {'C': [0.1, 1, 8, 10], 'gamma': [0.001, 0.01, 0.1, 1]}
    SVM = GridSearchCV(SVC(kernel='rbf',probability=True), cv=3, param_grid=param_grid, scoring='auc', verbose=1)
    SVM.fit(X, Y)
    Final_Model = SVM.best_estimator_
    Predict = Final_Model.predict(X)
    Prob = Final_Model.predict_proba(X)
    return categorical_hinge(tf.convert_to_tensor(Y, dtype=tf.float32), tf.convert_to_tensor(Predict, dtype=tf.float32))

sgd = SGD(lr=0.001, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss=custom_loss_value, optimizer=sgd, metrics=['accuracy'])

Body:
Try this

y_test = np.argmax(y_test , axis=1)
y_pred = np.argmax(y_pred , axis=1)


问:
None of DatetimeIndex are in column
I was trying to plot my MACD Line with date, but seems to face error of none of Datetimeindex are in column, below are my codes</p>

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
%matplotlib inline
plt.style = 'ggplot'

stock = "SPY"
Start_date = '2019-1-1'
End_date = dt.datetime.today()
Quick_EMA = 12
Slow_EMA = 26
df = web.DataReader(stock,'yahoo',Start_date,End_date)
df['12EMA'] = df['Adj Close'].ewm(span = Quick_EMA, min_periods = Quick_EMA).mean()
df['26EMA'] = df['Adj Close'].ewm(span = Slow_EMA, min_periods = Slow_EMA).mean()
df['MACDLine'] = df['12EMA'] - df['26EMA']
y = df['MACDLine']
x = df.index
df.plot(x,y)

KeyError: "None of [DatetimeIndex(['2018-12-31', '2019-01-02', '2019-01-03', '2019-01-04',\n               '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10',\n               '2019-01-11', '2019-01-14',\n               ...\n               '2020-05-15', '2020-05-18', '2020-05-19', '2020-05-20',\n               '2020-05-21', '2020-05-22', '2020-05-26', '2020-05-27',\n               '2020-05-28', '2020-05-29'],\n              dtype='datetime64[ns]', name='Date', length=356, freq=None)] are in the [columns]"

</code>```

答:
The data is specified like this.

```<code>df.plot(y='MACDLine')

df['MACDLine'].plot()
</code>```

Title: None of DatetimeIndex are in column

Body:
I was trying to plot my MACD Line with date, but seems to face error of none of Datetimeindex are in column, below are my codes

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import datetime as dt
%matplotlib inline
plt.style = 'ggplot'

stock = "SPY"
Start_date = '2019-1-1'
End_date = dt.datetime.today()
Quick_EMA = 12
Slow_EMA = 26
df = web.DataReader(stock,'yahoo',Start_date,End_date)
df['12EMA'] = df['Adj Close'].ewm(span = Quick_EMA, min_periods = Quick_EMA).mean()
df['26EMA'] = df['Adj Close'].ewm(span = Slow_EMA, min_periods = Slow_EMA).mean()
df['MACDLine'] = df['12EMA'] - df['26EMA']
y = df['MACDLine']
x = df.index
df.plot(x,y)

KeyError: "None of [DatetimeIndex(['2018-12-31', '2019-01-02', '2019-01-03', '2019-01-04',\n               '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10',\n               '2019-01-11', '2019-01-14',\n               ...\n               '2020-05-15', '2020-05-18', '2020-05-19', '2020-05-20',\n               '2020-05-21', '2020-05-22', '2020-05-26', '2020-05-27',\n               '2020-05-28', '2020-05-29'],\n              dtype='datetime64[ns]', name='Date', length=356, freq=None)] are in the [columns]"

Body:
The data is specified like this.

df.plot(y='MACDLine')

df['MACDLine'].plot()


问:
Linking a jpeglib to in makefile
Hi I am trying to use jpeglib in my code and i have trouble linking it with my Makefile
I downloaded it in tar.gz file then extracted it and did all the ./configure then the makes and all this stuff but now I have to link it in Makefile and I dunno how here is the Makefile

```<code>CFLAGS+= -Wall -Werror -fPIE -std=gnu99 -g
LDFLAGS=  -pthread

HW=prgsem
BINARIES=prgsem

#LDFLAGS += -L/usr/local/lib -ljpeglib
#CXXFLAGS += -I/usr/local/include
CFLAGS+=$(shell sdl2-config --cflags)
LDFLAGS+=$(shell sdl2-config --libs) -lSDL2_image

all: ${BINARIES}

OBJS=${patsubst %.c,%.o,${wildcard *.c}}

prgsem: ${OBJS}
    ${CC} ${OBJS} ${CXXFLAGS}  ${LDFLAGS} -o $@

${OBJS}: %.o: %.c
    ${CC} -c ${CFLAGS}  $< -o $@

clean:
    rm -f ${BINARIES} ${OBJS}
</code>```

The commented stuff is what I tried and didnt work. Also I tried to change the #include itself. Tried #include "jpeglib.h" also #include <jpeglib.h> nothing worked.

EDIT: added make compile error message

```<code>cc xwin_sdl.o event_queue.o prg_io_nonblock.o gui.o main.o prgsem.o messages.o keyboard.o computation.o utils.o   -pthread  -L/usr/local/lib -Wl,-rpath,/usr/local/lib -Wl,--enable-new-dtags -lSDL2 -lSDL2_image -o prgsem
/usr/bin/ld: gui.o: in function `save_img':
/home/peter/Cprog/bab36prga-sem/gui.c:67: undefined reference to `jpeg_std_error'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:69: undefined reference to `jpeg_CreateCompress'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:74: undefined reference to `jpeg_stdio_dest'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:81: undefined reference to `jpeg_set_defaults'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:83: undefined reference to `jpeg_start_compress'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:90: undefined reference to `jpeg_write_scanlines'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:93: undefined reference to `jpeg_finish_compress'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:97: undefined reference to `jpeg_destroy_compress'
collect2: error: ld returned 1 exit status
make: *** [Makefile:19: prgsem] Error 1
</code>```

Thanks for any answers.

答:
Your problem is not during the compilation phase of your program, so changing the #include etc. won't help in this case.

Your problem is during the linking phase, so that means you have not added the library to your link line.  If, for example, the library is named libjpeg.a or libjpeg.so, then you need to add -ljpeg to your link line.  The easiest way is to add it to the end of LDFLAGS:

```<code>LDFLAGS+=$(shell sdl2-config --libs) -lSDL2_image -ljpeg
</code>```

Title: Linking a jpeglib to in makefile

Body:
Hi I am trying to use jpeglib in my code and i have trouble linking it with my Makefile
I downloaded it in tar.gz file then extracted it and did all the ./configure then the makes and all this stuff but now I have to link it in Makefile and I dunno how here is the Makefile

CFLAGS+= -Wall -Werror -fPIE -std=gnu99 -g
LDFLAGS=  -pthread

HW=prgsem
BINARIES=prgsem

#LDFLAGS += -L/usr/local/lib -ljpeglib
#CXXFLAGS += -I/usr/local/include
CFLAGS+=$(shell sdl2-config --cflags)
LDFLAGS+=$(shell sdl2-config --libs) -lSDL2_image

all: ${BINARIES}

OBJS=${patsubst %.c,%.o,${wildcard *.c}}

prgsem: ${OBJS}
    ${CC} ${OBJS} ${CXXFLAGS}  ${LDFLAGS} -o $@

${OBJS}: %.o: %.c
    ${CC} -c ${CFLAGS}  $< -o $@

clean:
    rm -f ${BINARIES} ${OBJS}

The commented stuff is what I tried and didnt work. Also I tried to change the #include itself. Tried #include "jpeglib.h" also #include <jpeglib.h> nothing worked.

EDIT: added make compile error message

cc xwin_sdl.o event_queue.o prg_io_nonblock.o gui.o main.o prgsem.o messages.o keyboard.o computation.o utils.o   -pthread  -L/usr/local/lib -Wl,-rpath,/usr/local/lib -Wl,--enable-new-dtags -lSDL2 -lSDL2_image -o prgsem
/usr/bin/ld: gui.o: in function `save_img':
/home/peter/Cprog/bab36prga-sem/gui.c:67: undefined reference to `jpeg_std_error'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:69: undefined reference to `jpeg_CreateCompress'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:74: undefined reference to `jpeg_stdio_dest'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:81: undefined reference to `jpeg_set_defaults'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:83: undefined reference to `jpeg_start_compress'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:90: undefined reference to `jpeg_write_scanlines'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:93: undefined reference to `jpeg_finish_compress'
/usr/bin/ld: /home/peter/Cprog/bab36prga-sem/gui.c:97: undefined reference to `jpeg_destroy_compress'
collect2: error: ld returned 1 exit status
make: *** [Makefile:19: prgsem] Error 1

Thanks for any answers.

Body:
Your problem is not during the compilation phase of your program, so changing the #include etc. won't help in this case.

Your problem is during the linking phase, so that means you have not added the library to your link line.  If, for example, the library is named libjpeg.a or libjpeg.so, then you need to add -ljpeg to your link line.  The easiest way is to add it to the end of LDFLAGS:

LDFLAGS+=$(shell sdl2-config --libs) -lSDL2_image -ljpeg


问:
Springboot + Hibernate: Duplicate entry Exception while save entity
i got 2 simple entities:

```<code>@Entity
@Table(name = "user")
public class User extends Base {

   private String firstname;
   private String lastname;

   @OneToMany
   @JoinTable(
        name="user_emails",
        joinColumns = @JoinColumn( name="user_id"),
        inverseJoinColumns = @JoinColumn( name="email_id")
   )
   private List<Email> emails = new ArrayList<>();

   // getter setter
}
</code>```

And Email (dont have any reference to User)

```<code>@Entity
@Table(name = "email")
public class Email extends Base {

    private String sender;

    private String receiver;
}
</code>```

With the first mail everything is working
but now I want to save a second email to the user with the following code (error is thrown). The problem is, that they are 2 mails at the "saveUser-line" and i think hibernate try to save the first one again and get the duplicate entry exceptions. How i have to do it? Important to know: there are other objects like user and all of them try to save emails (also not working).

```<code>    // Create Email object
    eMailRepository.save(email);

    if (user != null) {
        user.getEmails().add(email);
        userDatabaseRepository.save(user); // ERROR THROWN
    }
</code>```

Here are the created entity table

Here are the problem sql:

```<code>Hibernate: insert into user_emails (user_id, email_id) values (?, ?)
</code>```

And here the exception:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'databaseSeedConfig' defined in file [E:\Arbeit\---\target\classes\de\---\config\DatabaseSeedConfig.class]: Invocation of init method failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_1j6q2cqg40ooyo8m7kq2miws2]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
    at de.dev.Pfffff.main(Pfffff.java:10)
Caused by: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_1j6q2cqg40ooyo8m7kq2miws2]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:296)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:536)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:534)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:305)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy134.save(Unknown Source)
    at de.dev.service.EMailQueueService.addEMailToQueue(EMailQueueService.java:132)
    at de.dev.service.EMailQueueService.addEMailToQueue(EMailQueueService.java:91)
    at de.dev.service.UserService.addUser(UserService.java:173)
    at de.dev.config.DatabaseSeedConfig.setUpAdminUser(DatabaseSeedConfig.java:133)
    at de.dev.config.DatabaseSeedConfig.afterPropertiesSet(DatabaseSeedConfig.java:99)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
    ... 16 common frames omitted
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1340)
    at org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:83)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:511)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3290)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2486)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:271)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:532)
    ... 39 common frames omitted
Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'UK_1j6q2cqg40ooyo8m7kq2miws2'
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:955)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1094)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1042)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1345)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1027)
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
    ... 56 common frames omitted
</code>```

答:
Try something like this

Email.java

```<code>@Entity
@Table(name = "user")
@Getter
@Setter
public class User extends Base {

   private String firstname;
   private String lastname;

   @OneToMany
   @JoinTable(
        name="user_emails",
        joinColumns = @JoinColumn( name="user_id"),
        inverseJoinColumns = @JoinColumn( name="email_id")
   )
   private List<Email> emails = new ArrayList<>();

   private void addEmail(Email email){
      emails.add(email);
   }

   private void removeEmail(Email email){
      emails.remove(email);
   }
}
</code>```

UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

  User findByNameAndSurname(String name, String surname);

}
```

<h3>EmailRepository.java</h3>

<pre class="lang-java prettyprint-override"><code>@Repository
public interface EmailRepository extends JpaRepository<Email, Long> {

   Email findBySenderAndReceiver(String sender, String receiver);

}
</code>```

SomeClass.java

@Autowired
private EmailRepository emailRepository;
@Autowired
private UserRepository userRepository;

/*
Some code
*/

emailRepository.saveAndFlush(email);

Email email = emailRepository.findBySenderAndReceiver("Sender", "Receiver");
emailRepository.flush();

User user = userRepository.findByNameAndSurname("Carlos", "Matos");

if(user != null){
 user.addEmail(email);
 userRepository.saveAndFlush(user);
}

```

Body:
i got 2 simple entities:

@Entity
@Table(name = "user")
public class User extends Base {

   private String firstname;
   private String lastname;

   @OneToMany
   @JoinTable(
        name="user_emails",
        joinColumns = @JoinColumn( name="user_id"),
        inverseJoinColumns = @JoinColumn( name="email_id")
   )
   private List<Email> emails = new ArrayList<>();

   // getter setter
}

And Email (dont have any reference to User)

@Entity
@Table(name = "email")
public class Email extends Base {

    private String sender;

    private String receiver;
}

With the first mail everything is working
but now I want to save a second email to the user with the following code (error is thrown). The problem is, that they are 2 mails at the "saveUser-line" and i think hibernate try to save the first one again and get the duplicate entry exceptions. How i have to do it? Important to know: there are other objects like user and all of them try to save emails (also not working).

    // Create Email object
    eMailRepository.save(email);

    if (user != null) {
        user.getEmails().add(email);
        userDatabaseRepository.save(user); // ERROR THROWN
    }

Here are the created entity table

Here are the problem sql:

Hibernate: insert into user_emails (user_id, email_id) values (?, ?)

And here the exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'databaseSeedConfig' defined in file [E:\Arbeit\---\target\classes\de\---\config\DatabaseSeedConfig.class]: Invocation of init method failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_1j6q2cqg40ooyo8m7kq2miws2]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1778)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:742)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:389)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:311)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1213)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1202)
    at de.dev.Pfffff.main(Pfffff.java:10)
Caused by: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [UK_1j6q2cqg40ooyo8m7kq2miws2]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:296)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:253)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:536)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:534)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:305)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy134.save(Unknown Source)
    at de.dev.service.EMailQueueService.addEMailToQueue(EMailQueueService.java:132)
    at de.dev.service.EMailQueueService.addEMailToQueue(EMailQueueService.java:91)
    at de.dev.service.UserService.addUser(UserService.java:173)
    at de.dev.config.DatabaseSeedConfig.setUpAdminUser(DatabaseSeedConfig.java:133)
    at de.dev.config.DatabaseSeedConfig.afterPropertiesSet(DatabaseSeedConfig.java:99)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
    ... 16 common frames omitted
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1340)
    at org.hibernate.action.internal.CollectionUpdateAction.execute(CollectionUpdateAction.java:83)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:511)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3290)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2486)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:271)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:532)
    ... 39 common frames omitted
Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '2' for key 'UK_1j6q2cqg40ooyo8m7kq2miws2'
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:955)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1094)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1042)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1345)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1027)
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
    ... 56 common frames omitted

Body:
Try something like this

Email.java

@Entity
@Table(name = "user")
@Getter
@Setter
public class User extends Base {

   private String firstname;
   private String lastname;

   @OneToMany
   @JoinTable(
        name="user_emails",
        joinColumns = @JoinColumn( name="user_id"),
        inverseJoinColumns = @JoinColumn( name="email_id")
   )
   private List<Email> emails = new ArrayList<>();

   private void addEmail(Email email){
      emails.add(email);
   }

   private void removeEmail(Email email){
      emails.remove(email);
   }
}

UserRepository.java

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

  User findByNameAndSurname(String name, String surname);

}

EmailRepository.java

@Repository
public interface EmailRepository extends JpaRepository<Email, Long> {

   Email findBySenderAndReceiver(String sender, String receiver);

}

SomeClass.java

@Autowired
private EmailRepository emailRepository;
@Autowired
private UserRepository userRepository;

/*
Some code
*/

emailRepository.saveAndFlush(email);

Email email = emailRepository.findBySenderAndReceiver("Sender", "Receiver");
emailRepository.flush();

User user = userRepository.findByNameAndSurname("Carlos", "Matos");

if(user != null){
 user.addEmail(email);
 userRepository.saveAndFlush(user);
}


问:
cannot send mail using php mail function
Im trying to use PHP mail on my local computer,  but its just not working. I am using the standard script from the php website:

PHP error I'm getting

```<code>SMTP server response: 550 Error sending message: Error: FROM address is invalid
</code>```

actual PHP

```<code>$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
</code>```

i downloaded a local mail server, argosoft.  it says the service URL is http://services.argosoft.com/RelayService/Service.asmx . I assume this is what i put in php.ini.

php ini.

```<code> For Win32 only.
 SMTP = services.argosoft.com/RelayService/Service.asmx
 smtp_port = 25
</code>```

答:
Apparently, a number of mail systems have trouble with the carriage return \r.  You might want to modify your $header to use only the new line character \n.  See if that works.

Also, you might want to try using the full From header:

From: Some Name Here <real_email@notAnExample.com>

Body:
Im trying to use PHP mail on my local computer,  but its just not working. I am using the standard script from the php website:

PHP error I'm getting

SMTP server response: 550 Error sending message: Error: FROM address is invalid

actual PHP

$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);

i downloaded a local mail server, argosoft.  it says the service URL is http://services.argosoft.com/RelayService/Service.asmx . I assume this is what i put in php.ini.

php ini.

 For Win32 only.
 SMTP = services.argosoft.com/RelayService/Service.asmx
 smtp_port = 25


问:
Sum values in a list of lists of dictionaries using common key-value pairs
How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

```<code>data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]
</code>```

Expected output:

```<code>op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]
</code>```

答:
Python list comprehension:

```<code>from collections import Counter
x = [[
        {'user': x[0], 'rating': x[1]} for x in
        Counter({d['user']: d['rating'] for d in group}).most_common()] for group in data
]
</code>```

Output:

```<code>[
    [
        {
            "rating": 20,
            "user": 1
        },
        {
            "rating": 10,
            "user": 2
        },
        {
            "rating": 10,
            "user": 3
        }
    ],
    [
        {
            "rating": 80,
            "user": 2
        },
        {
            "rating": 10,
            "user": 1
        },
        {
            "rating": 4,
            "user": 4
        }
    ]
]
</code>```

Body:
How do I sum duplicate elements in a list of lists of dictionaries?

Sample list:

data = [
        [
            {'user': 1, 'rating': 0},
            {'user': 2, 'rating': 10},
            {'user': 1, 'rating': 20},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 20},
            {'user': 1, 'rating': 10}
        ],
    ]

Expected output:

op = [
        [
            {'user': 1, 'rating': 20},
            {'user': 2, 'rating': 10},
            {'user': 3, 'rating': 10}
        ],
        [
            {'user': 4, 'rating': 4},
            {'user': 2, 'rating': 80},
            {'user': 1, 'rating': 30},
        ],
    ]

Body:
Python list comprehension:

from collections import Counter
x = [[
        {'user': x[0], 'rating': x[1]} for x in
        Counter({d['user']: d['rating'] for d in group}).most_common()] for group in data
]

Output:

[
    [
        {
            "rating": 20,
            "user": 1
        },
        {
            "rating": 10,
            "user": 2
        },
        {
            "rating": 10,
            "user": 3
        }
    ],
    [
        {
            "rating": 80,
            "user": 2
        },
        {
            "rating": 10,
            "user": 1
        },
        {
            "rating": 4,
            "user": 4
        }
    ]
]


问:
How can I align statements in android studio?
how can I align statements as follows:

```<code>    textView1 = findViewById(R.id.textView1);
    textView2 = findViewById(R.id.textView2);
    textView3 = findViewById(R.id.textView3);
    textView4 = findViewById(R.id.textView4);
    textView5 = findViewById(R.id.textView5);
    button    = findViewById(R.id.button);
</code>```

instead of

```<code>    textView1 = findViewById(R.id.textView1);
    textView2 = findViewById(R.id.textView2);
    textView3 = findViewById(R.id.textView3);
    textView4 = findViewById(R.id.textView4);
    textView5 = findViewById(R.id.textView5);
    button = findViewById(R.id.button);
</code>```

in Android Studio?

答:
The following works for Java, should probably work for Kotlin too.

Go to File > Settings > Editor > Code Style > Java > Wrapping and Braces > Group Declarations > (check Align Fields in columns)

Body:
how can I align statements as follows:

    textView1 = findViewById(R.id.textView1);
    textView2 = findViewById(R.id.textView2);
    textView3 = findViewById(R.id.textView3);
    textView4 = findViewById(R.id.textView4);
    textView5 = findViewById(R.id.textView5);
    button    = findViewById(R.id.button);

instead of

    textView1 = findViewById(R.id.textView1);
    textView2 = findViewById(R.id.textView2);
    textView3 = findViewById(R.id.textView3);
    textView4 = findViewById(R.id.textView4);
    textView5 = findViewById(R.id.textView5);
    button = findViewById(R.id.button);

in Android Studio?


问:
How to add Header with Authorization for springdoc-openapi endpoint calls
Swagger2 (springfox) worked with:

```<code>@Bean
public Docket getDocket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build()
        .useDefaultResponseMessages(false)
        .globalOperationParameters(Collections.singletonList(getAuthHeader()));
}

private Parameter getAuthHeader() {
    return new ParameterBuilder()
        .parameterType("header")
        .name("Authorization")
        .modelRef(new ModelRef("string"))
        .defaultValue(getBase64EncodedCredentials())
        .build();
}

private String getBase64EncodedCredentials() {
    String auth = authUser.getUser() + ":" + authUser.getPassword();
    byte[] encodedAuth = Base64.encode(auth.getBytes(StandardCharsets.UTF_8));
    return "Basic " + new String(encodedAuth, Charset.defaultCharset());
}
</code>```

Springdoc-openapi:

```<code>@Bean
public OpenAPI getOpenAPI() {
    return new OpenAPI().components(new Components()
        .addHeaders("Authorization", new Header().description("Auth header").schema(new StringSchema()._default(getBase64EncodedCredentials()))));
}
</code>```

I cant achieve it for springdoc-openapi. It seems the header is not working.

答:
The behaviour you are describing is not related to springdoc-openapi. But to swagger-ui which respects the OpenAPI Spec as well:

https://github.com/swagger-api/swagger-ui/issues/5715

The OpenAPI 3 specification does not allow explicitly adding Authorization header. For more information, please read:

Note: Header parameters named Accept, Content-Type and Authorization are not allowed. To describe these headers

Please read:

https://swagger.io/docs/specification/describing-parameters/#header-parameters.

Body:
Swagger2 (springfox) worked with:

@Bean
public Docket getDocket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .select()
        .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
        .apis(RequestHandlerSelectors.any())
        .paths(PathSelectors.any())
        .build()
        .useDefaultResponseMessages(false)
        .globalOperationParameters(Collections.singletonList(getAuthHeader()));
}

private Parameter getAuthHeader() {
    return new ParameterBuilder()
        .parameterType("header")
        .name("Authorization")
        .modelRef(new ModelRef("string"))
        .defaultValue(getBase64EncodedCredentials())
        .build();
}

private String getBase64EncodedCredentials() {
    String auth = authUser.getUser() + ":" + authUser.getPassword();
    byte[] encodedAuth = Base64.encode(auth.getBytes(StandardCharsets.UTF_8));
    return "Basic " + new String(encodedAuth, Charset.defaultCharset());
}

Springdoc-openapi:

@Bean
public OpenAPI getOpenAPI() {
    return new OpenAPI().components(new Components()
        .addHeaders("Authorization", new Header().description("Auth header").schema(new StringSchema()._default(getBase64EncodedCredentials()))));
}

I cant achieve it for springdoc-openapi. It seems the header is not working.


问:
How to fix a weird linux kernel module build problem on raspbian that works fine on x64 ubuntu
I ran into this problem and figured it out but it took me a while because it wasn't obvious, so I thought I'd post here to help out if anybody else has this problem.

I have a linux kernel module that I build on x86 and on a bunch of raspberry pis running raspian.

the build works fine on x64 ubuntu and it works fine when I run make from the command line on the raspberry pis.

But I have a build script to automate all the things that have to build and only in that case was it failing on the raspians.

the error I was getting was:

```<code>make[1]: Entering directory '/usr/src/linux-headers-4.19.75-v7+' Makefile:614: arch/armv7l/Makefile: No such file or directory make[1]:
*** No rule to make target 'arch/armv7l/Makefile'.  Stop. make[1]: Leaving directory '/usr/src/linux-headers-4.19.75-v7+'
</code>```

Looked fine to me, and it worked fine from the command line just not my build script.
See below for the solution.

答:
I have a few raspberry pis that build different architectures so in my build script I had added

export ARCH=uname -m

and I'd append that to the end of the build result filename.

It turns out that something about the kernel module build where make forks make -C again uses the ARCH environment variable, which my script was changing unexpectedly.

I was confused by the message "*** No rule to make target 'arch/armv7l/Makefile'" because that looks legit, but apparently that was being derived from the incorrect ARCH environment variable.

I change the name of the ARCH variable in the script and it all started working again.

Hope this helps somebody.

Body:
I ran into this problem and figured it out but it took me a while because it wasn't obvious, so I thought I'd post here to help out if anybody else has this problem.

I have a linux kernel module that I build on x86 and on a bunch of raspberry pis running raspian.

the build works fine on x64 ubuntu and it works fine when I run make from the command line on the raspberry pis.

But I have a build script to automate all the things that have to build and only in that case was it failing on the raspians.

the error I was getting was:

make[1]: Entering directory '/usr/src/linux-headers-4.19.75-v7+' Makefile:614: arch/armv7l/Makefile: No such file or directory make[1]:
*** No rule to make target 'arch/armv7l/Makefile'.  Stop. make[1]: Leaving directory '/usr/src/linux-headers-4.19.75-v7+'

Looked fine to me, and it worked fine from the command line just not my build script.
See below for the solution.


问:
Optimize row access and transformation in pyspark
I have a large dataset(5GB) in the form of jason in S3 bucket.
I need to transform the schema of the data, and write back the transformed data to S3 using an ETL script.

So I use a crawler to detect the schema and load the data in pyspark dataframe, and change the schema. Now I iterate over every row in the dataframe and convert it to dictionary. Remove null columns, and then convert the dictionary to string and write back to S3. Following is the code:

```<code>#df is the pyspark dataframe
columns = df.columns
print(columns)
s3 = boto3.resource('s3')
cnt = 1

for row in df.rdd.toLocalIterator():
    data = row.asDict(True)

    for col_name in columns:
        if data[col_name] is None:
            del data[col_name]

    content = json.dumps(data)
    object = s3.Object('write-test-transaction-transformed', str(cnt)).put(Body=content)
    cnt = cnt+1
print(cnt)
</code>```

I have used toLocalIterator.
Is the execution of above code performes serially? if yes then how to optimize it? Is there any better approach for execution of above logic?

答:
I'll follow the below approach(written in scala, but can be implemented in python with minimal change)-

Find the dataset count and named it as totalCount

val totalcount = inputDF.count()
```

<ol start="2">
<li><p>Find the <code>count(col)</code> for all the dataframe columns and get the map of fields to their count</p>

<ul>
<li>Here for all columns of input dataframe, the count is getting computed</li>
<li>Please note that <code>count(anycol)</code> returns the number of rows for which the supplied column are all non-null. For example -  if a column has 10 row value and if say 5 values are <code>null</code> then the count(column) becomes 5</li>
<li>Fetch the first row as <code>Map[colName, count(colName)]</code> referred as <code>fieldToCount</code></li>
</ul></li>
</ol>

<pre class="lang-scala prettyprint-override"><code>val cols = inputDF.columns.map { inputCol =>
      functions.count(col(inputCol)).as(inputCol)
    }
// Returns the number of rows for which the supplied column are all non-null.
    // count(null) returns 0
    val row = dataset.select(cols: _*).head()
    val fieldToCount = row.getValuesMap[Long]($(inputCols))
</code>```

Get the columns to be removed

Use the Map created in step#2 here and mark the column having count less than the totalCount as the column to be removed

select all the columns which has count == totalCount from the input dataframe and save the processed output Dataframe anywhere in any format as per requirement.

Please note that, this approach will remove all the column having at least one null value

val fieldToBool = fieldToCount.mapValues(_ < totalcount)
val processedDF = inputDF.select(fieldToBool.filterNot(_._2).map(_.1) :_*)
// save this processedDF anywhere in any format as per requirement
```

I believe this approach will perform well than the approach you have currently

Body:
I have a large dataset(5GB) in the form of jason in S3 bucket.
I need to transform the schema of the data, and write back the transformed data to S3 using an ETL script.

So I use a crawler to detect the schema and load the data in pyspark dataframe, and change the schema. Now I iterate over every row in the dataframe and convert it to dictionary. Remove null columns, and then convert the dictionary to string and write back to S3. Following is the code:

#df is the pyspark dataframe
columns = df.columns
print(columns)
s3 = boto3.resource('s3')
cnt = 1

for row in df.rdd.toLocalIterator():
    data = row.asDict(True)

    for col_name in columns:
        if data[col_name] is None:
            del data[col_name]

    content = json.dumps(data)
    object = s3.Object('write-test-transaction-transformed', str(cnt)).put(Body=content)
    cnt = cnt+1
print(cnt)

I have used toLocalIterator.
Is the execution of above code performes serially? if yes then how to optimize it? Is there any better approach for execution of above logic?

Body:
I'll follow the below approach(written in scala, but can be implemented in python with minimal change)-

Find the dataset count and named it as totalCount

val totalcount = inputDF.count()

Find the count(col) for all the dataframe columns and get the map of fields to their count

Here for all columns of input dataframe, the count is getting computed

Please note that count(anycol) returns the number of rows for which the supplied column are all non-null. For example -  if a column has 10 row value and if say 5 values are null then the count(column) becomes 5

Fetch the first row as Map[colName, count(colName)] referred as fieldToCount

val cols = inputDF.columns.map { inputCol =>
      functions.count(col(inputCol)).as(inputCol)
    }
// Returns the number of rows for which the supplied column are all non-null.
    // count(null) returns 0
    val row = dataset.select(cols: _*).head()
    val fieldToCount = row.getValuesMap[Long]($(inputCols))

Get the columns to be removed

Use the Map created in step#2 here and mark the column having count less than the totalCount as the column to be removed

select all the columns which has count == totalCount from the input dataframe and save the processed output Dataframe anywhere in any format as per requirement.

Please note that, this approach will remove all the column having at least one null value

val fieldToBool = fieldToCount.mapValues(_ < totalcount)
val processedDF = inputDF.select(fieldToBool.filterNot(_._2).map(_.1) :_*)
// save this processedDF anywhere in any format as per requirement

I believe this approach will perform well than the approach you have currently