问:
Logging in .NET Core without DI?
It seems that Microsoft are really trying to shove DI down your throat with .NET Core, and I'm not sure why, but frankly my console app is small and simple and I just don't want to build a whole DI container just to do some simple logging.  How can I do logging in .NET Core without using DI?  Everything I've read assumed you're going to use .NET Core's built-in logging architecture which obviously requires DI, but there must be a way to just do it without DI using a static variable on the class?</p>

答:
Complete example using .NET Core 6 and NLog 4.7.

Run dotnet new console

Run dotnet add package NLog

Create a new text file named NLog.config1.

```<code><?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="logfile" xsi:type="File" fileName="file.txt" />
        <target name="logconsole" xsi:type="Console" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="logconsole" />
        <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
</nlog>
</code>```

Add the NLog.config file to your project file.

```<code><Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <None Include="NLog.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="NLog" Version="4.7.13" />
  </ItemGroup>
</Project>
</code>```

Edit the Program.cs file as follows:

```<code>var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Info("Program started.");
logger.Info("Program completed.");
</code>```

Run dotnet run.

Expected Output

```<code>> dotnet run
2022-02-08 17:23:37.0430|INFO|Program|Program started.
2022-02-08 17:23:37.0924|INFO|Program|Program completed.
</code>```

1https://github.com/NLog/NLog/wiki/Tutorial#configure-nlog-targets-for-output

Title: Logging in .NET Core without DI?

Body:
Complete example using .NET Core 6 and NLog 4.7.

Run dotnet new console

Run dotnet add package NLog

Create a new text file named NLog.config1.

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="logfile" xsi:type="File" fileName="file.txt" />
        <target name="logconsole" xsi:type="Console" />
    </targets>

    <rules>
        <logger name="*" minlevel="Info" writeTo="logconsole" />
        <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
</nlog>

Add the NLog.config file to your project file.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <None Include="NLog.config">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="NLog" Version="4.7.13" />
  </ItemGroup>
</Project>

Edit the Program.cs file as follows:

var logger = NLog.LogManager.GetCurrentClassLogger();
logger.Info("Program started.");
logger.Info("Program completed.");

Run dotnet run.

Expected Output

> dotnet run
2022-02-08 17:23:37.0430|INFO|Program|Program started.
2022-02-08 17:23:37.0924|INFO|Program|Program completed.

1https://github.com/NLog/NLog/wiki/Tutorial#configure-nlog-targets-for-output


来源: stackexchange

问:
I am trying to pass parameters in cassandra query but I am getting error using python
```<code> user_input== "b":
       id = input("Enter id of  your book")
            idnum=int(id)
            column_name = input("Enter column name")
            delete= "delete %(column)s from books where book_id=%(i_d)s"
            session.execute(delete,{'column':column_name,'i_d':id})
</code>```

I am getting following error while executing this code

Traceback (most recent call last):

File "e:/workspace/library_mangement_application/main.py", line 40, in

delete_data()

File "e:/workspace/library_mangement_application/main.py", line 35, in delete_data

session.execute(delete,{'column':column_name,'i_d':id})

File "cassandra\cluster.py", line 2618, in cassandra.cluster.Session.execute

File "cassandra\cluster.py", line 4894, in cassandra.cluster.ResponseFuture.result

cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:7 mismatched input 'book_info' expecting K_FROM (delete ['book_inf]...)">

答:
So Python string formatting isn't a good way to inject variables in CQL.  That being said, it's not impossible to do with the column name.  So you could do something like this instead:

```<code>deleteCQL= "delete %s from books where book_id=?" % column_name
</code>```

Then create a prepared statement based on deleteCQL, and then bind idnum at query execution time.

```<code>pStatement = session.prepare(deleteCQL)
session.execute(pStatement,[idnum])
</code>```

This approach also helps with escaping any odd characters or punctuation inside the bind variables.

ContentLicense: CC BY-SA 4.0

Body:
 user_input== "b":
       id = input("Enter id of  your book")
            idnum=int(id)
            column_name = input("Enter column name")
            delete= "delete %(column)s from books where book_id=%(i_d)s"
            session.execute(delete,{'column':column_name,'i_d':id})

I am getting following error while executing this code

Traceback (most recent call last):

File "e:/workspace/library_mangement_application/main.py", line 40, in

delete_data()

File "e:/workspace/library_mangement_application/main.py", line 35, in delete_data

session.execute(delete,{'column':column_name,'i_d':id})

File "cassandra\cluster.py", line 2618, in cassandra.cluster.Session.execute

File "cassandra\cluster.py", line 4894, in cassandra.cluster.ResponseFuture.result

cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:7 mismatched input 'book_info' expecting K_FROM (delete ['book_inf]...)">

Body:
So Python string formatting isn't a good way to inject variables in CQL.  That being said, it's not impossible to do with the column name.  So you could do something like this instead:

deleteCQL= "delete %s from books where book_id=?" % column_name

Then create a prepared statement based on deleteCQL, and then bind idnum at query execution time.

pStatement = session.prepare(deleteCQL)
session.execute(pStatement,[idnum])

This approach also helps with escaping any odd characters or punctuation inside the bind variables.


问:
What's the difference between Curless VS Moller algortihms for ray tracing of triangles?
Moller is a universal and fastest algorithm used for ray tracing triangles.
It based on barycentrics coordinates.
Even if Weber(2016) can be better than Moller.

What's the difference with Curless algorithm and why is-it always better?

Curless : https://courses.cs.washington.edu/courses/csep557/10au/lectures/triangle_intersection.pdf
Moller : https://www.tandfonline.com/doi/abs/10.1080/10867651.1997.10487468

Thank you

答:
Curless needs to

compute the normal vector

do a triangle inside outside test (3 edge equation test)

compute barycentric coordiantes

Moeler does in one go compute barycentric coordiantes - boom! Less calculations.

Neverthless, checkout Watertight Ray/Triangle Intersection.


问:
Javascript bookmarklet go to URL and execute
I have a javascript like this, used i a bookmarklet:

```<code>window.location="URL"
document.getElementById('username-id').value = 'User'
document.getElementById('pwd-id').value = 'pass'
doLogin();
</code>```

The problem is that javascript stops as soon as it hits the URL.
How to make it go to a page and execute a script?

Any help would be greatly appreciated.

答:
Unfortunately your bookmarklet will not work. Change of window.location results loading of the new page - you cannot execute any Javascript on that page without having the document present first.

The desired action can be achieved by browser extensions, e.g. Greasemonkey script, which execute specified Javascript on the page upon page load.

ContentLicense: CC BY-SA 3.0

Body:
I have a javascript like this, used i a bookmarklet:

window.location="URL"
document.getElementById('username-id').value = 'User'
document.getElementById('pwd-id').value = 'pass'
doLogin();

The problem is that javascript stops as soon as it hits the URL.
How to make it go to a page and execute a script?

Any help would be greatly appreciated.


问:
Browser not storing session cookie from React XHR request from express-sessions ** updated config
I am using a React frontend to log into a nodejs server running express-session. Frontend is running on localhost:3000, server is on localhost:5000.

Everything is working properly using postman from localhost (session cookie is sent from server when user is properly authenticated and received/stored by postman. Subsequent postman api request to different path on server uses the session cookie and correctly retrieves the data it should based on the session contents). I can also is login using the browser directly to the server (http://localhost:5000/api/authenticate). The server generates the session, sends the cookie to the browser and it stores the cookie locally.

What doesn't work is when I make the api request from within the React app. The server is returning the session cookie but the browser is not storing it. After researching this for the last few days (there are a lot of questions on this general subject), it seems to be an issue with cross site request but I can't seem to find the right set of app and server settings to get it working properly. The cookie is being sent by the server but the browser won't store it when the request from the app.

*** after some additional troubleshooting and research, I've made some updates. My initial XHR request requires a pre-flight and the request and response headers appear to be correct now but still no cookie being stored in browser. More details below the setup ****

Server Setup

```<code>var corsOptions = {
  origin: 'http://localhost:3000',
  credentials: true
};

app.options('*', cors(corsOptions)) // for pre-flight

app.use(cors(corsOptions));

app.use(session({
  genid: (req) => {
    console.log('Inside the session middleware');
    console.log(req.sessionID);
    return uuidv4();
  },
  store: new FileStore(),
  secret: 'abc987',
  resave: false,
  saveUninitialized: true,
  cookie: { httpOnly: false, sameSite: 'Lax', hostOnly: false }
}));

app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, withCredentials, credentials');
  next();
});

app.post('/api/authenticate', function(req, res) {

  const usernameLower = req.body.username.toLowerCase();
  const passwordHash = md5(req.body.password);

  connection.query('select USERID from USERS where LOWER(USERNAME)=? && PASSWORD=? ', [usernameLower, passwordHash], function (error, results, fields) {
    if (error) {
      console.log(error);
      req.session.destroy();
      res.status(500)
        .json({
          error: 'Internal error please try again'
        });

    } else if (results[0]) {
          const userId = results[0].USERID;

          // setup session data
          mySession = req.session;
          mySession.user = {};
          mySession.user.userId = userId;

          res.json(mySession.user);

    } else {
      console.log('auth failed');
      req.session.destroy();
      res.status(401)
        .json({
          error: 'Incorrect email or password'
        });
    }
  });
});
</code>```

Client setup -- the request is triggered by clicking a submit button in a form

```<code>  handleSubmit(event) {
    event.preventDefault();
    axios.defaults.withCreditials = true;
    axios.defaults.credentials = 'include';

    axios({
      credentials: 'include',
      method: 'post',
      url: 'http://localhost:5000/api/authenticate/',
      headers: {'Content-Type': 'application/json' },
      data: {
          username: this.state.username,
          password: this.state.password
        }
      })
      .then((response) => {
        if (response.status === 200) {
          this.props.setLoggedIn(true);
          console.log('userId: '+response.data.userId);
        } else {
          console.log("login error");
        }
     })
      .catch(error => console.log(error))
  }
</code>```

Below is the response cookie sent to the browser but the browser is not storing it.

{"connect.sid":{"path":"/","samesite":"Lax","value":"s:447935ac-fc08-47c6-9b66-4fa30b355021.Yo5H3XVz3Ux3GjTPVhy8i2ZPJm2RM2RzUnznxU9wBvo"}}

Request headers from XHR request (pre-flight):

```<code>OPTIONS /api/authenticate/ HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:3000/
Origin: http://localhost:3000
DNT: 1
Connection: keep-alive
</code>```

Pre-flight server response headers

```<code>HTTP/1.1 204 No Content
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: content-type
Content-Length: 0
Date: Fri, 10 Jul 2020 21:35:05 GMT
Connection: keep-alive
</code>```

POST request header

```<code>POST /api/authenticate/ HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Content-Length: 45
Origin: http://localhost:3000
DNT: 1
Connection: keep-alive
Referer: http://localhost:3000/
</code>```

Server response headers

```<code>HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Content-Type: application/json; charset=utf-8
Content-Length: 95
ETag: W/"5f-Iu5VYnDYPKfn7WPrRi2d2Q168ds"
Set-Cookie: connect.sid=s%3A447935ac-fc08-47c6-9b66-4fa30b355021.Yo5H3XVz3Ux3GjTPVhy8i2ZPJm2RM2RzUnznxU9wBvo; Path=/; SameSite=Lax
Date: Fri, 10 Jul 2020 21:35:05 GMT
Connection: keep-alive
</code>```

I used the "Will it CORS" tool at https://httptoolkit.tech/will-it-cors/ and my request/response headers all seem to be correct but still no cookie stored.

Pre-flight request contains the correct origin
Pre-flight response contains the correct allow-origin and allow-credentials
POST request contains the correct origin and allow-credentials
POST response contains the correct

Appreciate any help to unravel this....

答:
I solved my issues and wanted to post the solution in case others come across this.

To recap, the backend server is nodejs using express. The following setup allows the front-end to accept the cookies which were created on the nodejs server.

```<code>app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "https://frontendserverdomain.com:3000"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", true); // allows cookie to be sent
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, HEAD, DELETE"); // you must specify the methods used with credentials. "*" will not work.
    next();
});
</code>```

The front-end app is based on React and uses axios to make http request. It is hosted at "https://frontendserverdomain.com:3000" which is added to the "Access-Control-Allow-Origin" header in the nodejs setup (see above).

On the front-end, Axios needs the withCredentials setting applied.

```<code>axios.defaults.withCredentials = true;

</code>```

With these settings, your app will be able to exchange cookies with the back-end server.

One gotcha for me getting CORS working was to make sure the front-end host is properly added to the back-end servers header "Access-Control-Allow-Origin". This includes the port number if it's specified in your URL when accessing the front-end.

Inn terms of cookie exchange, the "Access-Control-Allow-Credentials" and "Access-Control-Allow-Methods" headers must be set correctly as shown above. Using a wildcard on "Access-Control-Allow-Methods" will not work.

Body:
I am using a React frontend to log into a nodejs server running express-session. Frontend is running on localhost:3000, server is on localhost:5000.

Everything is working properly using postman from localhost (session cookie is sent from server when user is properly authenticated and received/stored by postman. Subsequent postman api request to different path on server uses the session cookie and correctly retrieves the data it should based on the session contents). I can also is login using the browser directly to the server (http://localhost:5000/api/authenticate). The server generates the session, sends the cookie to the browser and it stores the cookie locally.

What doesn't work is when I make the api request from within the React app. The server is returning the session cookie but the browser is not storing it. After researching this for the last few days (there are a lot of questions on this general subject), it seems to be an issue with cross site request but I can't seem to find the right set of app and server settings to get it working properly. The cookie is being sent by the server but the browser won't store it when the request from the app.

*** after some additional troubleshooting and research, I've made some updates. My initial XHR request requires a pre-flight and the request and response headers appear to be correct now but still no cookie being stored in browser. More details below the setup ****

Server Setup

var corsOptions = {
  origin: 'http://localhost:3000',
  credentials: true
};

app.options('*', cors(corsOptions)) // for pre-flight

app.use(cors(corsOptions));

app.use(session({
  genid: (req) => {
    console.log('Inside the session middleware');
    console.log(req.sessionID);
    return uuidv4();
  },
  store: new FileStore(),
  secret: 'abc987',
  resave: false,
  saveUninitialized: true,
  cookie: { httpOnly: false, sameSite: 'Lax', hostOnly: false }
}));

app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, withCredentials, credentials');
  next();
});

app.post('/api/authenticate', function(req, res) {

  const usernameLower = req.body.username.toLowerCase();
  const passwordHash = md5(req.body.password);

  connection.query('select USERID from USERS where LOWER(USERNAME)=? && PASSWORD=? ', [usernameLower, passwordHash], function (error, results, fields) {
    if (error) {
      console.log(error);
      req.session.destroy();
      res.status(500)
        .json({
          error: 'Internal error please try again'
        });

    } else if (results[0]) {
          const userId = results[0].USERID;

          // setup session data
          mySession = req.session;
          mySession.user = {};
          mySession.user.userId = userId;

          res.json(mySession.user);

    } else {
      console.log('auth failed');
      req.session.destroy();
      res.status(401)
        .json({
          error: 'Incorrect email or password'
        });
    }
  });
});

Client setup -- the request is triggered by clicking a submit button in a form

  handleSubmit(event) {
    event.preventDefault();
    axios.defaults.withCreditials = true;
    axios.defaults.credentials = 'include';

    axios({
      credentials: 'include',
      method: 'post',
      url: 'http://localhost:5000/api/authenticate/',
      headers: {'Content-Type': 'application/json' },
      data: {
          username: this.state.username,
          password: this.state.password
        }
      })
      .then((response) => {
        if (response.status === 200) {
          this.props.setLoggedIn(true);
          console.log('userId: '+response.data.userId);
        } else {
          console.log("login error");
        }
     })
      .catch(error => console.log(error))
  }

Below is the response cookie sent to the browser but the browser is not storing it.

{"connect.sid":{"path":"/","samesite":"Lax","value":"s:447935ac-fc08-47c6-9b66-4fa30b355021.Yo5H3XVz3Ux3GjTPVhy8i2ZPJm2RM2RzUnznxU9wBvo"}}

Request headers from XHR request (pre-flight):

OPTIONS /api/authenticate/ HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:3000/
Origin: http://localhost:3000
DNT: 1
Connection: keep-alive

Pre-flight server response headers

HTTP/1.1 204 No Content
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: content-type
Content-Length: 0
Date: Fri, 10 Jul 2020 21:35:05 GMT
Connection: keep-alive

POST request header

POST /api/authenticate/ HTTP/1.1
Host: localhost:5000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Content-Length: 45
Origin: http://localhost:3000
DNT: 1
Connection: keep-alive
Referer: http://localhost:3000/

Server response headers

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Content-Type: application/json; charset=utf-8
Content-Length: 95
ETag: W/"5f-Iu5VYnDYPKfn7WPrRi2d2Q168ds"
Set-Cookie: connect.sid=s%3A447935ac-fc08-47c6-9b66-4fa30b355021.Yo5H3XVz3Ux3GjTPVhy8i2ZPJm2RM2RzUnznxU9wBvo; Path=/; SameSite=Lax
Date: Fri, 10 Jul 2020 21:35:05 GMT
Connection: keep-alive

I used the "Will it CORS" tool at https://httptoolkit.tech/will-it-cors/ and my request/response headers all seem to be correct but still no cookie stored.

Pre-flight request contains the correct origin
Pre-flight response contains the correct allow-origin and allow-credentials
POST request contains the correct origin and allow-credentials
POST response contains the correct

Appreciate any help to unravel this....

Body:
I solved my issues and wanted to post the solution in case others come across this.

To recap, the backend server is nodejs using express. The following setup allows the front-end to accept the cookies which were created on the nodejs server.

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "https://frontendserverdomain.com:3000"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Credentials", true); // allows cookie to be sent
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, HEAD, DELETE"); // you must specify the methods used with credentials. "*" will not work.
    next();
});

The front-end app is based on React and uses axios to make http request. It is hosted at "https://frontendserverdomain.com:3000" which is added to the "Access-Control-Allow-Origin" header in the nodejs setup (see above).

On the front-end, Axios needs the withCredentials setting applied.

axios.defaults.withCredentials = true;

With these settings, your app will be able to exchange cookies with the back-end server.

One gotcha for me getting CORS working was to make sure the front-end host is properly added to the back-end servers header "Access-Control-Allow-Origin". This includes the port number if it's specified in your URL when accessing the front-end.

Inn terms of cookie exchange, the "Access-Control-Allow-Credentials" and "Access-Control-Allow-Methods" headers must be set correctly as shown above. Using a wildcard on "Access-Control-Allow-Methods" will not work.


问:
how to list col1 with the multiple values in col2
I need to to know

are there multiple Product-ID for the same barcode number

are there multiple barcodes number for the same Product-ID

example of the dataset:

```<code>data = {'Proudct':['SLL', 'MNO', 'Drin', 'JAJ'],
        'Product-ID':[20, 20, 19, 18]
         'barcode':['3633', '7676', '2313','3311'}
 df = pd.DataFrame(data) ```

I need the output to be like:

Name   ID   Code
SLL    20    3633
MNO    20    7676
```

答:
Use groupby + transform('count'):

```<code>filtered = df[df.groupby('Product-ID')['barcode'].transform('count') > 1]
</code>```

Output:

```<code>>>> filtered
  Proudct  Product-ID barcode
0     SLL          20    3633
1     MNO          20    7676
</code>```

Body:
I need to to know

are there multiple Product-ID for the same barcode number

are there multiple barcodes number for the same Product-ID

example of the dataset:

data = {'Proudct':['SLL', 'MNO', 'Drin', 'JAJ'],
        'Product-ID':[20, 20, 19, 18]
         'barcode':['3633', '7676', '2313','3311'}
 df = pd.DataFrame(data) ```

I need the output to be like:

Name   ID   Code
SLL    20    3633
MNO    20    7676

Body:
Use groupby + transform('count'):

filtered = df[df.groupby('Product-ID')['barcode'].transform('count') > 1]

Output:

>>> filtered
  Proudct  Product-ID barcode
0     SLL          20    3633
1     MNO          20    7676


问:
read specific files names in adf pipeline
I have got requirement saying, blob storage has multiple files with names file_1.csv,file_2.csv,file_3.csv,file_4.csv,file_5.csv,file_6.csv,file_7.csv. From these i have to read only filenames from 5 to 7.

how we can achieve this in ADF/Synapse pipeline.

答:
You can always do what @NiharikaMoola-MT suggested . But since you already know the range of the files ( 5-7) , I suggest

Declare two paramter as an upper and lower range

Create a Foreach loop and pass the parameter and to create a range[lowerlimit,upperlimit]

Create a paramterized dataset for source .

Use the fileNumber from the FE loop to create a dynamic expression like

@concat('file',item(),'.csv')


问:
Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:
I added Google Play services as a dependency in my current project.
If I save the project on the C: drive,
I get the following error while syncing up the project:

```<code>Error: Execution failed for task ':app:mergeDebugResources'.
       > Error: Failed to run command:
       C:\Program Files (x86)\Android\android-studio\sdk\build-tools\android-4.4.2\aapt.exe s -i C:\Users\ashokp\Desktop\Studio\AndroidV2SDK_AndroidStudioFormat\Google Play
       Services\SampleApplication\AndroidV2SDKSampleApp_GooglePlayServices\app\build\exploded-aar\com.google.android.gms\play-services\4.3.23\res\drawable-hdpi\common_signin_btn_text_focus_light.9.png -o
       C:\Users\ashokp\Desktop\Studio\AndroidV2SDK_AndroidStudioFormat\Google Play
       Services\SampleApplication\AndroidV2SDKSampleApp_GooglePlayServices\app\build\res\all\debug\drawable-hdpi\common_signin_btn_text_focus_light.9.png
       Error Code:
       42
</code>```

This only happens if the project is saved on the C: drive.
If I save it to some other drive, it works perfectly.

Does anyone else face this issue?
What causes this?
How can I fix/circumvent this?

答: I my case, I had duplicated properties in the xml file. The  'android:layout_height' was in my layout tag and also in one of his child.</p>

Body:
I added Google Play services as a dependency in my current project.
If I save the project on the C: drive,
I get the following error while syncing up the project:

Error: Execution failed for task ':app:mergeDebugResources'.
       > Error: Failed to run command:
       C:\Program Files (x86)\Android\android-studio\sdk\build-tools\android-4.4.2\aapt.exe s -i C:\Users\ashokp\Desktop\Studio\AndroidV2SDK_AndroidStudioFormat\Google Play
       Services\SampleApplication\AndroidV2SDKSampleApp_GooglePlayServices\app\build\exploded-aar\com.google.android.gms\play-services\4.3.23\res\drawable-hdpi\common_signin_btn_text_focus_light.9.png -o
       C:\Users\ashokp\Desktop\Studio\AndroidV2SDK_AndroidStudioFormat\Google Play
       Services\SampleApplication\AndroidV2SDKSampleApp_GooglePlayServices\app\build\res\all\debug\drawable-hdpi\common_signin_btn_text_focus_light.9.png
       Error Code:
       42

This only happens if the project is saved on the C: drive.
If I save it to some other drive, it works perfectly.

Does anyone else face this issue?
What causes this?
How can I fix/circumvent this?


问:
Why are my firebase storage security rules are not enforcing and letting users upload images over the limit?
I have setup my storage security rules to only allow authenticated users to post images that are less than 3mb with the following rule:

```<code>rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
          // Only allow uploads of any image file that's less than 3MB
      allow write: if request.resource.size < 3 * 1024 * 1024
                   && request.resource.contentType.matches('image/.*');
      allow read, write: if request.auth != null;
    }
  }
}
</code>```

However, I just tested from my client and I was able to upload a picture that is 14mb. I have given plenty of time for security rules to set.

How did I bypass this rule?

答:
Please see here:

In the case where multiple allow expressions match a request, the access is allowed if any of the conditions is true

So in your case:

```<code>allow read, write: if request.auth != null;
</code>```

let the user to write files with any size.

I think this is the rule you want:

```<code>allow write: if request.auth != null &&
                request.resource.size < 3 * 1024 * 1024 &&
                request.resource.contentType.matches('image/.*');
allow read: if request.auth != null;
</code>```

Body:
I have setup my storage security rules to only allow authenticated users to post images that are less than 3mb with the following rule:

rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
          // Only allow uploads of any image file that's less than 3MB
      allow write: if request.resource.size < 3 * 1024 * 1024
                   && request.resource.contentType.matches('image/.*');
      allow read, write: if request.auth != null;
    }
  }
}

However, I just tested from my client and I was able to upload a picture that is 14mb. I have given plenty of time for security rules to set.

How did I bypass this rule?

Body:
Please see here:

In the case where multiple allow expressions match a request, the access is allowed if any of the conditions is true

So in your case:

allow read, write: if request.auth != null;

let the user to write files with any size.

I think this is the rule you want:

allow write: if request.auth != null &&
                request.resource.size < 3 * 1024 * 1024 &&
                request.resource.contentType.matches('image/.*');
allow read: if request.auth != null;


问:
Salesforce API - This session is not valid for use with the REST API - Invalid Session ID
For over a year, I have connected to Salesforce using the simple_salesforce package in order to pull some data from various objects and load it to a data lake.

I have used the authentication method using username / password / security token.

```<code>client = Salesforce(
    username="****************",
    password="*************",
    security_token="****************"
    )
</code>```

On the 1st of February came the enforcement of multi factor auth. Starting on that day, I consistently hit the same error over and over.
[{'message': 'This session is not valid for use with the REST API', 'errorCode': 'INVALID_SESSION_ID'}]

After some research, I tried to add a permission set with API Enabled and then API Only user. Result: still the same error, but now I am locked out of the UI.

Has anyone else encountered similar issues and could point me towards the right resources, please? Thanks!

答:
MFA shouldn't matter for API access according to https://help.salesforce.com/s/articleView?id=000352937&type=1 (Ctrl+F "API"), it's probably something else your admin did.

Username, password+token sounds like you're use SOAP login method.

See if you can create a "connected app" in SF to use the OAuth2 login method, more natural for REST API. I wrote a bit about it in https://stackoverflow.com/a/62694002/313628. In the connected app you should be able to allow API access, even full if needed. No idea if Simple has natural place for the keys though, it's bit rubbish if you'll have to craft raw http requests yourself.

Simple's documentation also mentions using JWT to log in (and that requires connected app anyway), basically instead of username + pass you go username + certificate + the fact admin preauthorised this user... You'll be fine until certificate expires.

The text part of https://gist.github.com/booleangate/30d345ecf0617db0ea19c54c7a44d06f can help you with the connected app creation; sample code's probably not needed if you're going with Simple

Body:
For over a year, I have connected to Salesforce using the simple_salesforce package in order to pull some data from various objects and load it to a data lake.

I have used the authentication method using username / password / security token.

client = Salesforce(
    username="****************",
    password="*************",
    security_token="****************"
    )

On the 1st of February came the enforcement of multi factor auth. Starting on that day, I consistently hit the same error over and over.
[{'message': 'This session is not valid for use with the REST API', 'errorCode': 'INVALID_SESSION_ID'}]

After some research, I tried to add a permission set with API Enabled and then API Only user. Result: still the same error, but now I am locked out of the UI.

Has anyone else encountered similar issues and could point me towards the right resources, please? Thanks!


问:
sigrok PulseView download location
I am trying to access https://sigrok.org/wiki/Downloads to download the PulseView GUI, but the website is down for some time now.

Would anyone have a fairly recent version to share please?

Many thanks

答:
Here is a snapshot from Archive.org.

https://web.archive.org/web/20210410075147/https://sigrok.org/download/source/pulseview/

The Windows Installer is here:
https://web.archive.org/web/20201101141813/https://sigrok.org/jenkins/job/sigrok-cross-mingw/buildtype=static,debugtype=release,platform=cross-i686-w64-mingw32/lastSuccessfulBuild/artifact/pulseview-NIGHTLY-32bit-static-release-installer.exe

It appears to be down for me as well, hopefully it will be back soon.

Title: sigrok PulseView download location


问:
GMail composer links don't work on Android
I am using GMail links like

```<code>https://mail.google.com/?view=cm&to=some@email.com
</code>```

or

```<code>https://mail.google.com/mail/?extsrc=mailto&url=mailto%3A%3Fto%3Dsome%40email.com
</code>```

to simplify writing mails with prefilled receiver, subject, and body content. This works fine on desktop, but when I open either type of link in Firefox or Chrome on Android, it will just go to my inbox instead of opening a composer.

Any ideas how I can make this work?

答:
Use mailto instead

```<code>mailto:some@email.com?subject=test&body=test
</code>```

This will allow android and iOS to automatically use intents to offer the user a choice of email clients or selecting the default email client.

It will also use your default mail client on your pc. If gmail is not your default, you can make it so that links will open in your gmail browser

Body:
I am using GMail links like

https://mail.google.com/?view=cm&to=some@email.com

or

https://mail.google.com/mail/?extsrc=mailto&url=mailto%3A%3Fto%3Dsome%40email.com

to simplify writing mails with prefilled receiver, subject, and body content. This works fine on desktop, but when I open either type of link in Firefox or Chrome on Android, it will just go to my inbox instead of opening a composer.

Any ideas how I can make this work?

Body:
Use mailto instead

mailto:some@email.com?subject=test&body=test

This will allow android and iOS to automatically use intents to offer the user a choice of email clients or selecting the default email client.

It will also use your default mail client on your pc. If gmail is not your default, you can make it so that links will open in your gmail browser


问:
How do I fix a problem with Linker in C++ code?
I'm trying to compile this code and it's telling me that the linker command is failing, but I'm not able to work out why. Files provided below:

driver.cpp:

```<code>
#include <iostream>

#include "itemType.h"

#include "pQueueType.cpp"

using namespace std;

int main()
{
cout<<"\n\nbegin main()\n\n";

    pQueueType<itemType> pq;

    pq.create();

    itemType e;

    e="fee";

    pq.put(e);

    e="fie";

    pq.put(e);

    pq.put(e);

    e="foe";

    pq.put(e);

    e="fum";

    pq.put(e);

    e="baz";

    for(int i=0; i<100; i++)

              pq.put(e); // 99

    e="quux";

    for(int i=0; i<100; i++)

              pq.put(e); // 99

    e="fie";

    for(int i=0; i<500; i++)

              pq.put(e); // 499

    e="foo";

    for(int i=0; i<50; i++)

              pq.put(e); //49

    e="bar";

    pq.put(e); // 500

    pq.print();

    /*

    begin main()

    fee     0

    fie     501

    foe     0

    fum     0

    baz     99

    quux    99

    foo     49

    bar     0

    */

    cout<<"\n\n\n\n";

    while(!pq.isEmpty())

              cout<<pq.deQueue()<<"\n***********************\n";

    /*

    fie     501

    ***********************

    quux    99

    ***********************

    baz     99

    ***********************

    foo     49

    ***********************

    fum     0

    ***********************

    foe     0

    ***********************

    fee     0

    ***********************

    bar     0

    ***********************

    end main()

    */

    cout<<"\nend main()\n\n";

return 0;

}

</code>```

itemType.cpp:

```<code>
#include "itemType.h"
#include <iostream>
using namespace std;

itemType::itemType()
{
    payLoad_name="";
    payLoad_weight=0;
} // stubbed constructor

itemType::itemType(const itemType &p)
{
    payLoad_name = p.payLoad_name;
    payLoad_weight = p.payLoad_weight;
} // copy constructor

void itemType::operator =(itemType &i)
{
    if(payLoad_name==i.payLoad_name&&!i.payLoad_weight){
      payLoad_weight++;
    }
    else {
      payLoad_name=i.payLoad_name;
      payLoad_weight=i.payLoad_weight;
    }
}

bool itemType::operator ==(itemType &i)
{
    return payLoad_name==i.payLoad_name;
}

bool itemType::operator >(itemType &i)
{
    if(payLoad_weight==i.payLoad_weight){
      return payLoad_name>i.payLoad_name;
    }
    else {
      return payLoad_weight>i.payLoad_weight;
    }
}

bool itemType::operator <(itemType &i)
{
    if(payLoad_weight==i.payLoad_weight){
      return payLoad_name<i.payLoad_name;
    }
    else {
      return payLoad_weight<i.payLoad_weight;
    }
}

bool itemType::operator !=(itemType &i)
{
    return payLoad_name!=i.payLoad_name;
}

bool itemType::operator >=(itemType &i)
{
    if(payLoad_weight==i.payLoad_weight){
      return payLoad_name>=i.payLoad_name;
    }
    else {
      return payLoad_weight>=i.payLoad_weight;
    }
}

bool itemType::operator <=(itemType &i)
{
    if(payLoad_weight==i.payLoad_weight){
      return payLoad_name<=i.payLoad_name;
    }
    else {
      return payLoad_weight<=i.payLoad_weight;
    }
}

/*
void itemType::operator =(string s) // included only for the programmer's convieniance
{
    if(payLoad_name==i.payLoad_name&&!i.payLoad_weight){
          payLoad_weight++;
    }
    else {
      payLoad_name=i.payLoad_name;
      payLoad_weight=i.payLoad_weight;
    }
}
/*  in driver.cpp, the code:

        itemType i;
        i.payLoad="foo";

    would be perfectly legal.  This operator allows it to be simply:        i="foo";
    It's entirely optional.
*/

ostream &operator << (ostream &out, const itemType &c) // needed to print the list
{
    out << c.payLoad_name;
    return out;
}
</code>```

itemType.h:

```<code>#ifndef ITEMTYPE_FLAG
#define ITEMTYPE_FLAG

#include <string>
using namespace std;

struct itemType
{

  string payLoad_name;       // your option to name it

  int payLoad_weight;           // your option to name it

  itemType(); // constructor

  itemType(const itemType &); // copy constructor

  void operator =(itemType &);
  bool operator ==(itemType &);
  bool operator >(itemType &);
  bool operator <(itemType &);
  bool operator !=(itemType &);
  bool operator <=(itemType &);
  bool operator >=(itemType &);

  void operator =(string);

  friend ostream &operator << (ostream &, const itemType &);

};
#endif
</code>```

pQueueType.cpp:

```<code>#ifndef LISTTYPE_FLAG
#define LISTTYPE_FLAG
#include <iostream>
#include <cstddef>
using namespace std;

template <class T>
class pQueueType
{
    private:
        static const int MAX=10;

        int top, envVar; // discuss the uses of the environmental variable: envVar

        T* myList;

    public:
        pQueueType()
        {
            myList=NULL;
        } // constructor.

        //******************************

        ~pQueueType()
        {
            delete[] myList;
        } // destructor.

        //******************************

        void create()
        {
            myList=new T[MAX];
            top=0;
        }

        //******************************

        bool isRoom()
        {
            return top<MAX;
        }

        //******************************

        bool isEmpty()
        {
            return !top;
        }

        //******************************

        void put(T &e)
        {
            if(isRoom() && !isThere(e))
            myList[top++]=e;
        }

        //******************************

        T deQueue()
        {
            if(top>0)
            {
                T e;
                int i=MAX;
                e=myList[i];
                myList[i]=myList[-top];
                return e;
            }
            else {
                cout<<"Fatal Error; attempt to deQueue empty queue. \n"
                    <<"Check isEmpty()\n";
                cin.get();
                exit(1);
            }
        }

        //******************************

        bool isThere(T &e)
        {
            int j=0;

            while(j<top && myList[j]!=e)
                j++;

            if(j<top)
            {
                envVar=j;
                return true;
            }
            else return false;
        }

        //******************************

        void remove(T &e)
        {
            if(isThere(e))
                myList[envVar]=myList[--top];
        }

        //******************************

        void print() // for diagnostics only
        {
            for(int k=0; k<top; k++)
                cout<<myList[k]<<'\n';
        }
};
#endif
</code>```

makefile:

```<code>CFLAGS = -O
CC = g++

list: driver.o itemType.o pQueueType.o
    $(CC) $(CFLAGS) -o list driver.o itemType.o pQueueType.o

driver.o: driver.cpp
    $(CC) $(CFLAGS) -c driver.cpp

itemType.o: itemType.cpp
    $(CC) $(CFLAGS) -c itemType.cpp

pQueueType.o: pQueueType.cpp
    $(CC) $(CFLAGS) -c pQueueType.cpp

clean:
    rm -f core *.o

</code>```

console:

```<code>PriorityQueue % make
g++ -O -c pQueueType.cpp
g++ -O -o list driver.o itemType.o pQueueType.o
Undefined symbols for architecture x86_64:
  "itemType::operator=(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
      _main in driver.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [list] Error 1
</code>```

I'm a beginner to C++ and I really have no idea what's going on so any help would be greatly appreciated!

答:
The linker error is telling you, albeit quite obtusely, that it cannot find a implementation for:

void itemType::operator =(string s)
```

and, sure enough, if you look at your itemType.cpp file the implementation is commented out!

Body:
I'm trying to compile this code and it's telling me that the linker command is failing, but I'm not able to work out why. Files provided below:

driver.cpp:

#include <iostream>

#include "itemType.h"

#include "pQueueType.cpp"

using namespace std;

int main()
{
cout<<"\n\nbegin main()\n\n";

    pQueueType<itemType> pq;

    pq.create();

    itemType e;

    e="fee";

    pq.put(e);

    e="fie";

    pq.put(e);

    pq.put(e);

    e="foe";

    pq.put(e);

    e="fum";

    pq.put(e);

    e="baz";

    for(int i=0; i<100; i++)

              pq.put(e); // 99

    e="quux";

    for(int i=0; i<100; i++)

              pq.put(e); // 99

    e="fie";

    for(int i=0; i<500; i++)

              pq.put(e); // 499

    e="foo";

    for(int i=0; i<50; i++)

              pq.put(e); //49

    e="bar";

    pq.put(e); // 500

    pq.print();

    /*

    begin main()

    fee     0

    fie     501

    foe     0

    fum     0

    baz     99

    quux    99

    foo     49

    bar     0

    */

    cout<<"\n\n\n\n";

    while(!pq.isEmpty())

              cout<<pq.deQueue()<<"\n***********************\n";

    /*

    fie     501

    ***********************

    quux    99

    ***********************

    baz     99

    ***********************

    foo     49

    ***********************

    fum     0

    ***********************

    foe     0

    ***********************

    fee     0

    ***********************

    bar     0

    ***********************

    end main()

    */

    cout<<"\nend main()\n\n";

return 0;

}

itemType.cpp:

#include "itemType.h"
#include <iostream>
using namespace std;

itemType::itemType()
{
    payLoad_name="";
    payLoad_weight=0;
} // stubbed constructor

itemType::itemType(const itemType &p)
{
    payLoad_name = p.payLoad_name;
    payLoad_weight = p.payLoad_weight;
} // copy constructor

void itemType::operator =(itemType &i)
{
    if(payLoad_name==i.payLoad_name&&!i.payLoad_weight){
      payLoad_weight++;
    }
    else {
      payLoad_name=i.payLoad_name;
      payLoad_weight=i.payLoad_weight;
    }
}

bool itemType::operator ==(itemType &i)
{
    return payLoad_name==i.payLoad_name;
}

bool itemType::operator >(itemType &i)
{
    if(payLoad_weight==i.payLoad_weight){
      return payLoad_name>i.payLoad_name;
    }
    else {
      return payLoad_weight>i.payLoad_weight;
    }
}

bool itemType::operator <(itemType &i)
{
    if(payLoad_weight==i.payLoad_weight){
      return payLoad_name<i.payLoad_name;
    }
    else {
      return payLoad_weight=(itemType &i)
{
    if(payLoad_weight==i.payLoad_weight){
      return payLoad_name>=i.payLoad_name;
    }
    else {
      return payLoad_weight>=i.payLoad_weight;
    }
}

bool itemType::operator <=(itemType &i)
{
    if(payLoad_weight==i.payLoad_weight){
      return payLoad_name<=i.payLoad_name;
    }
    else {
      return payLoad_weight<=i.payLoad_weight;
    }
}

/*
void itemType::operator =(string s) // included only for the programmer's convieniance
{
    if(payLoad_name==i.payLoad_name&&!i.payLoad_weight){
          payLoad_weight++;
    }
    else {
      payLoad_name=i.payLoad_name;
      payLoad_weight=i.payLoad_weight;
    }
}
/*  in driver.cpp, the code:

        itemType i;
        i.payLoad="foo";

    would be perfectly legal.  This operator allows it to be simply:        i="foo";
    It's entirely optional.
*/

ostream &operator << (ostream &out, const itemType &c) // needed to print the list
{
    out << c.payLoad_name;
    return out;
}

itemType.h:

#ifndef ITEMTYPE_FLAG
#define ITEMTYPE_FLAG

#include <string>
using namespace std;

struct itemType
{

  string payLoad_name;       // your option to name it

  int payLoad_weight;           // your option to name it

  itemType(); // constructor

  itemType(const itemType &); // copy constructor

  void operator =(itemType &);
  bool operator ==(itemType &);
  bool operator >(itemType &);
  bool operator <(itemType &);
  bool operator !=(itemType &);
  bool operator <=(itemType &);
  bool operator >=(itemType &);

  void operator =(string);

  friend ostream &operator << (ostream &, const itemType &);

};
#endif

pQueueType.cpp:

#ifndef LISTTYPE_FLAG
#define LISTTYPE_FLAG
#include <iostream>
#include <cstddef>
using namespace std;

template <class T>
class pQueueType
{
    private:
        static const int MAX=10;

        int top, envVar; // discuss the uses of the environmental variable: envVar

        T* myList;

    public:
        pQueueType()
        {
            myList=NULL;
        } // constructor.

        //******************************

        ~pQueueType()
        {
            delete[] myList;
        } // destructor.

        //******************************

        void create()
        {
            myList=new T[MAX];
            top=0;
        }

        //******************************

        bool isRoom()
        {
            return top<MAX;
        }

        //******************************

        bool isEmpty()
        {
            return !top;
        }

        //******************************

        void put(T &e)
        {
            if(isRoom() && !isThere(e))
            myList[top++]=e;
        }

        //******************************

        T deQueue()
        {
            if(top>0)
            {
                T e;
                int i=MAX;
                e=myList[i];
                myList[i]=myList[-top];
                return e;
            }
            else {
                cout<<"Fatal Error; attempt to deQueue empty queue. \n"
                    <<"Check isEmpty()\n";
                cin.get();
                exit(1);
            }
        }

        //******************************

        bool isThere(T &e)
        {
            int j=0;

            while(j<top && myList[j]!=e)
                j++;

            if(j<top)
            {
                envVar=j;
                return true;
            }
            else return false;
        }

        //******************************

        void remove(T &e)
        {
            if(isThere(e))
                myList[envVar]=myList[--top];
        }

        //******************************

        void print() // for diagnostics only
        {
            for(int k=0; k<top; k++)
                cout<<myList[k]<<'\n';
        }
};
#endif

makefile:

CFLAGS = -O
CC = g++

list: driver.o itemType.o pQueueType.o
    $(CC) $(CFLAGS) -o list driver.o itemType.o pQueueType.o

driver.o: driver.cpp
    $(CC) $(CFLAGS) -c driver.cpp

itemType.o: itemType.cpp
    $(CC) $(CFLAGS) -c itemType.cpp

pQueueType.o: pQueueType.cpp
    $(CC) $(CFLAGS) -c pQueueType.cpp

clean:
    rm -f core *.o

console:

PriorityQueue % make
g++ -O -c pQueueType.cpp
g++ -O -o list driver.o itemType.o pQueueType.o
Undefined symbols for architecture x86_64:
  "itemType::operator=(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
      _main in driver.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [list] Error 1

I'm a beginner to C++ and I really have no idea what's going on so any help would be greatly appreciated!

Body:
The linker error is telling you, albeit quite obtusely, that it cannot find a implementation for:

void itemType::operator =(string s)

and, sure enough, if you look at your itemType.cpp file the implementation is commented out!


问:
using exact_extract from exactextractr in R
I am trying to run the example code from the exactextractr package in R

```<code>library(raster)
library(sf)
library(exactextractr)

    brazil <- st_as_sf(getData('GADM', country='BRA', level=2))

    prec <- getData('worldclim', var='prec', res=10)

    brazil$mean_dec_prec <- exact_extract(prec[[12]], brazil, 'mean')

    brazil <- cbind(brazil, exact_extract(prec, brazil, c('min', 'max')))
</code>```

When I get to the third line I keep getting the following error

```<code>    in CPP_stats(x, weights, wkb, default_value, default_weight, coverage_area,  :
  Cannot convert object to a function: [type=NULL; target=CLOSXP, SPECIALSXP, or BUILTINSXP].
</code>```

I've searched around but I can't find anyone else having this error, I've had other people run the code, we are using the same package versions and it works fine for them.

Does anyone have any ideas on the problem or how to fix it?

Thanks,
Dave

答: So it's maybe not the best fix but the only thing that worked was deleting all the packages involved and reinstalling them. For some reason even just updating them wouldn't work, had to completely get rid of them first</p>

Body:
I am trying to run the example code from the exactextractr package in R

library(raster)
library(sf)
library(exactextractr)

    brazil <- st_as_sf(getData('GADM', country='BRA', level=2))

    prec <- getData('worldclim', var='prec', res=10)

    brazil$mean_dec_prec <- exact_extract(prec[[12]], brazil, 'mean')

    brazil <- cbind(brazil, exact_extract(prec, brazil, c('min', 'max')))

When I get to the third line I keep getting the following error

    in CPP_stats(x, weights, wkb, default_value, default_weight, coverage_area,  :
  Cannot convert object to a function: [type=NULL; target=CLOSXP, SPECIALSXP, or BUILTINSXP].

I've searched around but I can't find anyone else having this error, I've had other people run the code, we are using the same package versions and it works fine for them.

Does anyone have any ideas on the problem or how to fix it?

Thanks,
Dave


问:
Removing duplicates from an vector is giving unexpected results

Given a vector of integers, iterate through the vector and check whether there are more than one of the same number. In that case, remove them so that only a single index of the vector contains that number. Here are a few examples:

```<code>vector<int> arr {1,1,1,1}
When arr is printed out the result should be 1.

vector<int> arr {1,2,1,2}
When arr is printed out the result should be 1,2.

vector<int> arr {1,3,2}
When arr is printed out the result should be 1,3,2.
</code>```

I know there are many solutions regarding this, but I want to solve it using my method. The solutions I've looked at use a lot of built-in functions, which I don't want to get too comfortable with as a beginner. I want to practice my problem-solving skills.

This is my code:

```<code>#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> arr {1,1,1,1,2,1,1,1,1,1};

    for (int i {}; i < arr.size(); ++i)
    {
        int counter {};

        for (int j {}; j < arr.size(); ++j)
        {
            if (arr.at(i) == arr.at(j))
            {
                counter++;

                if (counter > 1)
                    arr.erase(arr.begin()+j);
            }
        }
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        cout << value << endl;
    }

    return 0;
}
</code>```

The thing is that it works for the most part, except a few cases which have me confused.

For instance:

```<code>vector<int> arr {1,1,1,1,2,1,1,1,1,1}
When arr is printed out the result is 1,2,1 instead of 1,2.
</code>```

However, in this case:

```<code>vector<int> arr {1,1,1,1,2,1,1,1}
When arr is printed out the result is 1,2.
</code>```

It seems to work in the vast majority of cases, but when a number repeats itself a lot of times in the vector, it seems to not work, and I can't seem to find a reason for this.

I am now asking you to firstly tell me the cause of the problem, and then to give me guidance on how I should tackle this problem using my solution.

答:
As mentioned in the comments, when you erase a found duplicate (at index j), you are potentially modifying the position of the element at index i.

So, after you have called arr.erase(arr.begin() + j), you need to adjust i accordingly, if it was referring to an element that occurs after the removed element.

Here's a "quick fix" for your function:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> arr{ 1,1,1,1,2,1,1,1,1,1 };
    for (size_t i{}; i < arr.size(); ++i) {
        int counter{};
        for (size_t j{}; j < arr.size(); ++j) {
            if (arr.at(i) == arr.at(j)) {
                counter++;
                if (counter > 1) {
                    arr.erase(arr.begin() + j);
                    if (i >= j) --i; // Adjust "i" if it's after the erased element.
                }
            }
        }
    }

    //Prints out the vector arr
    for (auto value : arr) {
        std::cout << value << std::endl;
    }
    return 0;
}
```

As also mentioned in the comments, there are other ways of making the function more efficient; however, you have stated that you want to "practice your own problem-solving skills" (which is highly commendable), so I shall stick to offering a fix for your immediate issue.

Body:
Given a vector of integers, iterate through the vector and check whether there are more than one of the same number. In that case, remove them so that only a single index of the vector contains that number. Here are a few examples:

vector<int> arr {1,1,1,1}
When arr is printed out the result should be 1.

vector<int> arr {1,2,1,2}
When arr is printed out the result should be 1,2.

vector<int> arr {1,3,2}
When arr is printed out the result should be 1,3,2.

I know there are many solutions regarding this, but I want to solve it using my method. The solutions I've looked at use a lot of built-in functions, which I don't want to get too comfortable with as a beginner. I want to practice my problem-solving skills.

This is my code:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> arr {1,1,1,1,2,1,1,1,1,1};

    for (int i {}; i < arr.size(); ++i)
    {
        int counter {};

        for (int j {}; j < arr.size(); ++j)
        {
            if (arr.at(i) == arr.at(j))
            {
                counter++;

                if (counter > 1)
                    arr.erase(arr.begin()+j);
            }
        }
    }

    //Prints out the vector arr

    for (auto value : arr)
    {
        cout << value << endl;
    }

    return 0;
}

The thing is that it works for the most part, except a few cases which have me confused.

For instance:

vector<int> arr {1,1,1,1,2,1,1,1,1,1}
When arr is printed out the result is 1,2,1 instead of 1,2.

However, in this case:

vector<int> arr {1,1,1,1,2,1,1,1}
When arr is printed out the result is 1,2.

It seems to work in the vast majority of cases, but when a number repeats itself a lot of times in the vector, it seems to not work, and I can't seem to find a reason for this.

I am now asking you to firstly tell me the cause of the problem, and then to give me guidance on how I should tackle this problem using my solution.

Body:
As mentioned in the comments, when you erase a found duplicate (at index j), you are potentially modifying the position of the element at index i.

So, after you have called arr.erase(arr.begin() + j), you need to adjust i accordingly, if it was referring to an element that occurs after the removed element.

Here's a "quick fix" for your function:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> arr{ 1,1,1,1,2,1,1,1,1,1 };
    for (size_t i{}; i < arr.size(); ++i) {
        int counter{};
        for (size_t j{}; j < arr.size(); ++j) {
            if (arr.at(i) == arr.at(j)) {
                counter++;
                if (counter > 1) {
                    arr.erase(arr.begin() + j);
                    if (i >= j) --i; // Adjust "i" if it's after the erased element.
                }
            }
        }
    }

    //Prints out the vector arr
    for (auto value : arr) {
        std::cout << value << std::endl;
    }
    return 0;
}

As also mentioned in the comments, there are other ways of making the function more efficient; however, you have stated that you want to "practice your own problem-solving skills" (which is highly commendable), so I shall stick to offering a fix for your immediate issue.


问:
while input is different than (letter1, letter 2, ...) do this. Otherwise do this
```<code>umbrella = input("Which umbrella are you going to use? Select between a,b,c,d,e \n")

if umbrella == "a":
    amount_new_umbrellas = math.ceil(x / 45500)
    print("umbrellas type a: "+ str(amount_new_umbrellas))

elif umbrella == "b":
    amount_new_umbrellas = math.ceil(x / 16700)
    print("umbrellas type b: "+ str(amount_new_umbrellas))

elif umbrella == "c":
    amount_new_umbrellas = math.ceil(x / 27800)
    print("umbrellas type c: "+ str(amount_new_umbrellas))

elif umbrella == "d":
    amount_new_umbrellas = math.ceil(x / 7600)
    print("umbrellas type d: "+ str(amount_new_umbrellas))

elif umbrella == "e":
    amount_new_umbrellas = math.ceil(x / 13800)
    print("umbrellas type e: "+ str(amount_new_umbrellas))

else:
    print("Data Error")
</code>```

I need to improve the code using a WHILE loop, primary, to keep asking the user for an input that has to be (a,b,c,d,e)

答:
```<code>import math
umbrella = input("Which umbrella are you going to use? Select between a,b,c,d,e \n")
x = 100
amount_new_umbrellas = {
    "a" : math.ceil(x / 45500),
    "b" : math.ceil(x / 16700),
    "c" : math.ceil(x / 27800),
    "d" : math.ceil(x / 7600),
    "e" : math.ceil(x / 13800),
}.get(umbrella)
if amount_new_umbrellas:
   print("umbrellas type "+str(umbrella)+": "+ str(amount_new_umbrellas))
else:
  print("Data Error")

</code>```

you can add a loop and it work

```<code>import math
while True:
  umbrella = input("Which umbrella are you going to use? Select between a,b,c,d,e \n")
  x = 100
  amount_new_umbrellas = {
      "a" : math.ceil(x / 45500),
      "b" : math.ceil(x / 16700),
      "c" : math.ceil(x / 27800),
      "d" : math.ceil(x / 7600),
      "e" : math.ceil(x / 13800),
  }.get(umbrella)
  if amount_new_umbrellas:
    print("umbrellas type "+str(umbrella)+": "+ str(amount_new_umbrellas))
  else:
    print("Data Error")
    break

</code>```

Body:
umbrella = input("Which umbrella are you going to use? Select between a,b,c,d,e \n")

if umbrella == "a":
    amount_new_umbrellas = math.ceil(x / 45500)
    print("umbrellas type a: "+ str(amount_new_umbrellas))

elif umbrella == "b":
    amount_new_umbrellas = math.ceil(x / 16700)
    print("umbrellas type b: "+ str(amount_new_umbrellas))

elif umbrella == "c":
    amount_new_umbrellas = math.ceil(x / 27800)
    print("umbrellas type c: "+ str(amount_new_umbrellas))

elif umbrella == "d":
    amount_new_umbrellas = math.ceil(x / 7600)
    print("umbrellas type d: "+ str(amount_new_umbrellas))

elif umbrella == "e":
    amount_new_umbrellas = math.ceil(x / 13800)
    print("umbrellas type e: "+ str(amount_new_umbrellas))

else:
    print("Data Error")

I need to improve the code using a WHILE loop, primary, to keep asking the user for an input that has to be (a,b,c,d,e)

Body:
import math
umbrella = input("Which umbrella are you going to use? Select between a,b,c,d,e \n")
x = 100
amount_new_umbrellas = {
    "a" : math.ceil(x / 45500),
    "b" : math.ceil(x / 16700),
    "c" : math.ceil(x / 27800),
    "d" : math.ceil(x / 7600),
    "e" : math.ceil(x / 13800),
}.get(umbrella)
if amount_new_umbrellas:
   print("umbrellas type "+str(umbrella)+": "+ str(amount_new_umbrellas))
else:
  print("Data Error")

you can add a loop and it work

import math
while True:
  umbrella = input("Which umbrella are you going to use? Select between a,b,c,d,e \n")
  x = 100
  amount_new_umbrellas = {
      "a" : math.ceil(x / 45500),
      "b" : math.ceil(x / 16700),
      "c" : math.ceil(x / 27800),
      "d" : math.ceil(x / 7600),
      "e" : math.ceil(x / 13800),
  }.get(umbrella)
  if amount_new_umbrellas:
    print("umbrellas type "+str(umbrella)+": "+ str(amount_new_umbrellas))
  else:
    print("Data Error")
    break


问:
C# SerialPort Encoding conversion to byte[]
i know I recieve some data in byte format from the serial port (a u-blox GPS device), that should look like this:

```<code>Hex:        0xB5 0x62 0x01 0x21
ISO 8859-1: µ    b    1    !
</code>```

So i read a string s from the command line and print in in a text box and it looks like:

```<code>Tbx:        ?    b       !
</code>```

That seems fine, as the textbox isn't configured to respect the encoding.

When I try to convert the string s to the bytes (which should look like the first Hex-line), I get

```<code>Bytes(d):   63   98   1    33
Bytes(h):   0x3F 0x62 0x1  0x21
</code>```

As you see, the µ char is wrong encoded, somewhere along my way.
Here is the code:

```<code>string s = port.ReadLine();
System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
System.Text.Encoding ascii = port.Encoding;

byte[] bASCII = ascii.GetBytes(s);
byte[] bICO = Encoding.Convert(ascii, iso_8859_1, bASCII);
</code>```

Where do I mess up the µ?

答:
I believe the 0x3F character is actually a question mark.

Try setting the port.Encoding to Encoding.ASCII.  Set this value before calling port.ReadLine();

Otherwise you might have to read raw bytes and look for a \r or \n.

Body:
i know I recieve some data in byte format from the serial port (a u-blox GPS device), that should look like this:

Hex:        0xB5 0x62 0x01 0x21
ISO 8859-1: µ    b    1    !

So i read a string s from the command line and print in in a text box and it looks like:

Tbx:        ?    b       !

That seems fine, as the textbox isn't configured to respect the encoding.

When I try to convert the string s to the bytes (which should look like the first Hex-line), I get

Bytes(d):   63   98   1    33
Bytes(h):   0x3F 0x62 0x1  0x21

As you see, the µ char is wrong encoded, somewhere along my way.
Here is the code:

string s = port.ReadLine();
System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
System.Text.Encoding ascii = port.Encoding;

byte[] bASCII = ascii.GetBytes(s);
byte[] bICO = Encoding.Convert(ascii, iso_8859_1, bASCII);

Where do I mess up the µ?


问:
Python remove shapes from a pdf
In my setup, I have a student submit a pdf, and the teacher can annotate the pdf using the adobe embed api. This really nice since the teacher can create and delete comments.

However, take the example case where a student writes their answers on a paper then scans them to a pdf. They then draw on the pdf with a pdf editor like Microsoft edge. after they submit and the teacher is editing, it is possible for the teacher to delete what the student has drawn because the embed API treats it as a shape. I don't want this to be possible.

My backend is Django, so maybe there is some way for python to open a pdf file and "flatten" the shapes.

Thanks

答: The Embed API has an annotations API, and as part of that, you can delete them (https://developer.adobe.com/document-services/docs/overview/pdf-embed-api/howtos_comments/#deleteannotations-api). You would need to build the UI yourself to provide a way for a user to select an annotation and remote it. The API covers everything (getting, adding, deleting), so it's just up to you to build it out.</p>

Title: Python remove shapes from a pdf


问:
How to return different types based on parameters in a React.useCallback
I want to return an object when I have a certain prop in the parameter of my function, and a string when not.

I can't use functions overloads because it is used in a type that is shared with React components, in React.useCallback.

I tried:

```<code>type FileType = {
    name: string
    content: string
}

// This is a type that I use in many part of my code. I would like the result of onSave to depend on the props it receive
type Props = {
    onSave: <T extends FileType | undefined>(data: {
        id: string
        file: T
    }) => T extends FileType ? FileType : string
}

const isFile = (o: unknown): o is FileType => {
    return o !== undefined
}

// Here you can read the error
const insert: Props['onSave'] = prop => isFile(prop.file) ? prop.file : prop.id)

// Here is how the function is written in my code. But React doesn't exist in this playground
// const insert = React.useCallback<Props['onSave']>(prop => isFile(prop.file) ? prop.file : prop.id, [])

</code>```

the error:

```<code>Type 'string | (T & FileType)' is not assignable to type 'T extends FileType ? FileType : string'.
  Type 'string' is not assignable to type 'T extends FileType ? FileType : string'.
</code>```

Playground Link: Provided

答:
Here is what you can do: playground

Basically, first you need to define the parametric result using generics:

```<code>type FileType = {
    name: string
    content: string
}

type Id = { id: string }

type WithFile = Id & { file: FileType }

type OnSaveResult<T extends WithFile | Id> = T extends WithFile ? FileType : string
</code>```

Now you can define your general onSave function type:

```<code>type Props = {
    onSave: <T extends WithFile | Id = Id>(data: T) => OnSaveResult<T>
}
</code>```

Now, the trick is to cast the result of your function with the parametric result. To avoid hiding some type issues, it can be interesting to manually cast the result of each result returned based on what we know it should look like.

```<code>// Define your function using generics
const onSave = <T extends WithFile | Id>(prop: T) => (hasFile(prop)
    // Might be interesting to manually do the cast here to ensure that each type is valid. Otherwise, prop.file.content, for instance, would not raise an error
    ? prop.file as OnSaveResult<WithFile>
    // Same here, it might be worth manually enforcing the type checking
    : prop.id as OnSaveResult<Id>
// We need to manyally cast to OnSaveResult<T> for the result type to adapt to the generic on input
) as OnSaveResult<T>
</code>```

Your function is now inferring the types correctly based on props

```<code>const resultsToString = onSave({ id: 'test' }) // string
const resultsToFile = onSave({ id: 'test', file: { name: 'test', content: 'test'}}) // FileType
</code>```

In your useCallback, you can use these syntaxes based on the case:

```<code>// Only in the components that might need files, you can use this to declare your function
const insert = React.useCallback<Props['onSave']>(<T extends WithFile | Id>(prop: T) => (hasFile(prop) ? prop.file : prop.id) as OnSaveResult<T>, [])

// In more basic components, you might use a simpler version
const insert2 = React.useCallback<Props['onSave']>(prop => prop.id, [])
</code>```

Body:
I want to return an object when I have a certain prop in the parameter of my function, and a string when not.

I can't use functions overloads because it is used in a type that is shared with React components, in React.useCallback.

I tried:

type FileType = {
    name: string
    content: string
}

// This is a type that I use in many part of my code. I would like the result of onSave to depend on the props it receive
type Props = {
    onSave: <T extends FileType | undefined>(data: {
        id: string
        file: T
    }) => T extends FileType ? FileType : string
}

const isFile = (o: unknown): o is FileType => {
    return o !== undefined
}

// Here you can read the error
const insert: Props['onSave'] = prop => isFile(prop.file) ? prop.file : prop.id)

// Here is how the function is written in my code. But React doesn't exist in this playground
// const insert = React.useCallback<Props['onSave']>(prop => isFile(prop.file) ? prop.file : prop.id, [])

the error:

Type 'string | (T & FileType)' is not assignable to type 'T extends FileType ? FileType : string'.
  Type 'string' is not assignable to type 'T extends FileType ? FileType : string'.

Playground Link: <a href="https://www.typescriptlang.org/play?#code/C4TwDgpgBAYglgGwgFXNAvFA3gKCvqAOwEMBbCALigGdgAnOQgczwIGMB7Q4Cbq2hsxwBfHDgD04qMgAWcalHlRiUUJFUziwKAEkoAV2rRGUUsUIgoYYnW0cAZqcucAJhAB0uqAHcO+hC5QCHAA1tDAMtB0ENT+do5cAMrEAG7hHFBukISBXBrQYHQcYApw2tFsEHBpOGrQAApFJVCYuARQSamUUAA8yFAQAB48OQrwSKjqAD4GORD2jBAuAHwAFC5axFRt7QRwLvz0jCy7BAtIVMis+MIAlC3L0gPDvC5jiChoUAD8sB+T0EOghYohwnEItEU1HGGCgqw4VH0hBChA43kItyoGSUMIBD2w1yg0WA+johA6UAAhOhMEi3AtCEsRGIJFIABIQaJQEB+KBscxEiDEQIRaCcop0MFcSGMIy2KiNYrUADaAHJOmlVQBdFpWJr4+Qw1aFYruc4Qe6-E1gM0fKBUa3ufa3MSSKAcrlKGRo-JQexItjAOB5JTeBjAEaKcmkZwcNyeABC+m0ACUhYHMhwYoRVdohvJtCYIkowAhiCAmEU6ay+dLCxDOdpMGniIH3IYIABhYgIBAAI1bIR6ipKao1EG1a2tBuhH2NTVtSEtetN5vtK5t+wANFBlVqXUA" rel="nofollow noreferrer">Provided

Body:
Here is what you can do: <a href="https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgcmXRnwChSYBPMJOAMWABskAVa2gXjgG9S5+4AOxQgkALjgBnGFGCCA5nwFoIgmEjUTpshaQC+5KjTgBJACZwu3OMDNaZc+XAMV2cAOrAYACwbNLphYAZDxwmEzi9BFsxi5GtADyggDKKABuSMiSAK6MMAA8LHBIAB7qgmaSHl6+EXAAPoEAfAFFpeWV1T5+tAD8UcwxtPY6iq7GAAo4YFVWSvyqqRkShcVlGp2e3XWN5gHmTQAUZigwKBIsAJSWLUlLmUg5eYVN+uQqgtJw3iiSPQGHCASbKCADWgggAHdBJcJBAbFUtrV-BwWrwBHAoEgYNkoII4AkAEYAKyQGAAdGAcDAIPFyT9JAloVMIDRYJRyWgUIxGICADQEcLMfCXN6kAD04rgABEkOFBLRKBBcWEQRhgKo4NlJI44PINEhZGhJKQPl9FulOHBVu0Noiav9dmYjlTWRdrqi4IcGT1Dq6wKKMZK4ABZYDybzwQm0OTqLHSXU0uAgFCCbLcxiUOBmeE+Whcr7eQ20JMaHJYuA+U7FdDeStuYBVNLc2zkgl5qCQxtIAX+8lCpCc1TleCQ5WMCwQ+BQFDduCp4pQHBQeZwfp9gfzqp3S1ZXIFJE9V5BqWpUTfYsCrzJ8ORuDRuBj2B1lNpjNZjSYaBoRNF+vGNAizQUFHFXCQ+1sLcCRSXdHn3fIDglKV3FoBUkAsJNX0od84ALeAkx3DI92eFgWi-KBKz-eN93-Et4RQE4wHw3M-31BUjTgTU5DAbIYFIa5fmg+5iIKUjyGDABNZVcIXQCyVBSiSzcPDdQYlAmMTFjaH9E0zWnOC8kkFgIGSBwFACC0MkOaxbAkfB1GkfBnGuYNtFAvTMQMmAjIgf4uEspBrJsOwCAckgBQHCRrGEUQ7LC-ABQ+Ec4seEg9D0FypR6IZxKlJJMxsfE81w3BIAVNQqireAQFveA0IsAdJAFJVshk-FtRLbxG0reEzDJRgUArFqKMwNUYA1QRTVUL45EkQ14C4IgKQ6gBhDNCXQUF8hZGYAG18AC-AAF0jhtdYKntbZ-CdF1pndG4vR9CI-Wma512mfs6nAj7bAE7cYKIryXgFXajtFJDTHxEBoFoDadTQErwFUDRvOa6SaojeAOvnKRQDAZgKIyKAdVUKbPngWb5oAJgCJaYHJVb1s27bpkkfbDpOw4XrdQIPRaCCzBBsHSCAA" rel="nofollow noreferrer">playground

Basically, first you need to define the parametric result using generics:

type FileType = {
    name: string
    content: string
}

type Id = { id: string }

type WithFile = Id & { file: FileType }

type OnSaveResult<T extends WithFile | Id> = T extends WithFile ? FileType : string

Now you can define your general onSave function type:

type Props = {
    onSave: <T extends WithFile | Id = Id>(data: T) => OnSaveResult<T>
}

Now, the trick is to cast the result of your function with the parametric result. To avoid hiding some type issues, it can be interesting to manually cast the result of each result returned based on what we know it should look like.

// Define your function using generics
const onSave = <T extends WithFile | Id>(prop: T) => (hasFile(prop)
    // Might be interesting to manually do the cast here to ensure that each type is valid. Otherwise, prop.file.content, for instance, would not raise an error
    ? prop.file as OnSaveResult<WithFile>
    // Same here, it might be worth manually enforcing the type checking
    : prop.id as OnSaveResult<Id>
// We need to manyally cast to OnSaveResult<T> for the result type to adapt to the generic on input
) as OnSaveResult<T>

Your function is now inferring the types correctly based on props

const resultsToString = onSave({ id: 'test' }) // string
const resultsToFile = onSave({ id: 'test', file: { name: 'test', content: 'test'}}) // FileType

In your useCallback, you can use these syntaxes based on the case:

// Only in the components that might need files, you can use this to declare your function
const insert = React.useCallback<Props['onSave']>(<T extends WithFile | Id>(prop: T) => (hasFile(prop) ? prop.file : prop.id) as OnSaveResult<T>, [])

// In more basic components, you might use a simpler version
const insert2 = React.useCallback<Props['onSave']>(prop => prop.id, [])


问:
How to remove 'Server' header from .net core 3.1 api response?
How to configure .net core 3.1 application to prevent 'Server' in the response header</p>

答:
In .Net 6 ASP.Net Core</p>
```<code>builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false);
</code>```

Body:
In .Net 6 ASP.Net Core

builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false);


问:
Firebase CLI not deploying any Cloud Functions
I have an Angular project where I am trying to deploy a single firebase function.

This is what my functions directory looks like:

When I deploy these function with the command firebase deploy --only functions the output looks normal and no errors:

```<code>PS C:\Users\project-directory> firebase deploy --only functions

=== Deploying to 'firebase-project-name'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run build

> build
> tsc

+  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
+  functions: required API cloudfunctions.googleapis.com is enabled
+  functions: required API cloudbuild.googleapis.com is enabled
i  functions: cleaning up build files...

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/project-name/overview
</code>```

src/user/index.ts file with the function I am trying to deploy:

```<code>import functions = require('firebase-functions');
import admin = require('firebase-admin');

// import * as functions from "firebase-functions";
// import * as admin from 'firebase-admin';

const FieldValue = require('firebase-admin').firestore.FieldValue;

const db = admin.firestore();

/**
 * Add user to firestore
 */
export const createProfile = async (userRecord: any) => {
    const uid = userRecord.uid;
    const admin = false;
    const email = userRecord.email;
    const photoURL = userRecord.photoUrl || 'enter shortened url for default image';
    const name = userRecord.displayName || 'New User';
    const spouse = userRecord.spouse || 'TBA';
    const forumUserName = userRecord.forumUserName || 'New Username set by admin';
    const address = userRecord.address || 'TBA';
    const suburb = userRecord.suburb || 'TBA';
    const state = userRecord.state || 'QLD';
    const postCode = userRecord.postCode || '2000';
    const homePhone = userRecord.homePhone || '02 1234 5678';
    const mobilePhone = userRecord.mobilePhone || '0400 123 456';
    const memNum = userRecord.memNum || 123;
    const timestamp = FieldValue.serverTimestamp();
    const memType = userRecord.memType || 'Nominated';
    const memStatus = userRecord.memStatus || `Pending`;
    const isStateCoord = userRecord.isStateCoord || false;
    const stateCoordState = userRecord.stateCoordState || 'QLD';
    //const newUserRef = db.doc(`users/${uid}`)

    // Convert any date to timestamp for consistency

    try {
        return await db
            .collection(`users`)
            .doc(userRecord.uid)
            .set({
                uid: uid,
                email: email,
                photoURL: photoURL,
                fullName: name,
                mDOB: timestamp,
                spouse: spouse,
                sDOB: timestamp,
                forumUserName: forumUserName,
                address: address,
                suburb: suburb,
                state: state,
                postCode: postCode,
                homePhone: homePhone,
                mobilePhone: mobilePhone,
                memNum: memNum,
                memType: memType,
                memStatus: memStatus,
                memDueDate: timestamp,
                lastLoginDate: timestamp,
                joined: timestamp,
                updated: timestamp,
                admin: admin,
                isAdmin: admin,
                isStateCoord: isStateCoord,
                stateCoordState: stateCoordState,
            });
    } catch (message) {
        return console.error(message);
    }
};

exports.authOnCreate = functions.auth.user().onCreate(createProfile);
</code>```

src/index.ts file imports the above file:

```<code>import * as user from './user';
export const createProfile = user.createProfile
</code>```

The issue is that I am not seeing the function appear in the Firebase console.

What am I overlooking?

答:
In the original code I posted for you, createProfile was a const not an export.

Out of the box, should work just fine. The only difference I see is you've dropped the code into a user sub directory.

Again no issue and probably ok for readability.

Might be poor practice on my part, but ALL of my functions are in one file. Even when extensions are installed, they go into the same index.js(ts) file. Then if I modify a function I use firebase deploy --only functions:functionName

Body:
I have an Angular project where I am trying to deploy a single firebase function.

This is what my functions directory looks like:

When I deploy these function with the command firebase deploy --only functions the output looks normal and no errors:

PS C:\Users\project-directory> firebase deploy --only functions

=== Deploying to 'firebase-project-name'...

i  deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run build

> build
> tsc

+  functions: Finished running predeploy script.
i  functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i  functions: ensuring required API cloudbuild.googleapis.com is enabled...
+  functions: required API cloudfunctions.googleapis.com is enabled
+  functions: required API cloudbuild.googleapis.com is enabled
i  functions: cleaning up build files...

+  Deploy complete!

Project Console: https://console.firebase.google.com/project/project-name/overview

src/user/index.ts file with the function I am trying to deploy:

import functions = require('firebase-functions');
import admin = require('firebase-admin');

// import * as functions from "firebase-functions";
// import * as admin from 'firebase-admin';

const FieldValue = require('firebase-admin').firestore.FieldValue;

const db = admin.firestore();

/**
 * Add user to firestore
 */
export const createProfile = async (userRecord: any) => {
    const uid = userRecord.uid;
    const admin = false;
    const email = userRecord.email;
    const photoURL = userRecord.photoUrl || 'enter shortened url for default image';
    const name = userRecord.displayName || 'New User';
    const spouse = userRecord.spouse || 'TBA';
    const forumUserName = userRecord.forumUserName || 'New Username set by admin';
    const address = userRecord.address || 'TBA';
    const suburb = userRecord.suburb || 'TBA';
    const state = userRecord.state || 'QLD';
    const postCode = userRecord.postCode || '2000';
    const homePhone = userRecord.homePhone || '02 1234 5678';
    const mobilePhone = userRecord.mobilePhone || '0400 123 456';
    const memNum = userRecord.memNum || 123;
    const timestamp = FieldValue.serverTimestamp();
    const memType = userRecord.memType || 'Nominated';
    const memStatus = userRecord.memStatus || `Pending`;
    const isStateCoord = userRecord.isStateCoord || false;
    const stateCoordState = userRecord.stateCoordState || 'QLD';
    //const newUserRef = db.doc(`users/${uid}`)

    // Convert any date to timestamp for consistency

    try {
        return await db
            .collection(`users`)
            .doc(userRecord.uid)
            .set({
                uid: uid,
                email: email,
                photoURL: photoURL,
                fullName: name,
                mDOB: timestamp,
                spouse: spouse,
                sDOB: timestamp,
                forumUserName: forumUserName,
                address: address,
                suburb: suburb,
                state: state,
                postCode: postCode,
                homePhone: homePhone,
                mobilePhone: mobilePhone,
                memNum: memNum,
                memType: memType,
                memStatus: memStatus,
                memDueDate: timestamp,
                lastLoginDate: timestamp,
                joined: timestamp,
                updated: timestamp,
                admin: admin,
                isAdmin: admin,
                isStateCoord: isStateCoord,
                stateCoordState: stateCoordState,
            });
    } catch (message) {
        return console.error(message);
    }
};

exports.authOnCreate = functions.auth.user().onCreate(createProfile);

src/index.ts file imports the above file:

import * as user from './user';
export const createProfile = user.createProfile

The issue is that I am not seeing the function appear in the Firebase console.

What am I overlooking?


问:
Push Notifications not FULLY working unless tethered to Xcode
This has obviously been asked multiple times but I can't seem to get any of the proposed solutions working.

Push notifs work when tethered to xcode. Untethered, I get the push notification itself  but none of the delegate methods are called which results in not being able to increment badge count.

I also can't get silent notifications working on untethered as well. I use silent notifications to clear a notification with a given condition.

I've tried allowing background mode in plist, changing priorities, having an empty body. I've made sure that the device background refresh is on and that notifs are fully on. I've tried a ton more things that I can't remember off the top of my head. Nothing seems to work. I added a badge increment in every one of the push notif delegate methods and it seems none of them get called.

Here is the .js code snippet for regular notif

message1 = {
  notification: {
    title: "stackOverFlowTitle",
    body: "stackOverFlowBody"
  },
  apns: {
    payload: {
      aps : {
        "content-available": 1,
        "sound": "default",
        "priority" : 10
      },
      data: {
      //     collection: 'TestCollection',
      //     document: change.after.ref.id,
        timePushed: timePushed,
        alertOn: alertOn,
        readNotification: readNotification,
        eventKey: eventKey
      }
    },
    headers: {
      "apns-expiration": "4"
    }
  },
  topic: topic
};```
</div>
</div>
</p>

<p>Here is the .js code snippet for silent notif</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var message2 = {
  notification: {
    body: ""
  },
  apns: {
    payload: {
      aps: {
        "content-available": 1,
        "priority" : 10
      },
      data: {
        alertOn: alertOn,
        eventKey: eventKey
      }
    },
    headers: {
      "apns-expiration": "4"
    }
  },
  topic: topic
};</code>```

Anyone have any potential solutions I haven't mentioned?

答: According to the docs, when non-zero the apns-expiration represents a unix timestamp. By setting it to 4, you're telling APNs to expire the notification at 1970-01-01 00:00:04.

Body:
This has obviously been asked multiple times but I can't seem to get any of the proposed solutions working.

Push notifs work when tethered to xcode. Untethered, I get the push notification itself  but none of the delegate methods are called which results in not being able to increment badge count.

I also can't get silent notifications working on untethered as well. I use silent notifications to clear a notification with a given condition.

I've tried allowing background mode in plist, changing priorities, having an empty body. I've made sure that the device background refresh is on and that notifs are fully on. I've tried a ton more things that I can't remember off the top of my head. Nothing seems to work. I added a badge increment in every one of the push notif delegate methods and it seems none of them get called.

Here is the .js code snippet for regular notif

message1 = {
  notification: {
    title: "stackOverFlowTitle",
    body: "stackOverFlowBody"
  },
  apns: {
    payload: {
      aps : {
        "content-available": 1,
        "sound": "default",
        "priority" : 10
      },
      data: {
      //     collection: 'TestCollection',
      //     document: change.after.ref.id,
        timePushed: timePushed,
        alertOn: alertOn,
        readNotification: readNotification,
        eventKey: eventKey
      }
    },
    headers: {
      "apns-expiration": "4"
    }
  },
  topic: topic
};

Here is the .js code snippet for silent notif

var message2 = {
  notification: {
    body: ""
  },
  apns: {
    payload: {
      aps: {
        "content-available": 1,
        "priority" : 10
      },
      data: {
        alertOn: alertOn,
        eventKey: eventKey
      }
    },
    headers: {
      "apns-expiration": "4"
    }
  },
  topic: topic
};

Anyone have any potential solutions I haven't mentioned?


问:
Getting datetime count range in SQL Server
I try to get the date range between the data changes in SQL Server
my query is

```<code>select count(1) as qty, Info, convert(char,dFError,100) dErr
from TableData
group by Info, convert(char,dFError,100)
order by dErr asc
</code>```

I have this
qty has the number of reques to a server, info are the servers ip and the date it's when a request it's sended to another server.

qty
Info
dErr

1
1.97
Aug 11 2021  9:01AM

1
1.97
Aug 11 2021  9:06AM

88
1.33
Dec 21 2021  2:04PM

1
1.95
Dec 22 2021  9:44PM

9
1.95
Dec 22 2021  9:45PM

1
1.33
Dec 22 2021  9:51PM

19
1.33
Dec 22 2021  9:52PM

3
1.33
Dec 22 2021  9:53PM

6
1.33
Dec 27 2021  7:10PM

17
1.33
Dec 27 2021  7:11PM

15
1.95
Dec 27 2021  7:17PM

8
1.95
Dec 27 2021  7:18PM

and I want this, in Aug 11 at 9:06AM all are going to 1.97, at Dec 21 at 2:04PM all are going to 1.33, that means the date and the info

qty
Info
dErr

2
1.97
Aug 11 2021  9:06AM

88
1.33
Dec 21 2021  2:04PM

10
1.95
Dec 22 2021  9:45PM

46
1.33
Dec 27 2021  7:11PM

23
1.95
Dec 27 2021  7:18PM

in the same day can be the same group of numbers on distinct hour

qty
Info
dErr

1
1.97
Jan 24 2022  9:39AM

1
1.97
Jan 24 2022  9:51AM

1
1.97
Jan 24 2022  9:58AM

4
1.97
Jan 24 2022 10:08AM

1
1.97
Jan 24 2022 10:12AM

8
1.95
Jan 24 2022 10:24AM

2
1.95
Jan 24 2022 10:32AM

10
1.33
Jan 24 2022 10:33AM

1
1.33
Jan 24 2022 11:37AM

8
1.95
Jan 24 2022 11:59AM

1
1.95
Jan 24 2022 12:00PM

2
1.95
Jan 24 2022 12:08PM

and need to be displayed like

qty
Info
dErr

8
1.97
Jan 24 2022  10:12AM

10
1.95
Jan 24 2022 10:32AM

11
1.33
Jan 24 2022 11:37AM

11
1.95
Jan 24 2022 12:08PM

答:
Your expected results don't match the given data - in the first set you have rows for 12/22 with both 1.33 and 1.95, but not included in your expected results.

It seems to me you want to either group by the date - or the date\hour.  Here is an example of both:

```<code>Declare @testTable table (qty int, Info numeric(3,2), dErr datetime);
 Insert Into @testTable (qty, Info, dErr)
 Values ( 1, 1.97, 'Aug 11 2021 9:01AM')
      , ( 1, 1.97, 'Aug 11 2021 9:06AM')
      , (88, 1.33, 'Dec 21 2021 2:04PM')
      , ( 1, 1.95, 'Dec 22 2021 9:44PM')
      , ( 9, 1.95, 'Dec 22 2021 9:45PM')
      , ( 1, 1.33, 'Dec 22 2021 9:51PM')
      , (19, 1.33, 'Dec 22 2021 9:52PM')
      , ( 3, 1.33, 'Dec 22 2021 9:53PM')
      , ( 6, 1.33, 'Dec 27 2021 7:10PM')
      , (17, 1.33, 'Dec 27 2021 7:11PM')
      , (15, 1.95, 'Dec 27 2021 7:17PM')
      , ( 8, 1.95, 'Dec 27 2021 7:18PM')

      , ( 1, 1.97, 'Jan 24 2022 9:39AM')
      , ( 1, 1.97, 'Jan 24 2022 9:51AM')
      , ( 1, 1.97, 'Jan 24 2022 9:58AM')
      , ( 4, 1.97, 'Jan 24 2022 10:08AM')
      , ( 1, 1.97, 'Jan 24 2022 10:12AM')
      , ( 8, 1.95, 'Jan 24 2022 10:24AM')
      , ( 2, 1.95, 'Jan 24 2022 10:32AM')
      , (10, 1.33, 'Jan 24 2022 10:33AM')
      , ( 1, 1.33, 'Jan 24 2022 11:37AM')
      , ( 8, 1.95, 'Jan 24 2022 11:59AM')
      , ( 1, 1.95, 'Jan 24 2022 12:00PM')
      , ( 2, 1.95, 'Jan 24 2022 12:08PM');

 --==== Grouped by date
 Select total_qty = sum(tt.qty)
      , tt.Info
      , latest_date = max(tt.dErr)
   From @testTable tt
  Group By
        tt.Info
      , cast(tt.dErr As date)
  Order By
        cast(tt.dErr As date);

 --==== Grouped by date\hour
 Select total_qty = sum(tt.qty)
      , tt.Info
      , latest_date = max(tt.dErr)
   From @testTable tt
  Group By
        tt.Info
      , cast(tt.dErr As date)
      , datepart(Hour, tt.dErr)
  Order By
        cast(tt.dErr As date)
      , datepart(Hour, tt.dErr);
</code>```

Body:
I try to get the date range between the data changes in SQL Server
my query is

select count(1) as qty, Info, convert(char,dFError,100) dErr
from TableData
group by Info, convert(char,dFError,100)
order by dErr asc

I have this
qty has the number of reques to a server, info are the servers ip and the date it's when a request it's sended to another server.

qty
Info
dErr

1
1.97
Aug 11 2021  9:01AM

1
1.97
Aug 11 2021  9:06AM

88
1.33
Dec 21 2021  2:04PM

1
1.95
Dec 22 2021  9:44PM

9
1.95
Dec 22 2021  9:45PM

1
1.33
Dec 22 2021  9:51PM

19
1.33
Dec 22 2021  9:52PM

3
1.33
Dec 22 2021  9:53PM

6
1.33
Dec 27 2021  7:10PM

17
1.33
Dec 27 2021  7:11PM

15
1.95
Dec 27 2021  7:17PM

8
1.95
Dec 27 2021  7:18PM

and I want this, in Aug 11 at 9:06AM all are going to 1.97, at Dec 21 at 2:04PM all are going to 1.33, that means the date and the info

qty
Info
dErr

2
1.97
Aug 11 2021  9:06AM

88
1.33
Dec 21 2021  2:04PM

10
1.95
Dec 22 2021  9:45PM

46
1.33
Dec 27 2021  7:11PM

23
1.95
Dec 27 2021  7:18PM

in the same day can be the same group of numbers on distinct hour

qty
Info
dErr

1
1.97
Jan 24 2022  9:39AM

1
1.97
Jan 24 2022  9:51AM

1
1.97
Jan 24 2022  9:58AM

4
1.97
Jan 24 2022 10:08AM

1
1.97
Jan 24 2022 10:12AM

8
1.95
Jan 24 2022 10:24AM

2
1.95
Jan 24 2022 10:32AM

10
1.33
Jan 24 2022 10:33AM

1
1.33
Jan 24 2022 11:37AM

8
1.95
Jan 24 2022 11:59AM

1
1.95
Jan 24 2022 12:00PM

2
1.95
Jan 24 2022 12:08PM

and need to be displayed like

qty
Info
dErr

8
1.97
Jan 24 2022  10:12AM

10
1.95
Jan 24 2022 10:32AM

11
1.33
Jan 24 2022 11:37AM

11
1.95
Jan 24 2022 12:08PM

Body:
Your expected results don't match the given data - in the first set you have rows for 12/22 with both 1.33 and 1.95, but not included in your expected results.

It seems to me you want to either group by the date - or the date\hour.  Here is an example of both:

Declare @testTable table (qty int, Info numeric(3,2), dErr datetime);
 Insert Into @testTable (qty, Info, dErr)
 Values ( 1, 1.97, 'Aug 11 2021 9:01AM')
      , ( 1, 1.97, 'Aug 11 2021 9:06AM')
      , (88, 1.33, 'Dec 21 2021 2:04PM')
      , ( 1, 1.95, 'Dec 22 2021 9:44PM')
      , ( 9, 1.95, 'Dec 22 2021 9:45PM')
      , ( 1, 1.33, 'Dec 22 2021 9:51PM')
      , (19, 1.33, 'Dec 22 2021 9:52PM')
      , ( 3, 1.33, 'Dec 22 2021 9:53PM')
      , ( 6, 1.33, 'Dec 27 2021 7:10PM')
      , (17, 1.33, 'Dec 27 2021 7:11PM')
      , (15, 1.95, 'Dec 27 2021 7:17PM')
      , ( 8, 1.95, 'Dec 27 2021 7:18PM')

      , ( 1, 1.97, 'Jan 24 2022 9:39AM')
      , ( 1, 1.97, 'Jan 24 2022 9:51AM')
      , ( 1, 1.97, 'Jan 24 2022 9:58AM')
      , ( 4, 1.97, 'Jan 24 2022 10:08AM')
      , ( 1, 1.97, 'Jan 24 2022 10:12AM')
      , ( 8, 1.95, 'Jan 24 2022 10:24AM')
      , ( 2, 1.95, 'Jan 24 2022 10:32AM')
      , (10, 1.33, 'Jan 24 2022 10:33AM')
      , ( 1, 1.33, 'Jan 24 2022 11:37AM')
      , ( 8, 1.95, 'Jan 24 2022 11:59AM')
      , ( 1, 1.95, 'Jan 24 2022 12:00PM')
      , ( 2, 1.95, 'Jan 24 2022 12:08PM');

 --==== Grouped by date
 Select total_qty = sum(tt.qty)
      , tt.Info
      , latest_date = max(tt.dErr)
   From @testTable tt
  Group By
        tt.Info
      , cast(tt.dErr As date)
  Order By
        cast(tt.dErr As date);

 --==== Grouped by date\hour
 Select total_qty = sum(tt.qty)
      , tt.Info
      , latest_date = max(tt.dErr)
   From @testTable tt
  Group By
        tt.Info
      , cast(tt.dErr As date)
      , datepart(Hour, tt.dErr)
  Order By
        cast(tt.dErr As date)
      , datepart(Hour, tt.dErr);