问:
Why sklearn.discriminant_analysis uses priors for calculating within-class covariance matrix?
I found that Linear Discriminant Analysis of sklearn (discriminant_analysis.py) uses priors for calculating within-class covariance matrix.

I refered some books but they explained the priors are used for calculating intercepts.

Do you know any references which explain why the within-class covariance matrix is calculated by priors?

This is the line.

```<code>cov += priors[idx] * np.atleast_2d(_cov(Xg, shrinkage, covariance_estimator))
</code>```

Here is the class from the discriminant_analysis.py

```<code>def _class_cov(X, y, priors, shrinkage=None, covariance_estimator=None):
    """Compute weighted within-class covariance matrix.

    The per-class covariance are weighted by the class priors.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Input data.

    y : array-like of shape (n_samples,) or (n_samples, n_targets)
        Target values.

    priors : array-like of shape (n_classes,)
        Class priors.

    shrinkage : 'auto' or float, default=None
        Shrinkage parameter, possible values:
          - None: no shrinkage (default).
          - 'auto': automatic shrinkage using the Ledoit-Wolf lemma.
          - float between 0 and 1: fixed shrinkage parameter.

        Shrinkage parameter is ignored if `covariance_estimator` is not None.

    covariance_estimator : estimator, default=None
        If not None, `covariance_estimator` is used to estimate
        the covariance matrices instead of relying the empirical
        covariance estimator (with potential shrinkage).
        The object should have a fit method and a ``covariance_`` attribute
        like the estimators in sklearn.covariance.
        If None, the shrinkage parameter drives the estimate.

        .. versionadded:: 0.24

    Returns
    -------
    cov : array-like of shape (n_features, n_features)
        Weighted within-class covariance matrix
    """
    classes = np.unique(y)
    cov = np.zeros(shape=(X.shape[1], X.shape[1]))
    for idx, group in enumerate(classes):
        Xg = X[y == group, :]
        cov += priors[idx] * np.atleast_2d(_cov(Xg, shrinkage, covariance_estimator))
    return cov
</code>```

Here is the part of Linear Discriminant Analysis codes.

I understand the reason why the intercept is calculated by priors.

```<code>        self.means_ = _class_means(X, y)
        self.covariance_ = _class_cov(
            X, y, self.priors_, shrinkage, covariance_estimator
        )
        self.coef_ = linalg.lstsq(self.covariance_, self.means_.T)[0].T
        self.intercept_ = -0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + np.log(
            self.priors_
        )
</code>```

Body:
I found that Linear Discriminant Analysis of sklearn (discriminant_analysis.py) uses priors for calculating within-class covariance matrix.

I refered some books but they explained the priors are used for calculating intercepts.

Do you know any references which explain why the within-class covariance matrix is calculated by priors?

This is the line.

cov += priors[idx] * np.atleast_2d(_cov(Xg, shrinkage, covariance_estimator))

Here is the class from the discriminant_analysis.py

def _class_cov(X, y, priors, shrinkage=None, covariance_estimator=None):
    """Compute weighted within-class covariance matrix.

    The per-class covariance are weighted by the class priors.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        Input data.

    y : array-like of shape (n_samples,) or (n_samples, n_targets)
        Target values.

    priors : array-like of shape (n_classes,)
        Class priors.

    shrinkage : 'auto' or float, default=None
        Shrinkage parameter, possible values:
          - None: no shrinkage (default).
          - 'auto': automatic shrinkage using the Ledoit-Wolf lemma.
          - float between 0 and 1: fixed shrinkage parameter.

        Shrinkage parameter is ignored if `covariance_estimator` is not None.

    covariance_estimator : estimator, default=None
        If not None, `covariance_estimator` is used to estimate
        the covariance matrices instead of relying the empirical
        covariance estimator (with potential shrinkage).
        The object should have a fit method and a ``covariance_`` attribute
        like the estimators in sklearn.covariance.
        If None, the shrinkage parameter drives the estimate.

        .. versionadded:: 0.24

    Returns
    -------
    cov : array-like of shape (n_features, n_features)
        Weighted within-class covariance matrix
    """
    classes = np.unique(y)
    cov = np.zeros(shape=(X.shape[1], X.shape[1]))
    for idx, group in enumerate(classes):
        Xg = X[y == group, :]
        cov += priors[idx] * np.atleast_2d(_cov(Xg, shrinkage, covariance_estimator))
    return cov

Here is the part of Linear Discriminant Analysis codes.

I understand the reason why the intercept is calculated by priors.

        self.means_ = _class_means(X, y)
        self.covariance_ = _class_cov(
            X, y, self.priors_, shrinkage, covariance_estimator
        )
        self.coef_ = linalg.lstsq(self.covariance_, self.means_.T)[0].T
        self.intercept_ = -0.5 * np.diag(np.dot(self.means_, self.coef_.T)) + np.log(
            self.priors_
        )


来源: stackexchange

问:
Exiting with a weird exit code, and SIGSEGV on attempting to exit with 0 in .s file
I am trying to learn how to use .s files, and wrote the following:

```<code>    .globl main
    .text

main:
    mov $msg, %rdi
    call puts

    ret

    .data
msg:
    .asciz "Hello, world!"
</code>```

I then compile with the following:

```<code>$ gcc -no-pie -c -o example.o example.s
$ gcc -no-pie -o example example.s
</code>```

The example executable produced prints Hello, world! as expected, but exits with exit code 14, suggesting that something went wrong regarding the print?

I tried exiting manually like so:

```<code>    .globl main
    .text

main:
    mov $msg, %rdi
    call puts

    mov 0, %rdi
    call exit

    ret

    .data
msg:
    .asciz "Hello, world!"
</code>```

However, this segfaulted. From gdb, it seems to segfault on the line mov 0, %rdi, however I've tried multiple ways of moving (movq 0, %edi, movl 0, %edi, mov 0x0, %rdi) and all have segfaulted.

Am I doing something wrong?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to learn how to use .s files, and wrote the following:

    .globl main
    .text

main:
    mov $msg, %rdi
    call puts

    ret

    .data
msg:
    .asciz "Hello, world!"

I then compile with the following:

$ gcc -no-pie -c -o example.o example.s
$ gcc -no-pie -o example example.s

The example executable produced prints Hello, world! as expected, but exits with exit code 14, suggesting that something went wrong regarding the print?

I tried exiting manually like so:

    .globl main
    .text

main:
    mov $msg, %rdi
    call puts

    mov 0, %rdi
    call exit

    ret

    .data
msg:
    .asciz "Hello, world!"

However, this segfaulted. From gdb, it seems to segfault on the line mov 0, %rdi, however I've tried multiple ways of moving (movq 0, %edi, movl 0, %edi, mov 0x0, %rdi) and all have segfaulted.

Am I doing something wrong?


问:
How to Increase User Login Session Time in PHP
I made a simple Login in PHP based on tutorials, where the user after logging in is saved in the Session variable like the example below.

```<code>$_SESSION['username'] = $username
</code>```

The problem is that the login session is automatically closed after closing the browser, obligating the user to always start the login process all over again and again.

How I can keep the user logged in for a week or a month? (Like Facebook and others) What is the proper and safe way to do it?

Body:
I made a simple Login in PHP based on tutorials, where the user after logging in is saved in the Session variable like the example below.

$_SESSION['username'] = $username

The problem is that the login session is automatically closed after closing the browser, obligating the user to always start the login process all over again and again.

How I can keep the user logged in for a week or a month? (Like Facebook and others) What is the proper and safe way to do it?


问:
Using service discovery with AWS ECS services containing Flask/Gunicorn
I have two ECS Fargate services, both with a dockerized container containing a flask/gunicorn application that can be called via API. I have setup service discovery for service A to talk to service B. The issue I'm having is when I setup 2 tasks for service B, only 1 task is being called, unless I stop the other task, in which case the other task will be called. Both tasks are not being routed to. Oddly enough, if I use a lambda function to call Service B, It successfully routes to both tasks. Is there something that would cause Service A to only route to 1 task? It calls service B about 100 times per execution, once per hour, so I would think over the course of a couple days I would at least see logs on both tasks but I'm not?

Both ECS services are in the same cluster, in the same VPC


问:
How sort when have array with name and score mongodb
I have a document with users and each user haves "categories" and "tags", in both as at next:

```<code>[
{user_id: 1, categories:[
 {category: uuidv4x1, score:75},
 {category: uuidv4x2, score:67}
],
tags: [
 {tag: "1ne", score:15},
 {tag: "subjetive", score:89}
]}
</code>```

How can order by category, tag but too by score, if i have:

```<code>[
{id: 1, category: uuidv4x6, tags:["1ne", "optimized"]},
{id: 2, category: uuidv4x2, tags:["1ne", "subjetive"]},
{id: 3, category: uuidv4x1, tags:["home", "car"]}
]
</code>```

Before to all, thanks so much.

I expect sort my find for better matches, customize articles.

Body:
I have a document with users and each user haves "categories" and "tags", in both as at next:

[
{user_id: 1, categories:[
 {category: uuidv4x1, score:75},
 {category: uuidv4x2, score:67}
],
tags: [
 {tag: "1ne", score:15},
 {tag: "subjetive", score:89}
]}

How can order by category, tag but too by score, if i have:

[
{id: 1, category: uuidv4x6, tags:["1ne", "optimized"]},
{id: 2, category: uuidv4x2, tags:["1ne", "subjetive"]},
{id: 3, category: uuidv4x1, tags:["home", "car"]}
]

Before to all, thanks so much.

I expect sort my find for better matches, customize articles.


问:
Text overlapping button in Facebook Oauth view
I'm asking this question here since I have no more ideas of where to look.

I've integrated this Facebook SDK library in my React Native app for a Facebook API authorisation flow.

It works fine on recent large screens but on smaller screens, there's a layout issue in the Facebook pages in the internal browser: the legal text overlaps the buttons and the user cannot click them (see screenshot below).

I have no idea where to even start fixing this and I got no helpful answer from Facebook support.
If anyone has an idea, I'm open to everything.

Here is the code that launches the auth flow though I don't know how related it could be.

const permissions = [
    'instagram_basic',
    'pages_show_list',
    'instagram_manage_messages',
    'pages_manage_metadata',
    'pages_read_engagement',
  ];

  const handleFacebookPermissions = () => {
    // this is the line that starts the flow, I don't have much in terms of options
    LoginManager.logInWithPermissions(permissions).then(
      function (result) {
        if (result.isCancelled) {
          console.log('Login cancelled');
        } else {
          AccessToken.getCurrentAccessToken().then(data => {
            // doing stuff with the access token on success
          });
        }
      },
      function (error) {
        console.log('Login fail with error: ' + error);
      },
    );
  };
```

I don't have a lot of options to try since the actual function is just one line...

Body:
I'm asking this question here since I have no more ideas of where to look.

I've integrated this Facebook SDK library in my React Native app for a Facebook API authorisation flow.

It works fine on recent large screens but on smaller screens, there's a layout issue in the Facebook pages in the internal browser: the legal text overlaps the buttons and the user cannot click them (see screenshot below).

I have no idea where to even start fixing this and I got no helpful answer from Facebook support.
If anyone has an idea, I'm open to everything.

Here is the code that launches the auth flow though I don't know how related it could be.

const permissions = [
    'instagram_basic',
    'pages_show_list',
    'instagram_manage_messages',
    'pages_manage_metadata',
    'pages_read_engagement',
  ];

  const handleFacebookPermissions = () => {
    // this is the line that starts the flow, I don't have much in terms of options
    LoginManager.logInWithPermissions(permissions).then(
      function (result) {
        if (result.isCancelled) {
          console.log('Login cancelled');
        } else {
          AccessToken.getCurrentAccessToken().then(data => {
            // doing stuff with the access token on success
          });
        }
      },
      function (error) {
        console.log('Login fail with error: ' + error);
      },
    );
  };

I don't have a lot of options to try since the actual function is just one line...


问:
Spring Boot 3 Redis Indexed Session - Failure to save login
I am upgrading my team's Spring Boot project from 2.7.5 to 3.0.0, which includes a migration of the now deprecated WebSecurityConfigurerAdapter. I am working in Kotlin, but I do not believe the language impacts the performance of the component.

In both the old and new versions of the security configuration class, I have declared this Autowired field and corresponding bean:

    @Autowired
    private lateinit var sessionRepository: FindByIndexNameSessionRepository<out Session>

    @Bean
    fun sessionRegistry(): SessionRegistry {
        return SpringSessionBackedSessionRegistry(sessionRepository)
    }
```
<p>At first, my application would not start, because Spring could not wire the session repository into my configuration, but after some digging, it was because I had to change the <code>@EnableRedisHttpSession</code> annotation to</p>
<pre class="lang-kotlin prettyprint-override"><code>@EnableRedisIndexedHttpSession
class SecurityConfiguration(
</code>```

Now, my current issue with the application is that I cannot log into my application, and I think it has to do with the Redis session management.

I am able to load the login page, and submit a login request. When I submit the request, I am able to see all of the normal debug messages my application prints associated with logging in, taking me through a successful authentication. When all of that finishes, my application redirects the user to the main page, which checks if a user's authentication != null, and redirects them to the main page if so. However, the authentication at this point is null, and there is not an entry in redis for this user's authentication.

In case it helps, this is what the security configuration had defined in the SecurityFilterChain bean for the session parts before the migration:

.sessionManagement().sessionFixation().migrateSession().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).maximumSessions(1).sessionRegistry(sessionRegistry()).expiredUrl("/api/v1/logout").and()
```
<p>and after:</p>
<pre class="lang-kotlin prettyprint-override"><code>.sessionManagement { ssm ->
  ssm.sessionFixation { it.migrateSession() }
  ssm.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
    .maximumSessions(1).sessionRegistry(sessionRegistry()).expiredUrl("/api/v1/logout")
}
</code>```

Is there something I am missing to allow the user authentication to persist? I have not touched any part of the code for this migration besides the pom.xml file and the rewriting of the security configuration.

UPDATE: I have altered the tags of the security configuration, in a desperate attempt at getting something to save.

@Configuration
@EnableWebSecurity
@EnableSpringHttpSession
@EnableRedisIndexedHttpSession(redisNamespace = "admindev:session", flushMode = FlushMode.IMMEDIATE, saveMode = SaveMode.ALWAYS)
class SecurityConfiguration(
```
<p>I have increased the logging level for spring security, and everything looks fine, until the session token is not found.</p>
<hr />
<p>Update 2:</p>
<p>I have tweaked my application as I have described in my answer to this post, and I am now able to access the frontend of my application. However, when I attempt to login through the backend, I get caught up in an infinite redirection loop. The app tries to send me to the error/4xx page, which is the correct behavior, since we don't have a "/" link on the backend, but then the app tries to redirect me according to the "your session has expired" page, and since I'm logged in, it tries to redirect me back to "/"...</p>
<p>Looking through the logs, it seems to be related to the exception handling I set up on my filter chain:</p>
<pre class="lang-kotlin prettyprint-override"><code>http.exceptionHandling { e -> e.authenticationEntryPoint(LoginRedirectHandler()) }
//...
class LoginRedirectHandler : LoginUrlAuthenticationEntryPoint("/login") {
    override fun determineUrlToUseForThisRequest(
        request: HttpServletRequest,
        response: HttpServletResponse,
        exception: AuthenticationException?
    ): String {
        return "${this.loginFormUrl}?error=timeout&requestedUrl=${request.requestURL}"
    }
}
</code>```

Now, the question becomes: the backend webpages were not looping before, what could have changed about this behavior?

Body:
I am upgrading my team's Spring Boot project from 2.7.5 to 3.0.0, which includes a migration of the now deprecated WebSecurityConfigurerAdapter. I am working in Kotlin, but I do not believe the language impacts the performance of the component.

In both the old and new versions of the security configuration class, I have declared this Autowired field and corresponding bean:

    @Autowired
    private lateinit var sessionRepository: FindByIndexNameSessionRepository<out Session>

    @Bean
    fun sessionRegistry(): SessionRegistry {
        return SpringSessionBackedSessionRegistry(sessionRepository)
    }

At first, my application would not start, because Spring could not wire the session repository into my configuration, but after some digging, it was because I had to change the @EnableRedisHttpSession annotation to

@EnableRedisIndexedHttpSession
class SecurityConfiguration(

Now, my current issue with the application is that I cannot log into my application, and I think it has to do with the Redis session management.

I am able to load the login page, and submit a login request. When I submit the request, I am able to see all of the normal debug messages my application prints associated with logging in, taking me through a successful authentication. When all of that finishes, my application redirects the user to the main page, which checks if a user's authentication != null, and redirects them to the main page if so. However, the authentication at this point is null, and there is not an entry in redis for this user's authentication.

In case it helps, this is what the security configuration had defined in the SecurityFilterChain bean for the session parts before the migration:

.sessionManagement().sessionFixation().migrateSession().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).maximumSessions(1).sessionRegistry(sessionRegistry()).expiredUrl("/api/v1/logout").and()

and after:

.sessionManagement { ssm ->
  ssm.sessionFixation { it.migrateSession() }
  ssm.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
    .maximumSessions(1).sessionRegistry(sessionRegistry()).expiredUrl("/api/v1/logout")
}

Is there something I am missing to allow the user authentication to persist? I have not touched any part of the code for this migration besides the pom.xml file and the rewriting of the security configuration.

UPDATE: I have altered the tags of the security configuration, in a desperate attempt at getting something to save.

@Configuration
@EnableWebSecurity
@EnableSpringHttpSession
@EnableRedisIndexedHttpSession(redisNamespace = "admindev:session", flushMode = FlushMode.IMMEDIATE, saveMode = SaveMode.ALWAYS)
class SecurityConfiguration(

I have increased the logging level for spring security, and everything looks fine, until the session token is not found.

Update 2:

I have tweaked my application as I have described in my answer to this post, and I am now able to access the frontend of my application. However, when I attempt to login through the backend, I get caught up in an infinite redirection loop. The app tries to send me to the error/4xx page, which is the correct behavior, since we don't have a "/" link on the backend, but then the app tries to redirect me according to the "your session has expired" page, and since I'm logged in, it tries to redirect me back to "/"...

Looking through the logs, it seems to be related to the exception handling I set up on my filter chain:

http.exceptionHandling { e -> e.authenticationEntryPoint(LoginRedirectHandler()) }
//...
class LoginRedirectHandler : LoginUrlAuthenticationEntryPoint("/login") {
    override fun determineUrlToUseForThisRequest(
        request: HttpServletRequest,
        response: HttpServletResponse,
        exception: AuthenticationException?
    ): String {
        return "${this.loginFormUrl}?error=timeout&requestedUrl=${request.requestURL}"
    }
}

Now, the question becomes: the backend webpages were not looping before, what could have changed about this behavior?


问:
Swagger Codegen Spring Converters
I am using swagger(openapi) codegen to generate Rest Api Server Stub.

Is it possible to use the "spring" generator and somehow use Spring Rest converters ?

The problem is that before I had a simple

```<code>@GetMapping
public String (@RequestBody Locale locale)
</code>```

Now with openapi codegen I have an ugly LocaleDto that has 50 fields and so on. And also I need to manually transform my object back to "Locale" with

```<code>LocaleUtils.from().
</code>```

Relative docs:

https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen-maven-plugin/README.md

Any help is greatly appreciated.

Title: Swagger Codegen Spring Converters

Body:
I am using swagger(openapi) codegen to generate Rest Api Server Stub.

Is it possible to use the "spring" generator and somehow use Spring Rest converters ?

The problem is that before I had a simple

@GetMapping
public String (@RequestBody Locale locale)

Now with openapi codegen I have an ugly LocaleDto that has 50 fields and so on. And also I need to manually transform my object back to "Locale" with

LocaleUtils.from().

Relative docs:

https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen-maven-plugin/README.md

Any help is greatly appreciated.


问:
VS Code: why is Python dataclass not inheriting the parent's attributes?
I am new to OOP, often a big pain as things aren't explained clearly and have weird behaviours.

One frustrating example in Python 3.9.13:

```<code>@dataclass
class Person:
    name: str
    city: str
    age: int

@dataclass
class Student(Person):
    grade: int
    subjects: list
</code>```

I typed:

```<code>s = Student()
</code>```

getting, as expected:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [9], line 1
----> 1 s = Student()

TypeError: __init__() missing 2 required positional arguments: 'grade' and 'subjects'
</code>```

What's unexpected: why does it not say that name, city, and age are also required?

Body:
I am new to OOP, often a big pain as things aren't explained clearly and have weird behaviours.

One frustrating example in Python 3.9.13:

@dataclass
class Person:
    name: str
    city: str
    age: int

@dataclass
class Student(Person):
    grade: int
    subjects: list

I typed:

s = Student()

getting, as expected:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [9], line 1
----> 1 s = Student()

TypeError: __init__() missing 2 required positional arguments: 'grade' and 'subjects'

What's unexpected: why does it not say that name, city, and age are also required?


问:
TinyMCE - enable only table editing
I use TinyMCE and would like to allow the user to create only tables within the editor.

The user can create or paste them but not add additional text outside the table tags. However within the table tag it is possible to insert anything

I've tried several configurations but haven't found anything that works for me, and the documentation doesn't help. Does anyone have ideas on how to do this?

Title: TinyMCE - enable only table editing


问:
Django does not add attribute to the custom ModelForm widget
I'm trying to add another attribute in HTML (placeholder) using Django Widgets, when I do it, they don't appear in the HTML.

models.py

```<code>class InvitadosIngreso(forms.ModelForm):
    class Meta:
        model = InvitadosIngreso

        fields = ['oficina_pro'
                    ,'documento'

        widgets = {
            'oficina_pro' : forms.Select(attrs={'class':'form-control'},choices=ch_pro)
            ,'documento ': forms.TextInput(attrs={'class':'form-control', 'placeholder':'prueba',})
        }

</code>```

forms.py

```<code>class InvitadosIngreso(models.Model):

 oficina_pro = models.CharField(max_length=100, default='')
    documento = models.CharField(max_length=100, default='')
    nombre = models.CharField(max_length=100, default='')

    class Meta:
    db_table = 'InvitadosIngreso'

</code>```

Body:
I'm trying to add another attribute in HTML (placeholder) using Django Widgets, when I do it, they don't appear in the HTML.

models.py

class InvitadosIngreso(forms.ModelForm):
    class Meta:
        model = InvitadosIngreso

        fields = ['oficina_pro'
                    ,'documento'

        widgets = {
            'oficina_pro' : forms.Select(attrs={'class':'form-control'},choices=ch_pro)
            ,'documento ': forms.TextInput(attrs={'class':'form-control', 'placeholder':'prueba',})
        }

forms.py

class InvitadosIngreso(models.Model):

 oficina_pro = models.CharField(max_length=100, default='')
    documento = models.CharField(max_length=100, default='')
    nombre = models.CharField(max_length=100, default='')

    class Meta:
    db_table = 'InvitadosIngreso'


问:
Socketio emit and on is not working properly in NodeJS
Socket io.on is not working in NodeJS.

Front End - Angular 14x
socket io version - "socket.io-client": "^4.5.4",

BackEnd - Nodejs 14x
socket.io version - "socket.io": "^4.5.4",

FrontEnd Code -

```<code>import SocketClient from 'socket.io-client';

export class Customer_FileUpload implements OnInit {

 @Input() io = SocketClient(environment.url, {
      autoConnect: true
  })

  submitRequest() {
   this.shared.submitRequest(data).subscribe({
        next: (response) => {
          const result = JSON.parse(JSON.stringify(response));
          console.log(result);

          this.io.emit('emit-data', "I am good");

          this.io.on('data2', (msg) => {
             console.log('message: ' + JSON.stringify(msg));
          });

        },
        error: (error) => {
          console.log(error);
        }
      })
  }
}
</code>```

Backend Code -

index.js

```<code>const express = require('express');
const bodyparser = require('body-parser');
const cors = require('cors');
const fileUpload = require('express-fileupload');
const http = require('http');
const { RealTime } = require('./utils/socket');

const socket =  new RealTime();
const app = express();

app.use(cors())
app.options('*', cors());

app.use(bodyparser.json({limit: '5mb', extended: true}))
app.use(bodyparser.urlencoded({limit: '5mb', extended: true}))

const authRoutes = require('./routes/authRoutes');
const apiRoutes = require('./routes/routes');

// For File Upload
app.use(fileUpload({
  limits: { fileSize: 5 * 1024 * 1024 },
}));

app.use('/auth', authRoutes);
app.use('/user', apiRoutes);

//Capture All 404 errors
app.use(function (req,res,next){
    res.status(404).send('Error - Unable to find the requested resource!');
});

app.use((req, res, next) => {
  req.socket.on('error', () => {});
  next();
});

const server = http.createServer(app);

socket.intialized_connection(server);
socket.init();

module.exports = server;
</code>```

Socket.js

```<code>let io = null;

class RealTime {
    constructor() {
        if (io) return io;
        io = this;
        return io;
    }

    intialized_connection(httpServer) {
        return (io = require('socket.io')(httpServer, {
            cors: {
              origin: '*',
            //   methods: ['GET', 'POST', 'PUT', 'DELETE'],
            },
        }));
    }

    init() {
        io.on("connection", function (socket) {
            console.log("A user connected");
            //Whenever someone disconnects this piece of code executed
            socket.on('disconnect', function () {
                console.log('A user disconnected');
            });
        });
    }

    getIO() {
        if (!io) {
            throw new Error('Socket.io is not initialized');
        }
        return io;
    }

    sendEvents(event, data) {
       this.getIO().emit(event, data);
    }

    receivedEvents(event) {
        console.log(event);

        this.getIO().on(event, function(data) {
            console.log("I am emiiting here, ")
            console.log(data)
        });
    }
}
module.exports = {
    RealTime
};
</code>```

Controller.js

```<code>exports.submitRequest = async(req, res) => {
    socket.receivedEvents('emit-data');

    socket.sendEvents("data2", {
         message: "hello from nodejs controller"
    });

    res.json("done");
}
</code>```

I have 2 issues here. Issues are ---

socket.receivedEvents -- Is not working, Not getting any error message, Neither in the client side not server side.

socket.sendEvents, It is working fine, in the client side, when we click second time. Attach the screenshot below.

First Time when we click on the submit button --

First time when we click on the submit

Second Time when we click on the submit button --

Second time when we click on the submit

Third Time when we click on the submit button --
Getting 2 times the same result.

Third time when we click on the submit

Any idea what I am doing wrong?

Can you please give me these 2 solution's problem?

Body:
Socket io.on is not working in NodeJS.

Front End - Angular 14x
socket io version - "socket.io-client": "^4.5.4",

BackEnd - Nodejs 14x
socket.io version - "socket.io": "^4.5.4",

FrontEnd Code -

import SocketClient from 'socket.io-client';

export class Customer_FileUpload implements OnInit {

 @Input() io = SocketClient(environment.url, {
      autoConnect: true
  })

  submitRequest() {
   this.shared.submitRequest(data).subscribe({
        next: (response) => {
          const result = JSON.parse(JSON.stringify(response));
          console.log(result);

          this.io.emit('emit-data', "I am good");

          this.io.on('data2', (msg) => {
             console.log('message: ' + JSON.stringify(msg));
          });

        },
        error: (error) => {
          console.log(error);
        }
      })
  }
}

Backend Code -

index.js

const express = require('express');
const bodyparser = require('body-parser');
const cors = require('cors');
const fileUpload = require('express-fileupload');
const http = require('http');
const { RealTime } = require('./utils/socket');

const socket =  new RealTime();
const app = express();

app.use(cors())
app.options('*', cors());

app.use(bodyparser.json({limit: '5mb', extended: true}))
app.use(bodyparser.urlencoded({limit: '5mb', extended: true}))

const authRoutes = require('./routes/authRoutes');
const apiRoutes = require('./routes/routes');

// For File Upload
app.use(fileUpload({
  limits: { fileSize: 5 * 1024 * 1024 },
}));

app.use('/auth', authRoutes);
app.use('/user', apiRoutes);

//Capture All 404 errors
app.use(function (req,res,next){
    res.status(404).send('Error - Unable to find the requested resource!');
});

app.use((req, res, next) => {
  req.socket.on('error', () => {});
  next();
});

const server = http.createServer(app);

socket.intialized_connection(server);
socket.init();

module.exports = server;

Socket.js

let io = null;

class RealTime {
    constructor() {
        if (io) return io;
        io = this;
        return io;
    }

    intialized_connection(httpServer) {
        return (io = require('socket.io')(httpServer, {
            cors: {
              origin: '*',
            //   methods: ['GET', 'POST', 'PUT', 'DELETE'],
            },
        }));
    }

    init() {
        io.on("connection", function (socket) {
            console.log("A user connected");
            //Whenever someone disconnects this piece of code executed
            socket.on('disconnect', function () {
                console.log('A user disconnected');
            });
        });
    }

    getIO() {
        if (!io) {
            throw new Error('Socket.io is not initialized');
        }
        return io;
    }

    sendEvents(event, data) {
       this.getIO().emit(event, data);
    }

    receivedEvents(event) {
        console.log(event);

        this.getIO().on(event, function(data) {
            console.log("I am emiiting here, ")
            console.log(data)
        });
    }
}
module.exports = {
    RealTime
};

Controller.js

exports.submitRequest = async(req, res) => {
    socket.receivedEvents('emit-data');

    socket.sendEvents("data2", {
         message: "hello from nodejs controller"
    });

    res.json("done");
}

I have 2 issues here. Issues are ---

socket.receivedEvents -- Is not working, Not getting any error message, Neither in the client side not server side.

socket.sendEvents, It is working fine, in the client side, when we click second time. Attach the screenshot below.

First Time when we click on the submit button --

First time when we click on the submit

Second Time when we click on the submit button --

Second time when we click on the submit

Third Time when we click on the submit button --
Getting 2 times the same result.

Third time when we click on the submit

Any idea what I am doing wrong?

Can you please give me these 2 solution's problem?


问:
Accessing DI scope within a custom attribute
I have an application that consumes JSON from a 3rd party. When a new type comes in that we don't have defined, we log it and add it to our codebase. Sometimes these have empty arrays as properties; since we don't what they are, we initially define them as "object[]" in our Type definitions and decorate those with a custom JsonConverterAttribute. e.g. [JsonConverter(typeof(DoMyBestToFindAMatchingTypeConverter))]. Some of these decorations are deeply nested in our definitions. We don't want to modify the 3rd party source to make this work.

We also have a scoped TypeCheckingService that we use to determine if a type already exists based on the attributes on the inbound JSON. Within the implementation of our DoMyBestToFindAMatchingTypeConverter, we'd like to access this TypeCheckingService, which has constructor-injected dependencies. Since the custom attribute is from a third party which I assume performs some kind of reflection-based construction on the type assigned in the attribute, I'm not sure how to provide any scope to it as even IServiceProvider needs to be constructor injected. Is it possible to "look skyward" through the call stack to determine if I'm in a ServiceProvider Scope (not unlike how TransactionScope automagically works) and just grab it? One option, which feels extremely grotesque is that it seems possible to have a static reference to IServiceProvider somewhere and generate a scoped context from there, but I fear there might be lifetime things going on behind the scenes where holding such a reference could cause problems.


问:
Change UI color based on a condition in Xcode with SwiftUI
I am trying to change the color on animation applied on a swipe gesture but its not working. Is there any logical error that i am unable to find ? kindly help.

the if condition that i am using

```<code>import SwiftUI

struct ContentView: View {
    @StateObject var manager = RecipeManager()
    @Namespace private var viewSpace
    var body: some View {
        ZStack {
            if manager.currentRecipeIndex % 2 == 0 {
                Color.lightBackground
                    .ignoresSafeArea()
                    .transition(.move(edge: .bottom))
            } else {
                Color.darkBackground
                    .ignoresSafeArea()
                    .transition(.move(edge: .bottom))
            }

            RecipeOverview(manager: manager, viewSpace: viewSpace)
                .padding(.horizontal)

            if manager.selectedRecipe != nil {
                RecipeDetailView(manager: manager, viewSpace: viewSpace)
            }
        }
    }
}

</code>```

and here is the extension to the color

```<code>extension Color {
    static let lightBackground = Color.init(red: 243/255, green: 243/255, blue: 243/255)
    static let darkBackground = Color.init(red: 34/255, green: 51/255, blue: 68/255)
}
</code>```

The program keeps showing the white screen. but if change the if condition to show the darkBackground then it does not show the white screen while executing the else statement.

Body:
I am trying to change the color on animation applied on a swipe gesture but its not working. Is there any logical error that i am unable to find ? kindly help.

the if condition that i am using

import SwiftUI

struct ContentView: View {
    @StateObject var manager = RecipeManager()
    @Namespace private var viewSpace
    var body: some View {
        ZStack {
            if manager.currentRecipeIndex % 2 == 0 {
                Color.lightBackground
                    .ignoresSafeArea()
                    .transition(.move(edge: .bottom))
            } else {
                Color.darkBackground
                    .ignoresSafeArea()
                    .transition(.move(edge: .bottom))
            }

            RecipeOverview(manager: manager, viewSpace: viewSpace)
                .padding(.horizontal)

            if manager.selectedRecipe != nil {
                RecipeDetailView(manager: manager, viewSpace: viewSpace)
            }
        }
    }
}

and here is the extension to the color

extension Color {
    static let lightBackground = Color.init(red: 243/255, green: 243/255, blue: 243/255)
    static let darkBackground = Color.init(red: 34/255, green: 51/255, blue: 68/255)
}

The program keeps showing the white screen. but if change the if condition to show the darkBackground then it does not show the white screen while executing the else statement.


问:
Expo-Camera for local simulator development is not supported, how to work around this?
expo-camera is not supported by any of the simulators.  Therefore, when using this component in development & on the simulator, it results in an error and data is not stored as it would on the actual device.

Possible Unhandled Promise Rejection.  Error:  Video recording is not supported on a simulator

This is causing an issue in terms of verifying functionality and the "happy path".

I added an interim check for a video field and then return the basic camera, so at least our flow works, but I don't think it's a long terms solution:

```<code> if (
      process.env.NODE_ENV === 'development' &&
      field.kind === ComponentTypes.VIDEO
    ) {
       return <CameraImage />
    }
</code>```

How do you work around this intended behavior, in terms of getting data to store?  All I can think of doing for this is adding a catch and faking the data:

```<code> cameraRef?.current
        .recordAsync(options)
        .then(vid => {
          console.log({ vid });

          setRecordedVideo(vid);
        })
        .catch(() => {
          if (process.env.NODE_ENV === 'development') {
            setRecordedVideo({
              uri: someFakeUri,
            });
          }
        })
        .finally(() => setIsRecording(false));
</code>```

Body:
expo-camera is not supported by any of the simulators.  Therefore, when using this component in development & on the simulator, it results in an error and data is not stored as it would on the actual device.

Possible Unhandled Promise Rejection.  Error:  Video recording is not supported on a simulator

This is causing an issue in terms of verifying functionality and the "happy path".

I added an interim check for a video field and then return the basic camera, so at least our flow works, but I don't think it's a long terms solution:

 if (
      process.env.NODE_ENV === 'development' &&
      field.kind === ComponentTypes.VIDEO
    ) {
       return <CameraImage />
    }

How do you work around this intended behavior, in terms of getting data to store?  All I can think of doing for this is adding a catch and faking the data:

 cameraRef?.current
        .recordAsync(options)
        .then(vid => {
          console.log({ vid });

          setRecordedVideo(vid);
        })
        .catch(() => {
          if (process.env.NODE_ENV === 'development') {
            setRecordedVideo({
              uri: someFakeUri,
            });
          }
        })
        .finally(() => setIsRecording(false));


问:
How to verify user credentials against companys LDAP-Server via PHP (Server is accessible via LDAP Admin)?
I am trying to write an application in php, that verifies user-credentials against the companys ldap-server. The application runs on a virtual (Debian) Server located inside the company.

What I have accomplished so far is installing "LDAP Admin" on a PC inside the company and successfully connecting to the ldap-Server.

The Connection Properties that worked where like this:

Host: ldapadit.company.de
Port: 389
Version: 3
Base: DC=ad,DC=it,DC=company,DC=de
GSS-API selected
SASL: works with or without SASL checked
Account: my company-account credentials or checkbox "use current user credentials"

Simple authentication with or without SSL/TLS throws an error.

What i tried to connect via php was this:

```<code>$ds = ldap_connect("ldapadit.company.de");
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

if ($ds) {

    $ldap_dn = 'cn=username,dc=ad,dc=it,dc=company,dc=de';   <= I took base from LDAP-Admin
    $ldap_password = 'password';

    $r = ldap_sasl_bind($ds,$ldap_dn,$ldap_password);  <= ldap_sasl_bind because of GSS-API in LDAP-Admin

    if($r) {
        echo 'binding successful<br>';
    }
    else {
        echo 'binding NOT successful<br>';
    }
}
else {
    echo 'ldap_connect failed';
}
</code>```

My problem:
$ds is always true. It is always of type "resource" with the value "Resource #1" or "Resource #2", whatever I give to ldap_connect() as uri. (I already learned, that ldap_connect() does not in fact makes any connections, instead only checks if parameters are plausible. But this behaviour doesn't make much sense to me any way).

$r is always false, meaning the binding always fails.

Now I don't have a clue how to get closer to the core of the problem. Or at least how to get any error-message that woukld lead me in the right direction.

What I tried:

pinging ldapadit.company.de => succesful

binding with ldap_bind() <= failed

verifying function ldap_sasl_bind() is available <= function exists

giving ldap-uri with ldap://[] ldaps://[] and port 389/636 <= no difference

playing with the base-parameters <= no difference

Any hint, what to check next is highly welcome

Body:
I am trying to write an application in php, that verifies user-credentials against the companys ldap-server. The application runs on a virtual (Debian) Server located inside the company.

What I have accomplished so far is installing "LDAP Admin" on a PC inside the company and successfully connecting to the ldap-Server.

The Connection Properties that worked where like this:

Host: ldapadit.company.de
Port: 389
Version: 3
Base: DC=ad,DC=it,DC=company,DC=de
GSS-API selected
SASL: works with or without SASL checked
Account: my company-account credentials or checkbox "use current user credentials"

Simple authentication with or without SSL/TLS throws an error.

What i tried to connect via php was this:

$ds = ldap_connect("ldapadit.company.de");
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

if ($ds) {

    $ldap_dn = 'cn=username,dc=ad,dc=it,dc=company,dc=de';   <= I took base from LDAP-Admin
    $ldap_password = 'password';

    $r = ldap_sasl_bind($ds,$ldap_dn,$ldap_password);  <= ldap_sasl_bind because of GSS-API in LDAP-Admin

    if($r) {
        echo 'binding successful
';
    }
    else {
        echo 'binding NOT successful
';
    }
}
else {
    echo 'ldap_connect failed';
}

My problem:
$ds is always true. It is always of type "resource" with the value "Resource #1" or "Resource #2", whatever I give to ldap_connect() as uri. (I already learned, that ldap_connect() does not in fact makes any connections, instead only checks if parameters are plausible. But this behaviour doesn't make much sense to me any way).

$r is always false, meaning the binding always fails.

Now I don't have a clue how to get closer to the core of the problem. Or at least how to get any error-message that woukld lead me in the right direction.

What I tried:

pinging ldapadit.company.de => succesful

binding with ldap_bind() <= failed

verifying function ldap_sasl_bind() is available <= function exists

giving ldap-uri with ldap://[] ldaps://[] and port 389/636 <= no difference

playing with the base-parameters <= no difference

Any hint, what to check next is highly welcome


问:
dynamic filepath serach for image slider
I am new to js and tried to build an image slider for the web. I tried to stich together two bits of cod which work fine seperately but not togehther and I' am wondering why?

The slider function works fine as long as I input the value for the var slideNum directly as a number so: "var slideNum = 4"

But I Would like js to count the numbers of img. files in the src folder and adjust the slidNum dynamically. Any idea what I am doing wrong?

thx

```<code>const fs = require('fs');
var length = fs.readdirSync('../recursion/img').length;

function slide(n){

    var slideNum = length
    var imgNames = [
      "null",
      "img_1.jpeg",
      "img_2.jpeg",
      "img_3.jpeg",
      "img_4.jpeg",
      "img_5.jpeg",
      "img_6.jpeg",
      "img_7.jpeg",
      "img_8.jpeg",
      "img_9.jpeg",
      "img_10.jpeg",
      "img_11.jpeg",
      "img_12.jpeg",
      "img_13.jpeg",
      "img_14.jpeg",
      "img_15.jpeg",
      "img_16.jpeg",
      "img_17.jpeg",
      "img_18.jpeg",
      "img_19.jpeg",
      "img_20.jpeg",
    ];

    var selector = 'div#slider.slider img.slider-img';
    var imgName = $(selector)[0].outerHTML.split('img_');
    var imgNum = parseInt(imgName[1].split('.')[0]);
    if (n == 0) {
      var newName = (imgNum != 1) ? imgNames[imgNum - 1] : imgNames[imgNum + ((slideNum)-1)];
      $(selector)[0].outerHTML = getPath(imgName[0], newName);
    }
    else if (n == 1 ){
      var newName = (imgNum != slideNum) ? imgNames[imgNum + 1] : imgNames[imgNum - (slideNum-1)];
      $(selector)[0].outerHTML = getPath(imgName[0], newName);
    }
  }
  function getPath(path, imgName){
    return (path + imgName + "\">");
  }

</code>```

I tried to rearrange the bits of code in all possible manners but nothing worked.

Body:
I am new to js and tried to build an image slider for the web. I tried to stich together two bits of cod which work fine seperately but not togehther and I' am wondering why?

The slider function works fine as long as I input the value for the var slideNum directly as a number so: "var slideNum = 4"

But I Would like js to count the numbers of img. files in the src folder and adjust the slidNum dynamically. Any idea what I am doing wrong?

thx

const fs = require('fs');
var length = fs.readdirSync('../recursion/img').length;

function slide(n){

    var slideNum = length
    var imgNames = [
      "null",
      "img_1.jpeg",
      "img_2.jpeg",
      "img_3.jpeg",
      "img_4.jpeg",
      "img_5.jpeg",
      "img_6.jpeg",
      "img_7.jpeg",
      "img_8.jpeg",
      "img_9.jpeg",
      "img_10.jpeg",
      "img_11.jpeg",
      "img_12.jpeg",
      "img_13.jpeg",
      "img_14.jpeg",
      "img_15.jpeg",
      "img_16.jpeg",
      "img_17.jpeg",
      "img_18.jpeg",
      "img_19.jpeg",
      "img_20.jpeg",
    ];

    var selector = 'div#slider.slider img.slider-img';
    var imgName = $(selector)[0].outerHTML.split('img_');
    var imgNum = parseInt(imgName[1].split('.')[0]);
    if (n == 0) {
      var newName = (imgNum != 1) ? imgNames[imgNum - 1] : imgNames[imgNum + ((slideNum)-1)];
      $(selector)[0].outerHTML = getPath(imgName[0], newName);
    }
    else if (n == 1 ){
      var newName = (imgNum != slideNum) ? imgNames[imgNum + 1] : imgNames[imgNum - (slideNum-1)];
      $(selector)[0].outerHTML = getPath(imgName[0], newName);
    }
  }
  function getPath(path, imgName){
    return (path + imgName + "\">");
  }

I tried to rearrange the bits of code in all possible manners but nothing worked.


问:
E/StorageException Firebase, Cloud Firestore, Firestore Database
Android Studio tells me that the method of startActivityForResult and OnAcitvityResult are "deprecated", and I am unable to update the methods for this code, this code is a post publication in Firebase Cloud storage, and I use the method to upload it in jpeg format through Glide to Cloud Storage and it gives me an error in those methods, I have tried updating AcitivityResultLauncher but well I have commented before, I am unable to update it, could I change my API to a previous version or does anyone know how to update it, can anyone help me?

The console input this:
E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
E/StorageException: The server has terminated the upload session
java.io.IOException: The server has terminated the upload session
at com.google.firebase.storage.UploadTask.serverStateValid(UploadTask.java:358)

```<code>

    Uri imageUri;
    String myUrl = "";
    StorageTask uploadTask;
    StorageReference storageReference;

    ImageView ibAdjuntarFoto;
    ImageView imagePost;
    EditText etTitulo;
    EditText etDescripcion;
    Button btnPost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_publicar_post, container, false);

        ibAdjuntarFoto = view.findViewById(R.id.ibAdjuntarFoto);
        imagePost = view.findViewById(R.id.ivFoto);
        etTitulo = view.findViewById(R.id.etTituloPostFragment);
        etDescripcion = view.findViewById(R.id.etDescripcion);
        btnPost = view.findViewById(R.id.btnPost);

        storageReference = FirebaseStorage.getInstance().getReference("Posts");

        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etTitulo.getText().toString().isEmpty()) {
                    Toast.makeText(getContext(), "Debes escribir un título", Toast.LENGTH_SHORT).show();
                } else {
                    if (etDescripcion.getText().toString().isEmpty()) {
                        Toast.makeText(getContext(), "Debes escribir una descripción", Toast.LENGTH_SHORT).show();
                    } else {
                            uploadImage();
                        }
                    }
                }
        });

        ibAdjuntarFoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                startActivityForResult(Intent.createChooser(intent, "Complete la acción usando"), 1);
            }
        });

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            imageUri = data.getData();
            Glide.with(imagePost.getContext()).load(imageUri)
                    .into(imagePost);
        }
    }

    private void uploadImage() {
        ProgressDialog progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Publicando post");
        progressDialog.show();

        if (imageUri != null) {
            StorageReference fileReference = storageReference.child(System.currentTimeMillis() + "");
            uploadTask = fileReference.putFile(imageUri);
            uploadTask.continueWithTask(new Continuation() {
                @Override
                public Object then(@NonNull Task task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }
                    return fileReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUri = task.getResult();
                        myUrl = downloadUri.toString();

                        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");

                        String postId = reference.push().getKey();

                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("id", postId);
                        hashMap.put("titulo", etTitulo.getText().toString());
                        hashMap.put("descripcion", etDescripcion.getText().toString());
                        hashMap.put("imageUrl", myUrl);
                        hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());

                        reference.child(postId).setValue(hashMap);
                        progressDialog.dismiss();
                        startActivity(new Intent(getActivity(), MainActivity.class));

                    } else {
                        Toast.makeText(getContext(), "Error!", Toast.LENGTH_SHORT).show();
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(getContext(), "Erroor!" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            });
        } else {
            Toast.makeText(getContext(), "No has seleccionado ninguna imagen", Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
        }
    }

}
</code>```

Idk if the problem is the decrepted method but when i tried to upload the image the error starts, idk how to fix this problem someone can help me?

Body:
Android Studio tells me that the method of startActivityForResult and OnAcitvityResult are "deprecated", and I am unable to update the methods for this code, this code is a post publication in Firebase Cloud storage, and I use the method to upload it in jpeg format through Glide to Cloud Storage and it gives me an error in those methods, I have tried updating AcitivityResultLauncher but well I have commented before, I am unable to update it, could I change my API to a previous version or does anyone know how to update it, can anyone help me?

The console input this:
E/StorageException: StorageException has occurred.
Object does not exist at location.
Code: -13010 HttpResult: 404
E/StorageException: The server has terminated the upload session
java.io.IOException: The server has terminated the upload session
at com.google.firebase.storage.UploadTask.serverStateValid(UploadTask.java:358)

    Uri imageUri;
    String myUrl = "";
    StorageTask uploadTask;
    StorageReference storageReference;

    ImageView ibAdjuntarFoto;
    ImageView imagePost;
    EditText etTitulo;
    EditText etDescripcion;
    Button btnPost;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_publicar_post, container, false);

        ibAdjuntarFoto = view.findViewById(R.id.ibAdjuntarFoto);
        imagePost = view.findViewById(R.id.ivFoto);
        etTitulo = view.findViewById(R.id.etTituloPostFragment);
        etDescripcion = view.findViewById(R.id.etDescripcion);
        btnPost = view.findViewById(R.id.btnPost);

        storageReference = FirebaseStorage.getInstance().getReference("Posts");

        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (etTitulo.getText().toString().isEmpty()) {
                    Toast.makeText(getContext(), "Debes escribir un título", Toast.LENGTH_SHORT).show();
                } else {
                    if (etDescripcion.getText().toString().isEmpty()) {
                        Toast.makeText(getContext(), "Debes escribir una descripción", Toast.LENGTH_SHORT).show();
                    } else {
                            uploadImage();
                        }
                    }
                }
        });

        ibAdjuntarFoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                startActivityForResult(Intent.createChooser(intent, "Complete la acción usando"), 1);
            }
        });

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
            imageUri = data.getData();
            Glide.with(imagePost.getContext()).load(imageUri)
                    .into(imagePost);
        }
    }

    private void uploadImage() {
        ProgressDialog progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Publicando post");
        progressDialog.show();

        if (imageUri != null) {
            StorageReference fileReference = storageReference.child(System.currentTimeMillis() + "");
            uploadTask = fileReference.putFile(imageUri);
            uploadTask.continueWithTask(new Continuation() {
                @Override
                public Object then(@NonNull Task task) throws Exception {
                    if (!task.isSuccessful()) {
                        throw task.getException();
                    }
                    return fileReference.getDownloadUrl();
                }
            }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                @Override
                public void onComplete(@NonNull Task<Uri> task) {
                    if (task.isSuccessful()) {
                        Uri downloadUri = task.getResult();
                        myUrl = downloadUri.toString();

                        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Posts");

                        String postId = reference.push().getKey();

                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("id", postId);
                        hashMap.put("titulo", etTitulo.getText().toString());
                        hashMap.put("descripcion", etDescripcion.getText().toString());
                        hashMap.put("imageUrl", myUrl);
                        hashMap.put("publisher", FirebaseAuth.getInstance().getCurrentUser().getUid());

                        reference.child(postId).setValue(hashMap);
                        progressDialog.dismiss();
                        startActivity(new Intent(getActivity(), MainActivity.class));

                    } else {
                        Toast.makeText(getContext(), "Error!", Toast.LENGTH_SHORT).show();
                    }
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(getContext(), "Erroor!" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    progressDialog.dismiss();
                }
            });
        } else {
            Toast.makeText(getContext(), "No has seleccionado ninguna imagen", Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
        }
    }

}

Idk if the problem is the decrepted method but when i tried to upload the image the error starts, idk how to fix this problem someone can help me?


问:
namedJdbcTemplate.update not working for list of string
I am trying to use named jdbctemplate.update to fire a delete query but somehow this query is not working.

This is my code

Order looks something like this

```<code>public class Order {
  private Long cuId;
  private String supplierType;
  private String customerType;
  private String orderType;
}

final List<Order> ordersStuckInNewStatus; //defined like this

//main code starts here

List<String> cuIds=
      ordersStuckInNewStatus.stream()
          .map(Order::getCuId)
          .map(id -> String.format("'%s'", id))
          .collect(Collectors.toList());

 syso(cuIds)      //Output:- ['193111000000000451']

  SqlParameterSource parameters = new MapSqlParameterSource("cuIds", cuIds);

syso(parameters )      //Output:- MapSqlParameterSource {cuIds=['193111000000000451']}

  int deleteCount = 0;
  String sql = "DELETE FROM OLCM.REJECTED_EVENT where entity_id IN (:cuIds)";
  deleteCount = namedJdbcTemplate.update(sql, parameters);

  log.info("Delete Count:[{}]", deleteCount);

</code>```

This is how many logs gets printed . No compilation error

```<code>Query:["DELETE FROM OLCM.REJECTED_EVENT where entity_id IN (?)"], Params:[('193111000000000451')]
Delete Count:[0]
</code>```

Even though the correct query gets fired but somehow the reords did not get deleted. The records do exists in db.

Note:

entity_id is varchar

Instead of List<String> cuid if i use the below code it works

List<Long> cuIds=ordersStuckInNewStatus.stream().map(Order::getCuId).collect(Collectors.toList());

Any reason why this is not working for List<String> but works for List<Long>

Body:
I am trying to use named jdbctemplate.update to fire a delete query but somehow this query is not working.

This is my code

Order looks something like this

public class Order {
  private Long cuId;
  private String supplierType;
  private String customerType;
  private String orderType;
}

final List<Order> ordersStuckInNewStatus; //defined like this

//main code starts here

List<String> cuIds=
      ordersStuckInNewStatus.stream()
          .map(Order::getCuId)
          .map(id -> String.format("'%s'", id))
          .collect(Collectors.toList());

 syso(cuIds)      //Output:- ['193111000000000451']

  SqlParameterSource parameters = new MapSqlParameterSource("cuIds", cuIds);

syso(parameters )      //Output:- MapSqlParameterSource {cuIds=['193111000000000451']}

  int deleteCount = 0;
  String sql = "DELETE FROM OLCM.REJECTED_EVENT where entity_id IN (:cuIds)";
  deleteCount = namedJdbcTemplate.update(sql, parameters);

  log.info("Delete Count:[{}]", deleteCount);

This is how many logs gets printed . No compilation error

Query:["DELETE FROM OLCM.REJECTED_EVENT where entity_id IN (?)"], Params:[('193111000000000451')]
Delete Count:[0]

Even though the correct query gets fired but somehow the reords did not get deleted. The records do exists in db.

Note:

entity_id is varchar

Instead of List<String> cuid if i use the below code it works

List<Long> cuIds=ordersStuckInNewStatus.stream().map(Order::getCuId).collect(Collectors.toList());

Any reason why this is not working for List<String> but works for List<Long>


问:
White Blank Screen after using import { Link } from "react-router-dom";
This is exactly the code I copied in the video tutorial but I don't know why I got a blank white screen on my browser while the other (original) code doesn't get a blank screen after importing the { Link } from "react-router-dom"; How do you fix this? I can't find any solutions.

Here is my App.js

```<code>import React from "react";
import Navbar from "./components/Nav/Navbar";

function App () {
  return (

    <div>
    <Navbar/>
    </div>

  );

}

export default App;
</code>```

This is my Navbar.jsx

```<code>import React from "react";
import { Link } from "react-router-dom";
import Logo from "../../assets/Logo.png";

const Navbar = () => {
    return (
    <nav className="bg-white">
        <div className="flex items-center font-medium justify-around">
        <div>
            <img src={Logo} alt="logo" className="md:cursor-pointer" />
        </div>
        <ul>
            <li>
                <Link to="/" className="py-7 px-3 inline-block">
                Home
                </Link>
            </li>
        </ul>
        </div>
    </nav>
    );
};

export default Navbar;
</code>```

Body:
This is exactly the code I copied in the video tutorial but I don't know why I got a blank white screen on my browser while the other (original) code doesn't get a blank screen after importing the { Link } from "react-router-dom"; How do you fix this? I can't find any solutions.

Here is my App.js

import React from "react";
import Navbar from "./components/Nav/Navbar";

function App () {
  return (

    <Navbar/>

  );

}

export default App;

This is my Navbar.jsx

import React from "react";
import { Link } from "react-router-dom";
import Logo from "../../assets/Logo.png";

const Navbar = () => {
    return (

                <Link to="/" className="py-7 px-3 inline-block">
                Home
                </Link>

    );
};

export default Navbar;


问:
cmake targets from find_package are not propagated to siblings
I am unsure about the scope of a cmake target added in a subdirectory. I created the following structure

```<code>|---root
|   main_which_uses_lib2.cpp
|   CMakeLists.txt
|---|---first child
|       CMakeLists.txt
|       sourcefile_for_lib1.cpp
|---|---second child
|       CMakeLists.txt
|       sourcefile_for_lib2_which_uses_lib1.cpp
</code>```

second child library references first child library. main uses second child library. Both libraries are added to main through main directory via

```<code>add_subdirectory
</code>```

This compiles fine. Does it do that by design or by coincidence? I am working on another project where the CMakeLists.txt of lib1 calls find_package. find_package creates several targets which are not propagated to lib2. The setup causes errors in the cmake setup. More specifically, it populates the interface definitions with generator expressions like the following

```<code>INTERFACE_COMPILE_DEFINITIONS "\$<TARGET_PROPERTY:torch_cpu,INTERFACE_COMPILE_DEFINITIONS>"
</code>```

I link against the corresponding libraries in lib1 publicly, e.g. via

```<code>target_link_libraries(lib1 PUBLIC ${TORCH_LIBRARIES})
</code>```

which means everything that is in the interface libraries/compile definitions/include directories of ${TORCH_LIBRARIES} should be used by anything that uses target_link_libraries on lib1. While the definitions do carry over to lib2, the targets are gone: I get an error message like

```<code>torch_cpu is not a target.
</code>```

Variables in cmake generally have a local scope, however targets seem to work differently.

I did not find an explanation for this behaviour and would appreciate any input

Body:
I am unsure about the scope of a cmake target added in a subdirectory. I created the following structure

|---root
|   main_which_uses_lib2.cpp
|   CMakeLists.txt
|---|---first child
|       CMakeLists.txt
|       sourcefile_for_lib1.cpp
|---|---second child
|       CMakeLists.txt
|       sourcefile_for_lib2_which_uses_lib1.cpp

second child library references first child library. main uses second child library. Both libraries are added to main through main directory via

add_subdirectory

This compiles fine. Does it do that by design or by coincidence? I am working on another project where the CMakeLists.txt of lib1 calls find_package. find_package creates several targets which are not propagated to lib2. The setup causes errors in the cmake setup. More specifically, it populates the interface definitions with generator expressions like the following

INTERFACE_COMPILE_DEFINITIONS "\$<TARGET_PROPERTY:torch_cpu,INTERFACE_COMPILE_DEFINITIONS>"

I link against the corresponding libraries in lib1 publicly, e.g. via

target_link_libraries(lib1 PUBLIC ${TORCH_LIBRARIES})

which means everything that is in the interface libraries/compile definitions/include directories of ${TORCH_LIBRARIES} should be used by anything that uses target_link_libraries on lib1. While the definitions do carry over to lib2, the targets are gone: I get an error message like

torch_cpu is not a target.

Variables in cmake generally have a local scope, however targets seem to work differently.

I did not find an explanation for this behaviour and would appreciate any input