问:
Firebase + android method for generating a unique token for each user of my application independent from the device?
Good evening everyone, I use firebase authentication and I wish that at registration, a unique token for each user is generated so that I can do other things. The problem is that all the users I created on an X device, all have the same token. here is the code that i use:

```<code>        mAuth.createUserWithEmailAndPassword(email,pswd).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
            @Override
            public void onSuccess(AuthResult authResult) {
                                    // String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

                FirebaseInstanceId.getInstance().getInstanceId()
                        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                            @Override
                            public void onComplete(@NonNull final Task<InstanceIdResult> task) {
                                if (task.isSuccessful()) {

                                    final FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
                                    if (mFirebaseUser != null) {
                                        String newuser = mFirebaseUser.getUid(); //Do what you need to do with the id
                                        Log.d(TAG, " COMPARAISON " + newuser);

                                        mFirebaseUser.getIdToken(true).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
                                            @Override
                                            public void onSuccess(GetTokenResult result) {
                                                String token = result.getToken();
                                                //Do whatever
                                                Log.d(TAG, "GetTokenResult result = " + token);
                                                //String token = FirebaseInstanceId.getInstance().getToken();

                                                progressBar.setVisibility(View.VISIBLE);
                                                register.setVisibility(View.GONE);
                                                mAuth = FirebaseAuth.getInstance();

                                                String uid = mFirebaseUser.getUid();
                                                Log.d(TAG, " COMPARAION2" + uid);
                                                // String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

                                                Log.d(TAG, "Token utilisateur" + token);
                                                // Send token to your backend via HTTPS
                                                Log.d(TAG, " TOKEN " + token);
                                                Log.d(TAG, " UID DU USER" + uid);
                                                Map<String, Object> userdata = new HashMap<>();
                                                userdata.put("uid", uid);
                                                userdata.put("fln", fln);
                                                userdata.put("idToken", token);
                                                userdata.put("email", email);
                                                userdata.put("password", pswd);
                                                Log.d(TAG, "FULLNAME: " + fln);
                                                SharedPreferences.Editor editor = prefEnreg.edit();
                                                editor.putString("FULLNAME", fln);
                                                editor.putString("tok", token);
                                                editor.apply();
                                                db.collection("Users2").document(uid).set(userdata).addOnCompleteListener(new OnCompleteListener<Void>() {
                                                    @Override
                                                    public void onComplete(@NonNull Task<Void> task) {
                                                        Toast.makeText(getApplicationContext(), "Register User", Toast.LENGTH_SHORT).show();
                                                        register.setVisibility(View.VISIBLE);
                                                        progressBar.setVisibility(View.GONE);
                                                        Intent intent13 = new Intent(MainActivity.this, FriendList.class);
                                                        startActivity(intent13);
                                                        mail.setText("");
                                                        phone.setText("");
                                                        fllname.setText("");
                                                        passwd.setText("");

                                                    }

                                                });

                                            }
                                        });

                                    } else{
                                        Toast.makeText(getApplicationContext(),"Une erreur inconnue s'est produite",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }

                        });
                  }
             })
</code>```

I searched again and again on the net google, youtube, blog ... most of the solutions they give, it is to have the token according to the devices and like that, it is not good. I want to use the tokens after to send timely notifications

答:
The token returned by FirebaseInstanceId.getInstance().getInstanceId() is unrelated to the user of the app.

If you want to generate a new instance ID for each user, you'll want to clear the existing instance ID when the user signs out, or a new user signs in.

See my answer here for a longer explanation: When to register an FCM token for a user

Also see:

How to handle multiple Firebase FCM tokens per user?

Receiving the same token for different users when using firebase messaging

Is FCM (firebase cloud messaging) Token for one device or for one account?

Body:
Good evening everyone, I use firebase authentication and I wish that at registration, a unique token for each user is generated so that I can do other things. The problem is that all the users I created on an X device, all have the same token. here is the code that i use:

        mAuth.createUserWithEmailAndPassword(email,pswd).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
            @Override
            public void onSuccess(AuthResult authResult) {
                                    // String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

                FirebaseInstanceId.getInstance().getInstanceId()
                        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                            @Override
                            public void onComplete(@NonNull final Task<InstanceIdResult> task) {
                                if (task.isSuccessful()) {

                                    final FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
                                    if (mFirebaseUser != null) {
                                        String newuser = mFirebaseUser.getUid(); //Do what you need to do with the id
                                        Log.d(TAG, " COMPARAISON " + newuser);

                                        mFirebaseUser.getIdToken(true).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() {
                                            @Override
                                            public void onSuccess(GetTokenResult result) {
                                                String token = result.getToken();
                                                //Do whatever
                                                Log.d(TAG, "GetTokenResult result = " + token);
                                                //String token = FirebaseInstanceId.getInstance().getToken();

                                                progressBar.setVisibility(View.VISIBLE);
                                                register.setVisibility(View.GONE);
                                                mAuth = FirebaseAuth.getInstance();

                                                String uid = mFirebaseUser.getUid();
                                                Log.d(TAG, " COMPARAION2" + uid);
                                                // String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

                                                Log.d(TAG, "Token utilisateur" + token);
                                                // Send token to your backend via HTTPS
                                                Log.d(TAG, " TOKEN " + token);
                                                Log.d(TAG, " UID DU USER" + uid);
                                                Map<String, Object> userdata = new HashMap<>();
                                                userdata.put("uid", uid);
                                                userdata.put("fln", fln);
                                                userdata.put("idToken", token);
                                                userdata.put("email", email);
                                                userdata.put("password", pswd);
                                                Log.d(TAG, "FULLNAME: " + fln);
                                                SharedPreferences.Editor editor = prefEnreg.edit();
                                                editor.putString("FULLNAME", fln);
                                                editor.putString("tok", token);
                                                editor.apply();
                                                db.collection("Users2").document(uid).set(userdata).addOnCompleteListener(new OnCompleteListener<Void>() {
                                                    @Override
                                                    public void onComplete(@NonNull Task<Void> task) {
                                                        Toast.makeText(getApplicationContext(), "Register User", Toast.LENGTH_SHORT).show();
                                                        register.setVisibility(View.VISIBLE);
                                                        progressBar.setVisibility(View.GONE);
                                                        Intent intent13 = new Intent(MainActivity.this, FriendList.class);
                                                        startActivity(intent13);
                                                        mail.setText("");
                                                        phone.setText("");
                                                        fllname.setText("");
                                                        passwd.setText("");

                                                    }

                                                });

                                            }
                                        });

                                    } else{
                                        Toast.makeText(getApplicationContext(),"Une erreur inconnue s'est produite",Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }

                        });
                  }
             })

I searched again and again on the net google, youtube, blog ... most of the solutions they give, it is to have the token according to the devices and like that, it is not good. I want to use the tokens after to send timely notifications


来源: stackexchange

问:
Accessing ThreadLocal values from a method which a thread has invoked?
I have used ThreadLocal very little, however I need to know about it for work reasons. I did search on this, and came to know about the concept.

I made sample example below:

ThreadLocalMain.java -> Main driver program

```<code>package com.example.threads.threadlocal;

public class ThreadLocalMain {
    public static void main(String[] args) throws InterruptedException {
        Thread1 t1 = new Thread1("First");
        Thread1 t2 = new Thread1("Second");
        Thread1 t3 = new Thread1("Third");

        t1.start();
        t2.start();
        t3.start();
    }
}
</code>```

Thread1.java  -> Which uses ThreadLocal

```<code>package com.example.threads.threadlocal;

import com.example.threads.threadlocal.utils.Util1;

public class Thread1 extends Thread {

    private static Integer unique_id = 0;
    @SuppressWarnings("rawtypes")
    private static ThreadLocal tl = new ThreadLocal() {

        @Override
        public Integer initialValue() {
            return (++unique_id);
        }
    };

    public Thread1(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println("Current thread is --> " + Thread.currentThread().getName() + " with thread local value as --> " + tl.get());

        Util1 u1 = new Util1();
        u1.display(tl);
    }
</code>```

Util.java --> In this I want to check Thread's ThreadLocal value

```<code>
package com.example.threads.threadlocal.utils;

public class Util1 {
    public void display(ThreadLocal tl) {
        System.out.println("Inside Util1#display() method, executed by " + Thread.currentThread().getName()
                + " my thread local value is -->  " + tl.get());
    }
}
</code>```

I have main driver program, which creates 3-thread, and in thread class there is ThreadLocal which saves values for current thread.

My question is how can we print the value of ThreadLocal for current thread which has invoked a method on some object. In this case the object is Util. I was able to do by passing the instance of ThreadLocal into Util's display() method.

So my question:

Is it possible to print the value of ThreadLocal in a method without passing ThreadLocal reference to the method? Is it feasible at all? Is my method not the way it is intended to use ThreadLocal.

答:
As far as you do not execute code in different threads in display method, you can pass value of thread local instead the thread local to display method. Following code will lead the same result

```<code>@Override
public void run() {
      System.out.println("Current thread is --> " + Thread.currentThread().getName() + " with thread local value as --> " + tl.get());

    Util u1 = new Util();
    u1.display(tl.get());
}

public class Util {
  public void display(Object value) {
    System.out.println("Inside Util1#display() method, executed by " + Thread.currentThread().getName()
            + " my thread local value is -->  " + value);
}
</code>```

}

ContentLicense: CC BY-SA 4.0

Body:
I have used ThreadLocal very little, however I need to know about it for work reasons. I did search on this, and came to know about the concept.

I made sample example below:

ThreadLocalMain.java -> Main driver program

package com.example.threads.threadlocal;

public class ThreadLocalMain {
    public static void main(String[] args) throws InterruptedException {
        Thread1 t1 = new Thread1("First");
        Thread1 t2 = new Thread1("Second");
        Thread1 t3 = new Thread1("Third");

        t1.start();
        t2.start();
        t3.start();
    }
}

Thread1.java  -> Which uses ThreadLocal

package com.example.threads.threadlocal;

import com.example.threads.threadlocal.utils.Util1;

public class Thread1 extends Thread {

    private static Integer unique_id = 0;
    @SuppressWarnings("rawtypes")
    private static ThreadLocal tl = new ThreadLocal() {

        @Override
        public Integer initialValue() {
            return (++unique_id);
        }
    };

    public Thread1(String name) {
        super(name);
    }

    @Override
    public void run() {
        System.out.println("Current thread is --> " + Thread.currentThread().getName() + " with thread local value as --> " + tl.get());

        Util1 u1 = new Util1();
        u1.display(tl);
    }

Util.java --> In this I want to check Thread's ThreadLocal value

package com.example.threads.threadlocal.utils;

public class Util1 {
    public void display(ThreadLocal tl) {
        System.out.println("Inside Util1#display() method, executed by " + Thread.currentThread().getName()
                + " my thread local value is -->  " + tl.get());
    }
}

I have main driver program, which creates 3-thread, and in thread class there is ThreadLocal which saves values for current thread.

My question is how can we print the value of ThreadLocal for current thread which has invoked a method on some object. In this case the object is Util. I was able to do by passing the instance of ThreadLocal into Util's display() method.

So my question:

Is it possible to print the value of ThreadLocal in a method without passing ThreadLocal reference to the method? Is it feasible at all? Is my method not the way it is intended to use ThreadLocal.

Body:
As far as you do not execute code in different threads in display method, you can pass value of thread local instead the thread local to display method. Following code will lead the same result

@Override
public void run() {
      System.out.println("Current thread is --> " + Thread.currentThread().getName() + " with thread local value as --> " + tl.get());

    Util u1 = new Util();
    u1.display(tl.get());
}

public class Util {
  public void display(Object value) {
    System.out.println("Inside Util1#display() method, executed by " + Thread.currentThread().getName()
            + " my thread local value is -->  " + value);
}

}


问:
How to extract values from columns in CSV using a loop and use them in email body using python?
This is the information that needs to be mailed

I am trying to send the values of "id" and "desc" to the emails that in column B. I used a for loop to go through the email list and send emails, however, I am unable to attach the values of "id" and "desc" in my email.

Plus, I want the "assigned to" column to be filled with the email id that the "id" is sent to.

```<code>import pandas as pd
import win32com.client

e = pd.read_csv('combo.csv')
emails = e['Emails'].values
ticket_number = e['id'].values
desc_value = e['desc'].values
for i in emails, ticket_number, desc_value:
    outlook = win32com.client.Dispatch("Outlook.Application")
    message = 'Hello the ticket number {ticket_number} with the Description {desc_value} has been assigned to you.'
    mail = outlook.CreateItem(0)
    mail.To = i
    mail.Subject = 'This is a test'
    mail.HTMLBody = message
    mail.Send()
</code>```

Can someone guide me as to how
1. Use the values to send the email.
2. Add the emails in the "assigned to" column once the email is sent.

答:
Try this:

```<code>import pandas as pd
import win32com.client

def send_mail(email, ticket_number, desc_value):
    outlook = win32com.client.Dispatch("Outlook.Application")
    message = f'Hello the ticket number {ticket_number} with the Description {desc_value} has been assigned to you.'
    mail = outlook.CreateItem(0)
    mail.To = email
    mail.Subject = 'This is a test'
    mail.HTMLBody = message
    mail.Send()

if __name__ == "__main__":
    df = pd.read_csv('combo.csv')
    df.apply(lambda row: send_mail(row['Emails'], row['id'], row['desc']), axis=1)
</code>```

or just make changes in your code:

```<code>import pandas as pd
import win32com.client

e = pd.read_csv('combo.csv')
emails = e['Emails'].values
ticket_number = e['id'].values
desc_value = e['desc'].values
for i in range(len(emails)):
    outlook = win32com.client.Dispatch("Outlook.Application")
    message = f'Hello the ticket number {ticket_number[i]} with the Description {desc_value[i]} has been assigned to you.'
    mail = outlook.CreateItem(0)
    mail.To = emails[i]
    mail.Subject = 'This is a test'
    mail.HTMLBody = message
    mail.Send()
</code>```

Body:
This is the information that needs to be mailed

I am trying to send the values of "id" and "desc" to the emails that in column B. I used a for loop to go through the email list and send emails, however, I am unable to attach the values of "id" and "desc" in my email.

Plus, I want the "assigned to" column to be filled with the email id that the "id" is sent to.

import pandas as pd
import win32com.client

e = pd.read_csv('combo.csv')
emails = e['Emails'].values
ticket_number = e['id'].values
desc_value = e['desc'].values
for i in emails, ticket_number, desc_value:
    outlook = win32com.client.Dispatch("Outlook.Application")
    message = 'Hello the ticket number {ticket_number} with the Description {desc_value} has been assigned to you.'
    mail = outlook.CreateItem(0)
    mail.To = i
    mail.Subject = 'This is a test'
    mail.HTMLBody = message
    mail.Send()

Can someone guide me as to how
1. Use the values to send the email.
2. Add the emails in the "assigned to" column once the email is sent.

Body:
Try this:

import pandas as pd
import win32com.client

def send_mail(email, ticket_number, desc_value):
    outlook = win32com.client.Dispatch("Outlook.Application")
    message = f'Hello the ticket number {ticket_number} with the Description {desc_value} has been assigned to you.'
    mail = outlook.CreateItem(0)
    mail.To = email
    mail.Subject = 'This is a test'
    mail.HTMLBody = message
    mail.Send()

if __name__ == "__main__":
    df = pd.read_csv('combo.csv')
    df.apply(lambda row: send_mail(row['Emails'], row['id'], row['desc']), axis=1)

or just make changes in your code:

import pandas as pd
import win32com.client

e = pd.read_csv('combo.csv')
emails = e['Emails'].values
ticket_number = e['id'].values
desc_value = e['desc'].values
for i in range(len(emails)):
    outlook = win32com.client.Dispatch("Outlook.Application")
    message = f'Hello the ticket number {ticket_number[i]} with the Description {desc_value[i]} has been assigned to you.'
    mail = outlook.CreateItem(0)
    mail.To = emails[i]
    mail.Subject = 'This is a test'
    mail.HTMLBody = message
    mail.Send()


问:
Cannot send the body in postman
I have the following code:

```<code>@PostMapping()
    public ResponseEntity<Object> postAccounts(
            @RequestHeader(value = "client-id", required = true) String clientId,
            @RequestHeader(value = "X-client-Global-Id", required = false) String clientGlobalID,
            @RequestHeader(value = "Authorization", required = true) String authorization,
            @Valid @RequestBody(required = true) String inputContract, @RequestBody(required = true)String nameInput, @RequestBody(required = true) Boolean state) {

        return new ResponseEntity<>(inputContract, HttpStatus.OK);
    }

</code>```

When call this method by postman give me an error.

```<code>trace": "org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:217)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)\r\n\tat

</code>```

答:
You only can send an one RequestBody, if you want send more than one properties in the body. You must create an object

```<code>@PostMapping()
    public ResponseEntity<Object> postAccounts(
           //Other Headers...,
            @Valid @RequestBody(required = true) ObjectWithAllFields) {

        return new ResponseEntity<>(ObjectWithAllFields, HttpStatus.OK);
    }

</code>```

EDIT 1

And pls send your error trace.

Title: Cannot send the body in postman

Body:
I have the following code:

@PostMapping()
    public ResponseEntity<Object> postAccounts(
            @RequestHeader(value = "client-id", required = true) String clientId,
            @RequestHeader(value = "X-client-Global-Id", required = false) String clientGlobalID,
            @RequestHeader(value = "Authorization", required = true) String authorization,
            @Valid @RequestBody(required = true) String inputContract, @RequestBody(required = true)String nameInput, @RequestBody(required = true) Boolean state) {

        return new ResponseEntity<>(inputContract, HttpStatus.OK);
    }

When call this method by postman give me an error.

trace": "org.springframework.http.converter.HttpMessageNotReadableException: I/O error while reading input message; nested exception is java.io.IOException: Stream closed\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:217)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)\r\n\tat

Body:
You only can send an one RequestBody, if you want send more than one properties in the body. You must create an object

@PostMapping()
    public ResponseEntity<Object> postAccounts(
           //Other Headers...,
            @Valid @RequestBody(required = true) ObjectWithAllFields) {

        return new ResponseEntity<>(ObjectWithAllFields, HttpStatus.OK);
    }

EDIT 1

And pls send your error trace.


问:
How to match data based on a range of values
I have 2 genetic datasets where I am trying to find if a variant at a certain position in the genome (file1) is matching/found within the ranges any of my rows in another dataset (file2), then extract the matches found file 2 to merge with file 1. The one condition is that the matches are only searched for variants if they have the same chromosome. For example:

File1:

```<code>Chromosome    Position
1              3
1              47
2              10
3              2
</code>```

File2:

```<code>Chromosome    Start    End
1              101      102
1              40       50
2              40       50
3              20       22
</code>```

Expected output:

```<code>Chromosome    Start    End
1              40       50
#this is the only row from which a variant from file1 fits in its position range and is on the same chromosome
</code>```

Ideally, I would merge in the file1 variant to align with it's matched chromosome start and end position in file2 all in the same row, but I am new to R and stuck on the first step of trying to match the variant based on if it's position number is within the range of the second file. Currently I am trying to adapt:

```<code>dt1[ dt2, match := i.,ID  #including a made-up ID column for the sake of trying to adapt this code
     on = .(Chromosome, Position > Start, Position < End ) ]
</code>```

however this doesn't seem work, and beyond this I don't know how else to start. Any help on how to approach this would be appreciated

Data:

```<code>dput(file1)
structure(list(Chromosome = c(1L, 1L, 2L, 3L), Position = c(3L,
47L, 10L, 2L)), row.names = c(NA, -4L), class = c("data.table",
"data.frame"))

dput(file2)
structure(list(Chromosome = c(1L, 1L, 2L, 3L), Start = c(101L,
40L, 40L, 20L), End = c(102L, 50L, 50L, 22L)), row.names = c(NA,
-4L), class = c("data.table", "data.frame"))
</code>```

答:
You could use the tidyverse package to do some recoding and get the chromosomes where its Position value is between the Start and End.

```<code>library(tidyverse)

df<-file1 %>%
  # Join by Chromosome, it will duplicate each Position by Start and End Values
  left_join(file2,
            by = "Chromosome") %>%
  # Create a new column to indicate if the Position is between Start and End values
  mutate(isRange = Position >= Start & Position <= End) %>%
  # Filter to stay with only the chromosomes where the previous condition is met
  filter(isRange)
</code>```

Body:
I have 2 genetic datasets where I am trying to find if a variant at a certain position in the genome (file1) is matching/found within the ranges any of my rows in another dataset (file2), then extract the matches found file 2 to merge with file 1. The one condition is that the matches are only searched for variants if they have the same chromosome. For example:

File1:

Chromosome    Position
1              3
1              47
2              10
3              2

File2:

Chromosome    Start    End
1              101      102
1              40       50
2              40       50
3              20       22

Expected output:

Chromosome    Start    End
1              40       50
#this is the only row from which a variant from file1 fits in its position range and is on the same chromosome

Ideally, I would merge in the file1 variant to align with it's matched chromosome start and end position in file2 all in the same row, but I am new to R and stuck on the first step of trying to match the variant based on if it's position number is within the range of the second file. Currently I am trying to adapt:

dt1[ dt2, match := i.,ID  #including a made-up ID column for the sake of trying to adapt this code
     on = .(Chromosome, Position > Start, Position < End ) ]

however this doesn't seem work, and beyond this I don't know how else to start. Any help on how to approach this would be appreciated

Data:

dput(file1)
structure(list(Chromosome = c(1L, 1L, 2L, 3L), Position = c(3L,
47L, 10L, 2L)), row.names = c(NA, -4L), class = c("data.table",
"data.frame"))

dput(file2)
structure(list(Chromosome = c(1L, 1L, 2L, 3L), Start = c(101L,
40L, 40L, 20L), End = c(102L, 50L, 50L, 22L)), row.names = c(NA,
-4L), class = c("data.table", "data.frame"))

Body:
You could use the tidyverse package to do some recoding and get the chromosomes where its Position value is between the Start and End.

library(tidyverse)

df<-file1 %>%
  # Join by Chromosome, it will duplicate each Position by Start and End Values
  left_join(file2,
            by = "Chromosome") %>%
  # Create a new column to indicate if the Position is between Start and End values
  mutate(isRange = Position >= Start & Position <= End) %>%
  # Filter to stay with only the chromosomes where the previous condition is met
  filter(isRange)


问:
Bash/Python: SyntaxError: unexpected character after line continuation character whilst piping to python
I am trying to pipe into python using bash:

```<code>#!/bin/sh
echo "from rest_framework_api_key.models import APIKey\n_, key = APIKey.objects.create_key(name='test_key')\nprint(key)" | python manage.py shell
</code>```

This gives the following error:

```<code>    from rest_framework_api_key.models import APIKey\n_, key = APIKey.objects.create_key(name='test_key')\nprint(key)
                                                                                ^
SyntaxError: unexpected character after line continuation character
</code>```

Strangely, this works:

```<code>#!/bin/sh
echo "from users.models import CustomUser\nCustomUser.objects.create_superuser('foo', '$1')" | python manage.py shell
</code>```

And I can't see the difference in terms of new lines / escaping / quoting. If I remove the pipe to python (i.e. it runs only the echo command), it does not error.

答:
You are missing the -e flag in the echo.

It should be :

```<code>echo -e "from rest_framework_api_key.models import APIKey\n_, key = APIKey.objects.create_key(name='test_key')\nprint(key)"
</code>```

Let me know if it helps!

Note : I only now noticed the shebang in your code. Unless you have a very specific reason not to do so, you should change your #!/bin/sh for #!/bin/bash.

Body:
I am trying to pipe into python using bash:

#!/bin/sh
echo "from rest_framework_api_key.models import APIKey\n_, key = APIKey.objects.create_key(name='test_key')\nprint(key)" | python manage.py shell

This gives the following error:

    from rest_framework_api_key.models import APIKey\n_, key = APIKey.objects.create_key(name='test_key')\nprint(key)
                                                                                ^
SyntaxError: unexpected character after line continuation character

Strangely, this works:

#!/bin/sh
echo "from users.models import CustomUser\nCustomUser.objects.create_superuser('foo', '$1')" | python manage.py shell

And I can't see the difference in terms of new lines / escaping / quoting. If I remove the pipe to python (i.e. it runs only the echo command), it does not error.

Body:
You are missing the -e flag in the echo.

It should be :

echo -e "from rest_framework_api_key.models import APIKey\n_, key = APIKey.objects.create_key(name='test_key')\nprint(key)"

Let me know if it helps!

Note : I only now noticed the shebang in your code. Unless you have a very specific reason not to do so, you should change your #!/bin/sh for #!/bin/bash.


问:
My input is getting skipped no matter what I use
I am trying to have a user enter three inputs: user name, id, and an alternate id.  If the user enters a return for user name, the program should end.  If the user enters a user name and enters a return for the next two ids, the input should display as invalid.  I have tried using cin, fgets, and get(I know get is usually bad programming).  When I used cin, I tried using cin.clear() and cin.ignore() to skip a newline entry.  The first input always works, but the second input call keeps getting skipped.

Code snippet:

```<code>int main(){
    string name, altID, tempUWFID;
    char input;
    cout << "Name> ";
//  if (cin.get() == '\n') - This was one way that I tried.
    if ((input = getchar()) == '\n')
        break;
    else
        cin >> name;
    cout << "UWF ID> ";
    if ((input = getchar()) != '\n')
        cin >> tempUWFID;
    cout << "Alternate ID> ";
    if ((input = getchar()) != '\n')
        cin >>altID;
cout << "\nThank you for abusing my program, have a nice day!\n";
</code>```

Output:

```<code>Welcome to Voter's Registration
Name> johnny
UWF ID> Alternate ID>
ad
Invalid UWF ID

Name>

Thank you for abusing my program, have a nice day!
</code>```

Expected Output:

```<code>Welcome to Voter's Registration
Name> johnny
UWF ID> somenumber
Alternate ID> someothernumber
Invalid UWF ID

Name>

Thank you for abusing my program, have a nice day!
</code>```

答:
Here's a quick little program I built, does this solve your problem?

cin itself can read newline characters, and cin >> ... treats newline characters as whitespace and ignores them. cin.getline(...) and std::getline(cin, ...) will read and discard newline characters from cin and then stop reading.

So see if this works for you.

```<code>#include <iostream>
#include <string>
using namespace std;

int main()
{
  string name = "";
  string uwfId = "";
  string altId = "";

  cout << "\nName> ";
  getline(cin, name);
  if(name == "" )
    return 0;

  cout << "\nUWF ID> ";
  getline(cin, name);

  cout << "\nAlternate ID> ";
  getline(cin, name);

  if(uwfId == "" || altId == "")
  {
    cout << "\nInvalid!";
    return 1;
  }

  return 0;
}
</code>```

Body:
I am trying to have a user enter three inputs: user name, id, and an alternate id.  If the user enters a return for user name, the program should end.  If the user enters a user name and enters a return for the next two ids, the input should display as invalid.  I have tried using cin, fgets, and get(I know get is usually bad programming).  When I used cin, I tried using cin.clear() and cin.ignore() to skip a newline entry.  The first input always works, but the second input call keeps getting skipped.

Code snippet:

int main(){
    string name, altID, tempUWFID;
    char input;
    cout << "Name> ";
//  if (cin.get() == '\n') - This was one way that I tried.
    if ((input = getchar()) == '\n')
        break;
    else
        cin >> name;
    cout << "UWF ID> ";
    if ((input = getchar()) != '\n')
        cin >> tempUWFID;
    cout << "Alternate ID> ";
    if ((input = getchar()) != '\n')
        cin >>altID;
cout << "\nThank you for abusing my program, have a nice day!\n";

Output:

Welcome to Voter's Registration
Name> johnny
UWF ID> Alternate ID>
ad
Invalid UWF ID

Name>

Thank you for abusing my program, have a nice day!

Expected Output:

Welcome to Voter's Registration
Name> johnny
UWF ID> somenumber
Alternate ID> someothernumber
Invalid UWF ID

Name>

Thank you for abusing my program, have a nice day!

Body:
Here's a quick little program I built, does this solve your problem?

cin itself can read newline characters, and cin >> ... treats newline characters as whitespace and ignores them. cin.getline(...) and std::getline(cin, ...) will read and discard newline characters from cin and then stop reading.

So see if this works for you.

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string name = "";
  string uwfId = "";
  string altId = "";

  cout << "\nName> ";
  getline(cin, name);
  if(name == "" )
    return 0;

  cout << "\nUWF ID> ";
  getline(cin, name);

  cout << "\nAlternate ID> ";
  getline(cin, name);

  if(uwfId == "" || altId == "")
  {
    cout << "\nInvalid!";
    return 1;
  }

  return 0;
}


问:
Longest palindrome (dynamic programming) code fails with time-out for large inputs. How to improve it?
I am learning to solve dynamic programming problems on LeetCode recently. The problem in hand is to find the longest palindrome in any given string. My code works well for small sized input strings. But fails for very large size inputs. Looking forward for ideas to improve it.

Code :

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

class Solution {
    public:
    std::string longestPalindrome(std::string s) {
        std::vector<std::string> sequence;
        std::string dummy, longest;

        for(auto it = s.begin(); it < s.end(); it++){
            dummy += *it;
            for(auto  it2 = it+1; it2 < s.end(); it2++) {
                dummy += *it2;
                sequence.push_back(dummy);
            }
            dummy = "";
        }
        for(auto &item : sequence) {
            for(auto it = item.rbegin(); it < item.rend(); it++) {
                dummy += *it;
            }
            if(item == dummy && item.size() > longest.size()) {
                longest = item;
            }
            dummy = "";
        }
        if (longest.empty())
            longest += *s.begin();
        return longest;
    }
};

int main() {
Solution solver;
std::cout << solver.longestPalindrome("babadhabab") << std::endl;
return 0;
}
</code>```

答:
I made some code and it works well, I think.

I'm not sure this code is perfect and fast.

but most of input data is not a palindrome, so this function will work well, I believe
(Algorithm)
1. iterate every character and set char to pivot
2. check string whether it is a palindrome around pivot
3. most of input data is not a palindrome, so it
4. WORST INPUT_DATA : all input data has same value like 'aaaaaaaaaa'

```<code>    class Solution {
        public:
        std::string longestPalindrome(std::string const& input)
        {
            if (2 > input.length()) { return std::string(); }

            char const* input_data = input.c_str();
            int found_palindrome_max_len = 0;
            char const* found_palindrome = nullptr;
            char const* current = input_data+1;
            while ('\0' != *current)
            {
                auto palindrome = is_palindrome(input_data, current, found_palindrome_max_len);
                if (nullptr != palindrome) { found_palindrome = palindrome; }
                ++current;
            }

            if (nullptr == found_palindrome) { return std::string(); }
            return input.substr(found_palindrome - input_data, found_palindrome_max_len);
        }

        char const* is_palindrome(char const* begin, char const* pivot, int& max_palindrome_len)
        {
            std::cout << "[BEGIN] pivot=" << *pivot << ", max_len = " << max_palindrome_len << std::endl;
            bool is_odd_check = true; // ex) abcba (odd length)
            bool is_even_check = true; // ex) abccba (even lenth)
            int length = 1;
            char const* left = nullptr;
            char const* right = nullptr;
            char const* found = nullptr;
            while (true == is_odd_check || true == is_even_check)
            {
                if (true == is_even_check && 0 == length % 2)   // even length check
                {
                    left = pivot - length/2 + 1;
                    right = pivot + length/2;
                    std::cout <<  "(even)length=" << length << ", pivot=" << *pivot <<", left=" << *left << ", right=" << *right << std::endl;
                    if (*left != *right)
                    {
                        std::cout << "is_even_check = false" << std::endl;
                        is_even_check = false;
                    }
                    else
                    {
                        if (length > max_palindrome_len)
                        {
                            found = left; max_palindrome_len = length;
                            std::cout << "max_palindrome_len = " << length << ", found=" << left << std::endl;
                        }
                    }
                }
                else if (true == is_odd_check && 1 == length % 2)// odd length check
                {
                    left = pivot - length/2;
                    right = pivot + length/2;
                    std::cout <<  "(odd)length=" << length << ", pivot=" << *pivot <<", left=" << *left << ", right=" << *right << std::endl;
                    if (*left != *right)
                    {
                        std::cout << "is_odd_check = false" << std::endl;
                        is_odd_check = false;
                    }
                    else
                    {
                        if (length > max_palindrome_len)
                        {
                            found = left; max_palindrome_len = length;
                            std::cout << "max_palindrome_len = " << length << ", found=" << left << std::endl;
                        }
                    }
                }

                if (begin == left || '\0' == right+1)
                {
                    break;
                }
                ++length;
            }

            return found;
        }
    };

    void TestPalin()
    {
        Solution solver;
        auto found = solver.longestPalindrome("123abba");
        std::cout << "PALINDROME = " << found << std::endl;
    }
</code>```

Body:
I am learning to solve dynamic programming problems on LeetCode recently. The problem in hand is to find the longest palindrome in any given string. My code works well for small sized input strings. But fails for very large size inputs. Looking forward for ideas to improve it.

Code :

#include <iostream>
#include <vector>

class Solution {
    public:
    std::string longestPalindrome(std::string s) {
        std::vector<std::string> sequence;
        std::string dummy, longest;

        for(auto it = s.begin(); it < s.end(); it++){
            dummy += *it;
            for(auto  it2 = it+1; it2 < s.end(); it2++) {
                dummy += *it2;
                sequence.push_back(dummy);
            }
            dummy = "";
        }
        for(auto &item : sequence) {
            for(auto it = item.rbegin(); it < item.rend(); it++) {
                dummy += *it;
            }
            if(item == dummy && item.size() > longest.size()) {
                longest = item;
            }
            dummy = "";
        }
        if (longest.empty())
            longest += *s.begin();
        return longest;
    }
};

int main() {
Solution solver;
std::cout << solver.longestPalindrome("babadhabab") << std::endl;
return 0;
}

Body:
I made some code and it works well, I think.

I'm not sure this code is perfect and fast.

but most of input data is not a palindrome, so this function will work well, I believe
(Algorithm)
1. iterate every character and set char to pivot
2. check string whether it is a palindrome around pivot
3. most of input data is not a palindrome, so it
4. WORST INPUT_DATA : all input data has same value like 'aaaaaaaaaa'

    class Solution {
        public:
        std::string longestPalindrome(std::string const& input)
        {
            if (2 > input.length()) { return std::string(); }

            char const* input_data = input.c_str();
            int found_palindrome_max_len = 0;
            char const* found_palindrome = nullptr;
            char const* current = input_data+1;
            while ('\0' != *current)
            {
                auto palindrome = is_palindrome(input_data, current, found_palindrome_max_len);
                if (nullptr != palindrome) { found_palindrome = palindrome; }
                ++current;
            }

            if (nullptr == found_palindrome) { return std::string(); }
            return input.substr(found_palindrome - input_data, found_palindrome_max_len);
        }

        char const* is_palindrome(char const* begin, char const* pivot, int& max_palindrome_len)
        {
            std::cout << "[BEGIN] pivot=" << *pivot << ", max_len = " << max_palindrome_len << std::endl;
            bool is_odd_check = true; // ex) abcba (odd length)
            bool is_even_check = true; // ex) abccba (even lenth)
            int length = 1;
            char const* left = nullptr;
            char const* right = nullptr;
            char const* found = nullptr;
            while (true == is_odd_check || true == is_even_check)
            {
                if (true == is_even_check && 0 == length % 2)   // even length check
                {
                    left = pivot - length/2 + 1;
                    right = pivot + length/2;
                    std::cout <<  "(even)length=" << length << ", pivot=" << *pivot <<", left=" << *left << ", right=" << *right << std::endl;
                    if (*left != *right)
                    {
                        std::cout << "is_even_check = false" << std::endl;
                        is_even_check = false;
                    }
                    else
                    {
                        if (length > max_palindrome_len)
                        {
                            found = left; max_palindrome_len = length;
                            std::cout << "max_palindrome_len = " << length << ", found=" << left << std::endl;
                        }
                    }
                }
                else if (true == is_odd_check && 1 == length % 2)// odd length check
                {
                    left = pivot - length/2;
                    right = pivot + length/2;
                    std::cout <<  "(odd)length=" << length << ", pivot=" << *pivot <<", left=" << *left << ", right=" << *right << std::endl;
                    if (*left != *right)
                    {
                        std::cout << "is_odd_check = false" << std::endl;
                        is_odd_check = false;
                    }
                    else
                    {
                        if (length > max_palindrome_len)
                        {
                            found = left; max_palindrome_len = length;
                            std::cout << "max_palindrome_len = " << length << ", found=" << left << std::endl;
                        }
                    }
                }

                if (begin == left || '\0' == right+1)
                {
                    break;
                }
                ++length;
            }

            return found;
        }
    };

    void TestPalin()
    {
        Solution solver;
        auto found = solver.longestPalindrome("123abba");
        std::cout << "PALINDROME = " << found << std::endl;
    }


答:
bash's echo doesn't expand \n to a newline by default. Use printf:

```<code>printf "from rest_framework_api_key.models import APIKey\n_, key = APIKey.objects.create_key(name='test_key')\nprint(key)" | python manage.py shell
</code>```

or more simply, a here document:

```<code>python manage.py shell << EOF
from rest_framework_api_key.models import APIKey
_, key = APIKey.objects.create_key(name='test_key')
print(key)
EOF
</code>```

Title: Bash/Python: SyntaxError: unexpected character after line continuation character whilst piping to python

Body:
bash's echo doesn't expand \n to a newline by default. Use printf:

printf "from rest_framework_api_key.models import APIKey\n_, key = APIKey.objects.create_key(name='test_key')\nprint(key)" | python manage.py shell

or more simply, a here document:

python manage.py shell << EOF
from rest_framework_api_key.models import APIKey
_, key = APIKey.objects.create_key(name='test_key')
print(key)
EOF


问:
http_response_code(200) not working with ErrorDocument 404
I have a problem with the php function http_response_code(). I have set the ErrorDocument 404 in a htaccess file in the root directory of my website to redirect every wrong call to a php file. In this php file, I would like to set the header of the response in some cases to code 200 OK. But this doesn't work. Chrome always says to me that the status code is 404.

This is the content of my .htaccess file:

```<code>ErrorDocument 404 /abc.php
</code>```

This is the content of my simple abc.php file:

```<code><?php

http_response_code(200);

?>

Test
</code>```

If I use another code e.g. 201, 301 or something else, it works. Only 200 is not working.

Here is a link to the example: http://test.foxpage.de/abdfgsdfgsdfgsdfgsdf

Can someone help me?

Thx!!

答:
This works in first row: How can I replace Apache HTTP code 404 to 200

```<code><?php header("Status: 200 OK"); ?>
</code>```

This code has to be put at the top of the .php file in the first line of code. Search engines, crawlers, browsers and anyone accessing the site will see the errordocument 404 page as a header 200.

Header 200 means the page exists. Google will crawl and index sites with header status 200.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with the php function http_response_code(). I have set the ErrorDocument 404 in a htaccess file in the root directory of my website to redirect every wrong call to a php file. In this php file, I would like to set the header of the response in some cases to code 200 OK. But this doesn't work. Chrome always says to me that the status code is 404.

This is the content of my .htaccess file:

ErrorDocument 404 /abc.php

This is the content of my simple abc.php file:

<?php

http_response_code(200);

?>

Test

If I use another code e.g. 201, 301 or something else, it works. Only 200 is not working.

Here is a link to the example: http://test.foxpage.de/abdfgsdfgsdfgsdfgsdf

Can someone help me?

Thx!!

Body:
This works in first row: How can I replace Apache HTTP code 404 to 200

<?php header("Status: 200 OK"); ?>

This code has to be put at the top of the .php file in the first line of code. Search engines, crawlers, browsers and anyone accessing the site will see the errordocument 404 page as a header 200.

Header 200 means the page exists. Google will crawl and index sites with header status 200.


Title: Increasing code execution time-efficiency using data.table and for-loop

Body:
Problem: How can I make the for-loop in below code run more time-efficiently? For this toy example it works in a reasonable amount of time. However, unique_ids will be a vector of approximately 8000 entries and the for-loop slows down heavily the computation. Any ideas? Many thanks!

Purpose:
Cluster retrospectively IIDs for each day into hop and top based on calculation logic in for-loop.

Initial Data:

   IID      ENTRY     FINISH     TARGET max_finish_target_date
1:      1 2020-02-11 2020-02-19 2020-02-15             2020-02-19
2:      2 2020-02-13 2020-02-17 2020-02-19             2020-02-19

Final (Target) Data:

 IID      Dates    ind_frist
 1:      1 2020-02-10
 2:      1 2020-02-11 hop
 3:      1 2020-02-12 hop
 4:      1 2020-02-13 hop
 5:      1 2020-02-14 hop
 6:      1 2020-02-15 hop
 7:      1 2020-02-16 top
 8:      1 2020-02-17 top
 9:      1 2020-02-18 top
10:      1 2020-02-19 top
11:      2 2020-02-10
12:      2 2020-02-11
13:      2 2020-02-12
14:      2 2020-02-13 hop
15:      2 2020-02-14 hop
16:      2 2020-02-15 hop
17:      2 2020-02-16 hop
18:      2 2020-02-17 hop
19:      2 2020-02-18
20:      2 2020-02-19
21:      3 2020-02-10
22:      3 2020-02-11
23:      3 2020-02-12
24:      3 2020-02-13
25:      3 2020-02-14
26:      3 2020-02-15 hop
27:      3 2020-02-16 hop
28:      3 2020-02-17 top
29:      3 2020-02-18 top
30:      3 2020-02-19 top

Code

rm(list = ls())

library(data.table)

# Some sample start data
initial_dt <- data.table(IID = c(1, 2, 3),
                         ENTRY = c("2020-02-11", "2020-02-13", "2020-02-15"),
                         FINISH = c("2020-02-19", "2020-02-17", ""),
                         TARGET = c("2020-02-15", "2020-02-19", "2020-02-16"))

initial_dt[, ":="(ENTRY = ymd(ENTRY),
                  FINISH = ymd(FINISH),
                  TARGET = ymd(TARGET))]

initial_dt[is.na(FINISH), FINISH := as.Date(ymd_hms(Sys.time()), format = "%Y-%m-%d")]

initial_dt[, max_finish_target_date := pmax(FINISH, TARGET)]

# Specify target data shape and output format
unique_ids <- c(1, 2, 3)

dts <- seq(as.Date("2020-02-10", format = "%Y-%m-%d"), as.Date(ymd_hms(Sys.time()), format = "%Y-%m-%d"), by = "days")

ids <- rep(unique_ids, each = length(dts))
len <- length(unique_ids)

final_dt <- data.table(IID = ids,
                       Dates = rep(dts, times = len))

# Calculation logic
# QUESTION: How can I make this part below run more efficiently and less time costly?
for (d_id in unique_ids){
  final_dt[(IID == d_id) & (Dates %between% c(initial_dt[IID == d_id, ENTRY], initial_dt[IID == d_id, max_finish_target_date])),
                ind_frist := ifelse((Dates > initial_dt[IID == d_id, TARGET]) & (Dates <= initial_dt[IID == d_id, max_finish_target_date]),
                                    "hop",
                                    "top")]
}

Body:
Your loop doesn't produce the output you show. The following non-equi joins produce that output but could easily be adjusted for other rules (e.g. those from your for loop):

final_dt <- CJ(IID = initial_dt[["IID"]], Dates = dts)
final_dt[initial_dt, ind_frist := "hop", on = .(IID, Dates >= ENTRY, Dates <= FINISH)]
final_dt[initial_dt, ind_frist := "top", on = .(IID, Dates > TARGET, Dates <= FINISH)]

These joins should be very fast.

Result:

#    IID      Dates ind_frist
# 1:   1 2020-02-10      <NA>
# 2:   1 2020-02-11       hop
# 3:   1 2020-02-12       hop
# 4:   1 2020-02-13       hop
# 5:   1 2020-02-14       hop
# 6:   1 2020-02-15       hop
# 7:   1 2020-02-16       top
# 8:   1 2020-02-17       top
# 9:   1 2020-02-18       top
#10:   1 2020-02-19       top
#11:   2 2020-02-10      <NA>
#12:   2 2020-02-11      <NA>
#13:   2 2020-02-12      <NA>
#14:   2 2020-02-13       hop
#15:   2 2020-02-14       hop
#16:   2 2020-02-15       hop
#17:   2 2020-02-16       hop
#18:   2 2020-02-17       hop
#19:   2 2020-02-18      <NA>
#20:   2 2020-02-19      <NA>
#21:   3 2020-02-10      <NA>
#22:   3 2020-02-11      <NA>
#23:   3 2020-02-12      <NA>
#24:   3 2020-02-13      <NA>
#25:   3 2020-02-14      <NA>
#26:   3 2020-02-15       hop
#27:   3 2020-02-16       hop
#28:   3 2020-02-17       top
#29:   3 2020-02-18       top
#30:   3 2020-02-19       top
#    IID      Dates ind_frist


问:
to display student details from and list of array,by validating or using a 6 digit string of code in php?
`

<!DOCTYPE html>

 <title>string checker</title>

 <?php

 $student_1 =array("name"=>"deepak","bc"=>"bca","year"=>2,"e_roll"=>001);
 $student_2 = array("name"=>"aditya","bs"=>"bs-it","year"=>2,"e_roll"=>002);
 $student_3 = array("name"=>"kissan","mc"=>"mca","year"=>3,"e_roll"=>003);
 $student_4 = array("name"=>"Shubham","bc"=>"bca","year"=>1,"e_roll"=>004);
 $student_5 = array("name"=>"vivek","bc"=>"bca","year"=>3,"e_roll"=>005);
 $student_6 = array("name"=>"rohit","mc"=>"mca","year"=>2,"e_roll"=>0003);

 $test_1="bc1001";
 $test_2="mc2003";
 $test_3="bs2002";

 $test_1 = str_replace(array_keys($student_1),$student_1,$test_1);

 ?>

```

using test_1 i want to  display student_1 details

`we have a 6 character alpha-numerical string.
1st two-character represents a program or course he/she pursuing**(eg; bs-BSC(it),bc-BCA,mc-MCA)**.
next char represents in which year he/she studying.
and remaining char represents roll no.

sample of the string is bc1001 should display student name course as BCA, year first and roll no 001

答:
It's not really clear what your expectation is but in general you could achieve this in multiple ways. One of it is regular expressions with preg_match https://www.php.net/manual/de/function.preg-match.php

Here is an example:

```<code>$string = 'bc1001';

preg_match('#([\w]{2})(\d{1})(\d{3})#i', $string, $matches);
</code>```

Result:

```<code>var_dump($matches[1], $matches[2], $matches[3]);

// string(2) "bc"
// string(1) "1"
// string(3) "001"
</code>```

Body:
`

<!DOCTYPE html>

 <title>string checker</title>

 <?php

 $student_1 =array("name"=>"deepak","bc"=>"bca","year"=>2,"e_roll"=>001);
 $student_2 = array("name"=>"aditya","bs"=>"bs-it","year"=>2,"e_roll"=>002);
 $student_3 = array("name"=>"kissan","mc"=>"mca","year"=>3,"e_roll"=>003);
 $student_4 = array("name"=>"Shubham","bc"=>"bca","year"=>1,"e_roll"=>004);
 $student_5 = array("name"=>"vivek","bc"=>"bca","year"=>3,"e_roll"=>005);
 $student_6 = array("name"=>"rohit","mc"=>"mca","year"=>2,"e_roll"=>0003);

 $test_1="bc1001";
 $test_2="mc2003";
 $test_3="bs2002";

 $test_1 = str_replace(array_keys($student_1),$student_1,$test_1);

 ?>

using test_1 i want to  display student_1 details

`we have a 6 character alpha-numerical string.
1st two-character represents a program or course he/she pursuing**(eg; bs-BSC(it),bc-BCA,mc-MCA)**.
next char represents in which year he/she studying.
and remaining char represents roll no.

sample of the string is bc1001 should display student name course as BCA, year first and roll no 001

Body:
It's not really clear what your expectation is but in general you could achieve this in multiple ways. One of it is regular expressions with preg_match https://www.php.net/manual/de/function.preg-match.php

Here is an example:

$string = 'bc1001';

preg_match('#([\w]{2})(\d{1})(\d{3})#i', $string, $matches);

Result:

var_dump($matches[1], $matches[2], $matches[3]);

// string(2) "bc"
// string(1) "1"
// string(3) "001"


问:
invalid prop source supplied to image React Native
I am new to react native. I have a list of image files stored in json format and would like to display them in a flatlist, but am getting the following warning

Here is my json

[{"eventDate": "Tuesday", "eventImage": "require('./youth.png')", "eventTime": "11am - 1pm", "id": "2", "name": "Food Band"}, {"eventDate": "Friday", "eventImage": "require('./youth.png')", "eventTime": "7:30pm", "id": "3", "name": "Youth"}]```
</div>
</div>
</p>

<p>Here is my code.</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>constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      imageHolder: ''

    }
  }
  webCall= () => {
       fetch('http://5e26eb00.ngrok.io/events.php', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      }).then((response) => response.json())
      .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson,
        imageHolder: responseJson[0].eventImage
      }, () => {
      });
      console.log(responseJson);
    }).catch((error) => {
    console.error(error);
  });
  }
   componentDidMount(){

    this.webCall();

   }
  render() {
    if (this.state.isLoading){
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
   <FlatList

    data={ this.state.dataSource }

    ItemSeparatorComponent = {this.FlatListItemSeparator}

    renderItem={({item}) =>

        <View style={{flex:1, flexDirection: 'row', paddingTop: 30, paddingLeft: 10}}>

          <Image source={item.eventImage}

              style={{ width: 100, height: 100, paddingBottom: 10 }}
            />

        <View>
              <Text style={styles.rowViewContainer}>{item.name}</Text>
              <Text style={styles.SermonByText}>{item.eventDate} - {item.eventTime}</Text>
          </View>

        </View>

      }

    keyExtractor={(item, index) => index.toString()}

    />

 </View>
);
}</code>```

My images are stored locally on my computer and I am using Xcode to run an iOS simulator. I can't understand why my images won't display or what I am doing wrong.

答:
You are setting the source of the <Image> to a String with the value of "require('./youth.png')".  This isn't going to execute the way you think it is.  If you need to require, you have to execute that as part of your actual program due to the way React Native bundles static assets.

If that value is coming from some service, it won't work.  If this is some JSON file or Object that you define elsewhere in your program, you need to execute the require explicitly.

```<code>const img = require('./youth.png');
// or
import img from './youth.png';

<Image source={img} />
</code>```

If your JSON is coming from some service, then you need another service to host the images.  React Native will only bundle assets that it knows about and can determine at "compile" time.

Body:
I am new to react native. I have a list of image files stored in json format and would like to display them in a flatlist, but am getting the following warning

Here is my json

[{"eventDate": "Tuesday", "eventImage": "require('./youth.png')", "eventTime": "11am - 1pm", "id": "2", "name": "Food Band"}, {"eventDate": "Friday", "eventImage": "require('./youth.png')", "eventTime": "7:30pm", "id": "3", "name": "Youth"}]

Here is my code.

constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      imageHolder: ''

    }
  }
  webCall= () => {
       fetch('http://5e26eb00.ngrok.io/events.php', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      }).then((response) => response.json())
      .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson,
        imageHolder: responseJson[0].eventImage
      }, () => {
      });
      console.log(responseJson);
    }).catch((error) => {
    console.error(error);
  });
  }
   componentDidMount(){

    this.webCall();

   }
  render() {
    if (this.state.isLoading){
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }
    return (
   <FlatList

    data={ this.state.dataSource }

    ItemSeparatorComponent = {this.FlatListItemSeparator}

    renderItem={({item}) =>

        <View style={{flex:1, flexDirection: 'row', paddingTop: 30, paddingLeft: 10}}>

          <Image source={item.eventImage}

              style={{ width: 100, height: 100, paddingBottom: 10 }}
            />

        <View>
              <Text style={styles.rowViewContainer}>{item.name}</Text>
              <Text style={styles.SermonByText}>{item.eventDate} - {item.eventTime}</Text>
          </View>

        </View>

      }

    keyExtractor={(item, index) => index.toString()}

    />

 </View>
);
}

My images are stored locally on my computer and I am using Xcode to run an iOS simulator. I can't understand why my images won't display or what I am doing wrong.

Body:
You are setting the source of the <Image> to a String with the value of "require('./youth.png')".  This isn't going to execute the way you think it is.  If you need to require, you have to execute that as part of your actual program due to the way React Native bundles static assets.

If that value is coming from some service, it won't work.  If this is some JSON file or Object that you define elsewhere in your program, you need to execute the require explicitly.

const img = require('./youth.png');
// or
import img from './youth.png';

<Image source={img} />

If your JSON is coming from some service, then you need another service to host the images.  React Native will only bundle assets that it knows about and can determine at "compile" time.


问:
transfer ownership and billing of storage buckets
I am currently hosting several cloud storage buckets with archived data for some of my clients.
For one client I would like to transfer the ownership and subsequent billing of multiple storage buckets to that client, but continue to administer them myself.

The buckets in question are already in their own (the clients name) project, but the are all hosted within my company domain.

How would I go about that transfer? Does my client need to create their own company domain and I then somehow transfer the project to them? Or do they get user access within my company domain and get a separate billing instance within my company domain?

It all a bit confusing to me.

答:
To disattach this project from your organization, you need to check that the project is in compliance with this document after that is necessary to file a case with support.

when the project is disattached from an organization, the billing account for this project is deleted and your customer need to a billing account in order to attach it to the project that has the buckets.

A billing account is created when a GCP project is created and upgraded(non free trial project)

And Complementing the answer from @JohnHanley  is necessary to change the billing account in the customer project, this change must be performed by a user with this permissions.

Project Owner or Project Billing Manager on the project, AND Billing Account Administrator or Billing Account User for the target Cloud Billing Account.

you can find more information on this link

Keep in mind that is not possible to transfer a bucket from one project to another or from a domain to another domain, you must copy the contents of the existing bucket to a new bucket that belongs to your customer's project.

This action need to be executed by an user that has access to read and write objects over the 2 buckets (source & target)


问:
Spring security custom token filter
I'm trying to perform a custom filter to get a token and validate it. I'm following the approach in this response.

This is the relevant configuration:

SecurityConfig:

```<code>@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = {"com.company.app"})
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Inject
AuthenticationTokenFilter authenticationTokenFilter;

@Inject
TokenAuthenticationProvider tokenAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(authenticationTokenFilter, BasicAuthenticationFilter.class)
                .antMatcher("/*")
                .authenticationProvider(tokenAuthenticationProvider)
                .authorizeRequests()
                    .anyRequest().authenticated();
    }

}
</code>```

AuthenticationTokenFilter:

```<code>@Component
public class AuthenticationTokenFilter implements Filter {

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

@Override
public void init(FilterConfig fc) throws ServletException {
    logger.info("Init AuthenticationTokenFilter");
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
    SecurityContext context = SecurityContextHolder.getContext();
    if (context.getAuthentication() != null && context.getAuthentication().isAuthenticated()) {
        // do nothing
    } else {
        Map<String,String[]> params = req.getParameterMap();
        if (!params.isEmpty() && params.containsKey("auth_token")) {
            String token = params.get("auth_token")[0];
            if (token != null) {
                Authentication auth = new TokenAuthentication(token);
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
    }

    fc.doFilter(req, res);
}

@Override
public void destroy() {

}
}
</code>```

TokenAuthentication:

```<code>public class TokenAuthentication implements Authentication {
private String token;

public TokenAuthentication(String token) {
    this.token = token;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return new ArrayList<GrantedAuthority>(0);
}
@Override
public Object getCredentials() {
    return token;
}
@Override
public Object getDetails() {
    return null;
}
@Override
public Object getPrincipal() {
    return null;
}
@Override
public boolean isAuthenticated() {
    return false;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
@Override
public String getName() {
    return null;
}
}
</code>```

TokenAuthenticationProvider:

```<code>@Component
public class TokenAuthenticationProvider implements AuthenticationProvider {

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

@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (auth.isAuthenticated())
        return auth;

    String token = auth.getCredentials().toString();
    User user = userSvc.validateApiAuthenticationToken(token);
    if (user != null) {
        auth = new PreAuthenticatedAuthenticationToken(user, token);
        auth.setAuthenticated(true);
        logger.debug("Token authentication. Token: ");
    } else
        throw new BadCredentialsException("Invalid token " + token);
    return auth;
}

@Override
public boolean supports(Class<?> aClass) {
    return true;
}

}
</code>```

But it's like the AuthenticationTokenFilter is not being added to the chain. Debugging I can see that when I do a call it enters to the SecurityConfig and configure method but not to the filter.
What is missing?

答: FYI: using both the @Component on the Filter and @Inject with addFilterBefore will apply the filter twice! In your case it is just more processing time, so you wont see any errors. But if you are injecting lets say a metrics filter, then you will be getting wrong metrics.

Title: Spring security custom token filter

Body:
I'm trying to perform a custom filter to get a token and validate it. I'm following the approach in this response.

This is the relevant configuration:

SecurityConfig:

@Configuration
@EnableWebSecurity
@ComponentScan(basePackages = {"com.company.app"})
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Inject
AuthenticationTokenFilter authenticationTokenFilter;

@Inject
TokenAuthenticationProvider tokenAuthenticationProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .addFilterBefore(authenticationTokenFilter, BasicAuthenticationFilter.class)
                .antMatcher("/*")
                .authenticationProvider(tokenAuthenticationProvider)
                .authorizeRequests()
                    .anyRequest().authenticated();
    }

}

AuthenticationTokenFilter:

@Component
public class AuthenticationTokenFilter implements Filter {

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

@Override
public void init(FilterConfig fc) throws ServletException {
    logger.info("Init AuthenticationTokenFilter");
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
    SecurityContext context = SecurityContextHolder.getContext();
    if (context.getAuthentication() != null && context.getAuthentication().isAuthenticated()) {
        // do nothing
    } else {
        Map<String,String[]> params = req.getParameterMap();
        if (!params.isEmpty() && params.containsKey("auth_token")) {
            String token = params.get("auth_token")[0];
            if (token != null) {
                Authentication auth = new TokenAuthentication(token);
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        }
    }

    fc.doFilter(req, res);
}

@Override
public void destroy() {

}
}

TokenAuthentication:

public class TokenAuthentication implements Authentication {
private String token;

public TokenAuthentication(String token) {
    this.token = token;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return new ArrayList<GrantedAuthority>(0);
}
@Override
public Object getCredentials() {
    return token;
}
@Override
public Object getDetails() {
    return null;
}
@Override
public Object getPrincipal() {
    return null;
}
@Override
public boolean isAuthenticated() {
    return false;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
}
@Override
public String getName() {
    return null;
}
}

TokenAuthenticationProvider:

@Component
public class TokenAuthenticationProvider implements AuthenticationProvider {

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

@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    if (auth.isAuthenticated())
        return auth;

    String token = auth.getCredentials().toString();
    User user = userSvc.validateApiAuthenticationToken(token);
    if (user != null) {
        auth = new PreAuthenticatedAuthenticationToken(user, token);
        auth.setAuthenticated(true);
        logger.debug("Token authentication. Token: ");
    } else
        throw new BadCredentialsException("Invalid token " + token);
    return auth;
}

@Override
public boolean supports(Class<?> aClass) {
    return true;
}

}

But it's like the AuthenticationTokenFilter is not being added to the chain. Debugging I can see that when I do a call it enters to the SecurityConfig and configure method but not to the filter.
What is missing?


问:
Missing .dll in different Visual Studio versions
I recently came up with an issue. I had a project created on visual studio 2015, using allegro5 library which executed on Debug and Release mode correctly.

When I changed visual studio versions though and started using 2019 version (In the mean time I had to format my PC and re-installed only VS19) and loaded the project, the execution had a missing msvc110d.dll error shown up.

I tried to find a way in order for my project to be "upgraded" and instead of looking into the old version of msvc to try and look up the newer version, but couldn't find anything.

So is there a way for me to change some settings in order for my project to expect newer versions of msvc, or do I have to create a new project and copy paste all the configurations and files/assets inside that new project?

Thank you all

P.S I know that the error can be resolved If I get the .dll file inside that directory, but that is bad practice for sure. Also could you give me a tip on how to setup a project correctly in order to prevent those kind of issues in the future?

答:
Windows dynamic library files are installed under c:\windows\system32 directory. A 32 bit dll file in a 64 bit windows can be found under c:\windows\syswow64. When your VC++ developed application searches for the dll it first checks in the application folder and then the system folder. If it is not found in these locations, a "missing dll file" error will be shown.

Normally, installing the right VC++ redistributable does the trick. But at times the mismatch persist as the sdk you're using is not in conformity with the system dll. You shouldn't replace the existing dll in the system directory manually with a downloaded( download only from www.microsoft.com) one as other installed software may also failed in the process.

In such worse case scenario, you can however directly copy the downloaded dll files  in your application folder itself and distribute along your software so that it runs on a remote host too. Normally these compatible dll files, for both debug and release versions, are also available in your VC++ sdk directory which can be copied for a perfect match.


问:
Artifactory in Jenkins pipeline: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String
I have this in my Jenkinsfile:

```<code>stage('Artifactory Deploy') {
    options {
        timeout(time: 5, unit: 'MINUTES')
    }
    when {
        anyOf {
            branch "master"
            branch "develop"
        }
    }
    steps {
        withMaven(jdk: "${JDK_VERSION}", maven: 'M3') {
            script {
                def server = Artifactory.server('itext-artifactory')
                def rtMaven = Artifactory.newMavenBuild()
                rtMaven.deployer server: server, releaseRepo: 'releases', snapshotRepo: 'snapshot'
                rtMaven.tool = 'M3'
                def buildInfo = rtMaven.run pom: 'pom.xml',
                        goals: "--threads 2C --no-transfer-progress " +
                                "install --activate-profiles artifactory " +
                                "-Dmaven.repo.local=${env.WORKSPACE.replace('\\','/')}/.repository"
                server.publishBuildInfo buildInfo
            }
        }
    }
}
</code>```

${env.WORKSPACE.replace('\\','/')} is required because while Linux behaves as expected, Windows apparently behaves like T̪̩͑̒̀o̭̦̱͎̗̲̎̿̎ͩ̓̏̔n̊̀ͅy̲͓̘ͥͬ̾ͮ̌ͮ̐ ̘̪̝̳̺̖t̪͎̒̓͑̆̎̚h̵ͥͯ̅ͯ̚ȩ̟̩̞̹̫̌ͦ̉͂ͨ̔ͣͅ ̺͋̆͂̅ͥP̵̖̞͕̲̂̄ͥͩơ̙͇̫̰͍ͮ̽̓nͨ̄ͮy̘̪ͨͯ͂ͪ with regards to path separators.

I'd much rather have

```<code>withMaven(jdk: "${JDK_VERSION}", maven: 'M3', mavenLocalRepo: '.repository')
</code>```

but we can't have nice things.

Anyway, when running this on Jenkins, I get the following error:

```<code>java.lang.ClassCastException: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String
    at org.jfrog.hudson.pipeline.common.types.builds.MavenBuild.run(MavenBuild.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:47)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:160)
    at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:157)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:158)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:162)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
    at WorkflowScript.run(WorkflowScript:193)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor290.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.CollectionLiteralBlock$ContinuationImpl.dispatch(CollectionLiteralBlock.java:55)
    at com.cloudbees.groovy.cps.impl.CollectionLiteralBlock$ContinuationImpl.item(CollectionLiteralBlock.java:45)
    at sun.reflect.GeneratedMethodAccessor340.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:107)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor290.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:89)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor290.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:400)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:96)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:312)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:276)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

and no artifacts are deployed to Artifactory (and the build fails).

How to fix this? Either upstream bugfix or local workaround.

Posting my question on Stack Overflow because we have an Artifactory Pro license, and Jfrog's customer support portal is only available for Pro X, Enterprise and Enterprise+ customers. Other customers get directed to Stack Overflow, see https://jfrog.com/support/.

答:
A possible root cause is something found in a comment on GStringImpl cannot be cast to java.lang.String:

if you try to assign a GString to something that is statically typed as String (or pass a GString for a String-type method parameter) then Groovy will do the conversion for you, but if you assign to something that is typed as Object then you have to convert it yourself.

Because I'm using a variable in curly braces (${env.WORKSPACE.replace('\\','/')}), I automatically have a Groovy GString instead of a Java String.

So, Jfrog staff, if you are monitoring the artifactory tag on Stack Overflow: according to the Jenkins documentation for the Artifactory plugin, goals is defined as type String, but apparently this is not the case because Groovy can't do the conversion? Can you confirm or explain? Thanks!

EDIT

I found the Jenkins Artifactory Plugin API Javadocs and the run() method of org.jfrog.hudson.pipeline.common.types.builds.MavenBuild takes a Map as argument:

```<code>public void run(Map<String,Object> args)
</code>```

So indeed, while Groovy will automagically do the conversion from a Groovy GString to a Java String, it won't do the conversion from a Groovy Gstring to an Object inside a Map.

Workaround

As described in the linked question, I added .toString() to manually convert the Groovy GString to a Java String.

So

```<code>def buildInfo = rtMaven.run pom: 'pom.xml',
        goals: "--threads 2C --no-transfer-progress " +
                "install --activate-profiles artifactory " +
                "-Dmaven.repo.local=${env.WORKSPACE.replace('\\','/')}/.repository"

</code>```

became

```<code>def buildInfo = rtMaven.run pom: 'pom.xml',
        goals: "--threads 2C --no-transfer-progress " +
                "install --activate-profiles artifactory " +
                "-Dmaven.repo.local=${env.WORKSPACE.replace('\\','/')}/.repository".toString()

</code>```

Body:
I have this in my Jenkinsfile:

stage('Artifactory Deploy') {
    options {
        timeout(time: 5, unit: 'MINUTES')
    }
    when {
        anyOf {
            branch "master"
            branch "develop"
        }
    }
    steps {
        withMaven(jdk: "${JDK_VERSION}", maven: 'M3') {
            script {
                def server = Artifactory.server('itext-artifactory')
                def rtMaven = Artifactory.newMavenBuild()
                rtMaven.deployer server: server, releaseRepo: 'releases', snapshotRepo: 'snapshot'
                rtMaven.tool = 'M3'
                def buildInfo = rtMaven.run pom: 'pom.xml',
                        goals: "--threads 2C --no-transfer-progress " +
                                "install --activate-profiles artifactory " +
                                "-Dmaven.repo.local=${env.WORKSPACE.replace('\\','/')}/.repository"
                server.publishBuildInfo buildInfo
            }
        }
    }
}

${env.WORKSPACE.replace('\\','/')} is required because while Linux behaves as expected, Windows apparently behaves like T̪̩͑̒̀o̭̦̱͎̗̲̎̿̎ͩ̓̏̔n̊̀ͅy̲͓̘ͥͬ̾ͮ̌ͮ̐ ̘̪̝̳̺̖t̪͎̒̓͑̆̎̚h̵ͥͯ̅ͯ̚ȩ̟̩̞̹̫̌ͦ̉͂ͨ̔ͣͅ ̺͋̆͂̅ͥP̵̖̞͕̲̂̄ͥͩơ̙͇̫̰͍ͮ̽̓nͨ̄ͮy̘̪ͨͯ͂ͪ with regards to path separators.

I'd much rather have

withMaven(jdk: "${JDK_VERSION}", maven: 'M3', mavenLocalRepo: '.repository')

but we can't have nice things.

Anyway, when running this on Jenkins, I get the following error:

java.lang.ClassCastException: org.codehaus.groovy.runtime.GStringImpl cannot be cast to java.lang.String
    at org.jfrog.hudson.pipeline.common.types.builds.MavenBuild.run(MavenBuild.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:47)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:160)
    at org.kohsuke.groovy.sandbox.GroovyInterceptor.onMethodCall(GroovyInterceptor.java:23)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onMethodCall(SandboxInterceptor.java:157)
    at org.kohsuke.groovy.sandbox.impl.Checker$1.call(Checker.java:158)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedCall(Checker.java:162)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.methodCall(SandboxInvoker.java:17)
    at WorkflowScript.run(WorkflowScript:193)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:86)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor290.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.CollectionLiteralBlock$ContinuationImpl.dispatch(CollectionLiteralBlock.java:55)
    at com.cloudbees.groovy.cps.impl.CollectionLiteralBlock$ContinuationImpl.item(CollectionLiteralBlock.java:45)
    at sun.reflect.GeneratedMethodAccessor340.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:107)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor290.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:89)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:113)
    at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:83)
    at sun.reflect.GeneratedMethodAccessor290.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:185)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:400)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:96)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:312)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:276)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

and no artifacts are deployed to Artifactory (and the build fails).

How to fix this? Either upstream bugfix or local workaround.

Posting my question on Stack Overflow because we have an Artifactory Pro license, and Jfrog's customer support portal is only available for Pro X, Enterprise and Enterprise+ customers. Other customers get directed to Stack Overflow, see https://jfrog.com/support/.

Body:
A possible root cause is something found in a comment on GStringImpl cannot be cast to java.lang.String:

if you try to assign a GString to something that is statically typed as String (or pass a GString for a String-type method parameter) then Groovy will do the conversion for you, but if you assign to something that is typed as Object then you have to convert it yourself.

Because I'm using a variable in curly braces (${env.WORKSPACE.replace('\\','/')}), I automatically have a Groovy GString instead of a Java String.

So, Jfrog staff, if you are monitoring the artifactory tag on Stack Overflow: according to the Jenkins documentation for the Artifactory plugin, goals is defined as type String, but apparently this is not the case because Groovy can't do the conversion? Can you confirm or explain? Thanks!

EDIT

I found the Jenkins Artifactory Plugin API Javadocs and the run() method of org.jfrog.hudson.pipeline.common.types.builds.MavenBuild takes a Map as argument:

public void run(Map<String,Object> args)

So indeed, while Groovy will automagically do the conversion from a Groovy GString to a Java String, it won't do the conversion from a Groovy Gstring to an Object inside a Map.

Workaround

As described in the linked question, I added .toString() to manually convert the Groovy GString to a Java String.

So

def buildInfo = rtMaven.run pom: 'pom.xml',
        goals: "--threads 2C --no-transfer-progress " +
                "install --activate-profiles artifactory " +
                "-Dmaven.repo.local=${env.WORKSPACE.replace('\\','/')}/.repository"

became

def buildInfo = rtMaven.run pom: 'pom.xml',
        goals: "--threads 2C --no-transfer-progress " +
                "install --activate-profiles artifactory " +
                "-Dmaven.repo.local=${env.WORKSPACE.replace('\\','/')}/.repository".toString()


问:
Recipe for target failed
Basically It is supposed to calculate the Federal Income of the user. But anytime I run it to see what is no doubt a baragge of structure errors I get this MakeFile

```<code>CPP      = g++.exe
CC       = gcc.exe
WINDRES  = windres.exe
OBJ      = #3.o
LINKOBJ  = #3.o
LIBS     = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc
INCS     = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS  = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN      = HOMEWORK.exe
CXXFLAGS = $(CXXINCS)
CFLAGS   = $(INCS)
RM       = rm.exe -f

.PHONY: all all-before all-after clean clean-custom

all: all-before $(BIN) all-after

clean: clean-custom
    ${RM} $(OBJ) $(BIN)

$(BIN): $(OBJ)
    $(CPP) $(LINKOBJ) -o $(BIN) $(LIBS)

#3.o: #3.cpp
    $(CPP) -c #3.cpp -o #3.o $(CXXFLAGS)
</code>```

Any and all help/advice is appreciated.

答: The filename #3.cpp breaks your makefile, makes it invalid, such name is treated as a comment. Rename the file, so # is not used. Surrounding it with quotation marks, "#3.cpp" and "#3.o" does not work in Makefile: GNU makefile how to and when to quote strings</p>

Title: Recipe for target failed

Body:
Basically It is supposed to calculate the Federal Income of the user. But anytime I run it to see what is no doubt a baragge of structure errors I get this MakeFile

CPP      = g++.exe
CC       = gcc.exe
WINDRES  = windres.exe
OBJ      = #3.o
LINKOBJ  = #3.o
LIBS     = -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib" -L"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/lib" -static-libgcc
INCS     = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include"
CXXINCS  = -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/x86_64-w64-mingw32/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include" -I"C:/Program Files (x86)/Dev-Cpp/MinGW64/lib/gcc/x86_64-w64-mingw32/4.9.2/include/c++"
BIN      = HOMEWORK.exe
CXXFLAGS = $(CXXINCS)
CFLAGS   = $(INCS)
RM       = rm.exe -f

.PHONY: all all-before all-after clean clean-custom

all: all-before $(BIN) all-after

clean: clean-custom
    ${RM} $(OBJ) $(BIN)

$(BIN): $(OBJ)
    $(CPP) $(LINKOBJ) -o $(BIN) $(LIBS)

#3.o: #3.cpp
    $(CPP) -c #3.cpp -o #3.o $(CXXFLAGS)

Any and all help/advice is appreciated.