问:
IntelliSense not working in React Native stylesheet after first item
I am using VSCode (1.34.0) + Flow (Flow Language Support: 1.1.1, Flow Language Client: 0.2.1) (switched to Typescript but still having the same error) Typescript 3.4.5 on my React Native project.

When I start typing a style property, it completes the first property with no problem, then when I start typing the second style property, it doesn't complete:

What am I doing wrong?

UPDATE: My (relevant) enabled extensions are:

Babel JavaScript 0.0.22,

Flow Language Support: 1.1.1,

Flow Language Client: 0.2.1,

npm Intellisense 1.3.0,

Prettier - Code formatter 1.8.1,

React Native Tools 0.9.3.

答:
Hi There I faced the same problem what I did is I
just installed a vs code  plugin named
IntelliSense for CSS class names in HTML
and it solved the problem for me now it's working
The perfect link is here

https://marketplace.visualstudio.com/items?itemName=Zignd.html-css-class-completion


来源: stackexchange

问:
How to get copy of the ArrayList<Sealed Class> in android using kotlin
How to get the copy of arraylist of sealed class in android

private var homePageApiResponseList : ArrayList<HomeApiResponseModel> = ArrayList()

Here HomeApiResponseModel is a Sealed class. HomeApiResponseModel is given as Below

```<code>sealed class HomeApiResponseModel {

    data class HomeCategoryListModel(
        var categoryList : MutableList<CategoryModel> = mutableListOf(),
        var categoryNameType : String = ""
    ) : HomeApiResponseModel()

    data class HomeBestSellerListModel(
        var bestSellerList : MutableList<ChildrenModel> = mutableListOf(),
        var bestSellerNameType : String = ""
    ) : HomeApiResponseModel()

    data class HomeMustTryListModel(
        var mustTryList : MutableList<ChildrenModel> = mutableListOf(),
        var mustTryNameType : String = ""
    ) : HomeApiResponseModel()
}
</code>```

Normally arraylist of object copy is easly obtain by anyList.map { it.copy() }

While in sealed class it shows error. How to get a copy of arraylist of sealed class

Thanks

答:
Create an abstract function in the parent. Each child can implement it and call through to their own copy(). The abstract function should have a different name than “copy” to avoid conflicts.

By the way, in your case, a sealed interface is probably a cleaner choice than a sealed class because there is no common functionality between the children. And I suggest avoiding combining mutable collections with var properties. Making something mutable in two different ways adds (usually unnecessary) complexity and more opportunities for bugs.

ContentLicense: CC BY-SA 4.0

Body:
How to get the copy of arraylist of sealed class in android

private var homePageApiResponseList : ArrayList<HomeApiResponseModel> = ArrayList()

Here HomeApiResponseModel is a Sealed class. HomeApiResponseModel is given as Below

sealed class HomeApiResponseModel {

    data class HomeCategoryListModel(
        var categoryList : MutableList<CategoryModel> = mutableListOf(),
        var categoryNameType : String = ""
    ) : HomeApiResponseModel()

    data class HomeBestSellerListModel(
        var bestSellerList : MutableList<ChildrenModel> = mutableListOf(),
        var bestSellerNameType : String = ""
    ) : HomeApiResponseModel()

    data class HomeMustTryListModel(
        var mustTryList : MutableList<ChildrenModel> = mutableListOf(),
        var mustTryNameType : String = ""
    ) : HomeApiResponseModel()
}

Normally arraylist of object copy is easly obtain by anyList.map { it.copy() }

While in sealed class it shows error. How to get a copy of arraylist of sealed class

Thanks


问:
Remove newline from string output

try:
    with cx_oracle.connect(user,password,dsn,encoding ="UTF-8") as connection:
        cursor = connection.cursor()
        cursor.execute("select * from customer")
        results =cursor.fetchall()
        return json.dumps(results,indent=4,sort_keys = True,default=str)
except Exception as error:
    print ("error occurred",error)
```
<p>output</p>
```'[\n [\n 1456,\n   "ice kle",\n  "2022:02:08 8:06:01",\n  "2022-02-08 8:07:01",\n "fund"\n]'
```

答:
just dont tell it to format the json

json.dumps(results) instead of json.dumps(results,indent=4...)

if you really just want to keep that json dumps for some reason and instead remove the newlines ... just do

```<code>result = result.replace("\n","")
</code>```

Title: Remove newline from string output

Body:
try:
    with cx_oracle.connect(user,password,dsn,encoding ="UTF-8") as connection:
        cursor = connection.cursor()
        cursor.execute("select * from customer")
        results =cursor.fetchall()
        return json.dumps(results,indent=4,sort_keys = True,default=str)
except Exception as error:
    print ("error occurred",error)

output

'[\n [\n 1456,\n   "ice kle",\n  "2022:02:08 8:06:01",\n  "2022-02-08 8:07:01",\n "fund"\n]'

Body:
just dont tell it to format the json

json.dumps(results) instead of json.dumps(results,indent=4...)

if you really just want to keep that json dumps for some reason and instead remove the newlines ... just do

result = result.replace("\n","")


问:
res.redirected returning false even when the backend returns a redirect
I'm trying to create a login page which redirects the user back to the home page after successful login using nodejs and fetch.
Here is the code of backend.

```<code>app.post('/login',(req,res)=>
{
    user.findOne(req.body,(err,info)=>{
        if(err)
        {
            res.json(`error in finding item in database ,error info ${err}`);
        }

        else if(!info)
        {
            console.log('user doesnot exist');
            let message='*please enter a valid username and password';
            res.json(message);
        }

        else{
            console.log(info);
            res.redirect('/');
        }
    });

});
</code>```

This is the front end code

```<code>form.addEventListener('submit',(e)=>{
    e.preventDefault();

    const username=document.getElementById('username').value.trim();
    const password=document.getElementById('password').value;

    fetch('/login',{
        method:'POST',
        headers:{
            'Content-Type':'application/json'
        },
        redirect:"manual",
        body:JSON.stringify({username,password})
    }).then((res)=>{
        if(res.redirected)
        {
            console.log(`redirected to ${res.url}`);
            window.location.href=res.url;
            // return;
        }
        else{
            console.log("no")
            return res.json()
        }
    })
    .then((data)=>{
        if(data)
        alt.innerText=data;//showing the error on the page
    })
    .catch((err)=>{throw err})
})
</code>```

When I enter the correct credentials it prints the info on the console, that means it is inside the else and ideally should redirect back to the home page. But it never enters the if(res.redirected) statement which means it is returning false.

答:
Since some older chrome version does not read res.redirected, and for the sake of achieving cleaner codes as well as unexpected redirects (e.g. HTTP to HTTPS), you may want to set res.direct('/') to res.json({ redirect: '/' }) instead.

```<code>const results = await fetch(....).then(res.json());

if (results.redirect) {
     window.location.href = results.redirect
}

if (results.data) {
     //do something
}
</code>```

Backend

```<code>if (info) {
   return res.json({ data: info });
} else {
   return res.json({ redirect: '/', error: true })
}
</code>```

Body:
I'm trying to create a login page which redirects the user back to the home page after successful login using nodejs and fetch.
Here is the code of backend.

app.post('/login',(req,res)=>
{
    user.findOne(req.body,(err,info)=>{
        if(err)
        {
            res.json(`error in finding item in database ,error info ${err}`);
        }

        else if(!info)
        {
            console.log('user doesnot exist');
            let message='*please enter a valid username and password';
            res.json(message);
        }

        else{
            console.log(info);
            res.redirect('/');
        }
    });

});

This is the front end code

form.addEventListener('submit',(e)=>{
    e.preventDefault();

    const username=document.getElementById('username').value.trim();
    const password=document.getElementById('password').value;

    fetch('/login',{
        method:'POST',
        headers:{
            'Content-Type':'application/json'
        },
        redirect:"manual",
        body:JSON.stringify({username,password})
    }).then((res)=>{
        if(res.redirected)
        {
            console.log(`redirected to ${res.url}`);
            window.location.href=res.url;
            // return;
        }
        else{
            console.log("no")
            return res.json()
        }
    })
    .then((data)=>{
        if(data)
        alt.innerText=data;//showing the error on the page
    })
    .catch((err)=>{throw err})
})

When I enter the correct credentials it prints the info on the console, that means it is inside the else and ideally should redirect back to the home page. But it never enters the if(res.redirected) statement which means it is returning false.

Body:
Since some older chrome version does not read res.redirected, and for the sake of achieving cleaner codes as well as unexpected redirects (e.g. HTTP to HTTPS), you may want to set res.direct('/') to res.json({ redirect: '/' }) instead.

const results = await fetch(....).then(res.json());

if (results.redirect) {
     window.location.href = results.redirect
}

if (results.data) {
     //do something
}

Backend

if (info) {
   return res.json({ data: info });
} else {
   return res.json({ redirect: '/', error: true })
}


问:
define a generic property in non-generic base class
I dont think what I am trying to do is possible; is there a way to actually make this work?

There is a Base class from which a variety of different classes are derived. Derived classes can be generic or not; instances of the derived classes are added to a collection of type Base in WindowViewModel. The Base class has a collection of Options that are accessed by the WindowViewModel.

The issue is: the IOption interface declares a return type of Func<object, bool> MyFunc but the return type of MyFunc needs to be Func<T, bool> for the generic class method RunIt() and for the assignment in MyClass to work. I could make the IOption generic, but then the Base class would need to be generic, and then the WindowViewModel.ViewModels would also need to be redefined somehow. I dont want to make the Base generic as introducing generics there just makes everything else a real mess.

Question: is there a different way to declare MyFunc in IOption without using generics to allow assignment of Func<T,bool> in MyClass ?

```<code>public interface IOption
{
    public string Description {get; set;}
    public Expression<Func<object,bool>> MyFunc { get; set; }
}

public class Option : IOption
{
    public string Description {get; set;}
    public Expression<Func<object,bool>> MyFunc { get; set; }
}

public abstract class Base
{
    public abstract ObservableCollection<Option> Options { get; set; }
    public abstract Option SelectedOption { get; set; }

    public abstract void RunIt();
}

public class Generic<T> : Base
{
    private DBContext _context;

    public override ObservableCollection<Option> Options { get; set; }
    public override Option SelectedOption { get; set; }

    public Generic()
       : base()
    {
        Options = new ObservableCollection<Option>();
    }
    public override void RunIt()
    {
        var result = _context.Set<T>().Where(SelectedOption?.MyFunc);
        // process result
    }
}

public class MyClass : Generic<MyType>
{
    public MyClass
       : base()
    {
        Func<MyType,bool> expression = t => t.MyDescription = "Hello World";
        Options.Add(new Option("Hi", expression));  // fail to compile type mismatch
        SelectedOption = Options.First();
    }
}

public class Special : Base
{
// do something else
}

public class WindowViewModel
{
   public WindowViewModel ()
   {
     MyViewModels = new ObservableCollection<Base>();
     MyViewModels.Add(new Special());
     MyViewModels.Add(new MyClass());
   }

   public ObservableCollection<Base> MyViewModels {get; set;}
   public Base SelectedViewModel { get; set; }

   public void DoRunIt()
   {
      SelectedViewModel.RunIt();
   }
}
</code>```

one of the things I did try that compiles but throws runtime exception when used, is

```<code>Func<MyType,bool> expression = t => t.MyDescription = "Hello World";
MyFunc = t => expression((MyType)t);
</code>```

答:
There is a way to do this. It uses the ability for all delegates (Func<MyType, bool> is a delegate) to be cast to Delegate.

You'd change IOption and Option to this:

```<code>public interface IOption
{
    public string Description { get; set; }
    Func<T, bool> GetMyFunc<T>();
}

public class Option : IOption
{
    string description;
    private Delegate expression;

    public Option(string description, Delegate expression)
    {
        this.description = description;
        this.expression = expression;
    }

    public string Description { get; set; }
    public Func<T, bool> GetMyFunc<T>() => (Func<T, bool>)this.expression;
}
</code>```

Then MyClass works as expected (except for the other syntax error in your code).

You then just need to change RunIt on Generic<T> to this:

```<code>public override void RunIt()
{
    var result = _context.Set<T>().Where(SelectedOption?.GetMyFunc<T>());
    // process result
}
</code>```

Body:
I dont think what I am trying to do is possible; is there a way to actually make this work?

There is a Base class from which a variety of different classes are derived. Derived classes can be generic or not; instances of the derived classes are added to a collection of type Base in WindowViewModel. The Base class has a collection of Options that are accessed by the WindowViewModel.

The issue is: the IOption interface declares a return type of Func<object, bool> MyFunc but the return type of MyFunc needs to be Func<T, bool> for the generic class method RunIt() and for the assignment in MyClass to work. I could make the IOption generic, but then the Base class would need to be generic, and then the WindowViewModel.ViewModels would also need to be redefined somehow. I dont want to make the Base generic as introducing generics there just makes everything else a real mess.

Question: is there a different way to declare MyFunc in IOption without using generics to allow assignment of Func<T,bool> in MyClass ?

public interface IOption
{
    public string Description {get; set;}
    public Expression<Func<object,bool>> MyFunc { get; set; }
}

public class Option : IOption
{
    public string Description {get; set;}
    public Expression<Func<object,bool>> MyFunc { get; set; }
}

public abstract class Base
{
    public abstract ObservableCollection<Option> Options { get; set; }
    public abstract Option SelectedOption { get; set; }

    public abstract void RunIt();
}

public class Generic<T> : Base
{
    private DBContext _context;

    public override ObservableCollection<Option> Options { get; set; }
    public override Option SelectedOption { get; set; }

    public Generic()
       : base()
    {
        Options = new ObservableCollection<Option>();
    }
    public override void RunIt()
    {
        var result = _context.Set<T>().Where(SelectedOption?.MyFunc);
        // process result
    }
}

public class MyClass : Generic<MyType>
{
    public MyClass
       : base()
    {
        Func<MyType,bool> expression = t => t.MyDescription = "Hello World";
        Options.Add(new Option("Hi", expression));  // fail to compile type mismatch
        SelectedOption = Options.First();
    }
}

public class Special : Base
{
// do something else
}

public class WindowViewModel
{
   public WindowViewModel ()
   {
     MyViewModels = new ObservableCollection<Base>();
     MyViewModels.Add(new Special());
     MyViewModels.Add(new MyClass());
   }

   public ObservableCollection<Base> MyViewModels {get; set;}
   public Base SelectedViewModel { get; set; }

   public void DoRunIt()
   {
      SelectedViewModel.RunIt();
   }
}

one of the things I did try that compiles but throws runtime exception when used, is

Func<MyType,bool> expression = t => t.MyDescription = "Hello World";
MyFunc = t => expression((MyType)t);

Body:
There is a way to do this. It uses the ability for all delegates (Func<MyType, bool> is a delegate) to be cast to Delegate.

You'd change IOption and Option to this:

public interface IOption
{
    public string Description { get; set; }
    Func<T, bool> GetMyFunc<T>();
}

public class Option : IOption
{
    string description;
    private Delegate expression;

    public Option(string description, Delegate expression)
    {
        this.description = description;
        this.expression = expression;
    }

    public string Description { get; set; }
    public Func<T, bool> GetMyFunc<T>() => (Func<T, bool>)this.expression;
}

Then MyClass works as expected (except for the other syntax error in your code).

You then just need to change RunIt on Generic<T> to this:

public override void RunIt()
{
    var result = _context.Set<T>().Where(SelectedOption?.GetMyFunc<T>());
    // process result
}


答:
You can extract the year from the date. For each userid subtract the row number by number of values that are <= 2017.

```<code>library(dplyr)

df %>%
  mutate(date = as.Date(date),
         year = lubridate::year(date)) %>%
  arrange(userid, date) %>%
  group_by(userid) %>%
  mutate(rownumber = pmax(row_number() - sum(year <= 2017), 0)) %>%
  ungroup

#  userid date        year rownumber
#  <chr>  <date>     <dbl>     <int>
#1 1      2016-10-23  2016         0
#2 1      2018-01-01  2018         1
#3 1      2020-03-03  2020         2
#4 2      2008-09-04  2008         0
#5 2      2021-08-08  2021         1
#6 3      2019-10-02  2019         1
#7 3      2022-01-02  2022         2
</code>```

Title: get row number of group but with condition in R

Body:
I have a dataframe that has been sorted by userid and date as below:

df <- data.frame(
  userid = c("1", "1", "1", "2", "2", "3", "3"),
  date = c("2016-10-23", "2018-01-01", "2020-03-03", "2008-09-04", "2021-08-08", "2019-10-02", "2022-01-02")
)

 userid       date
      1 2016-10-23
      1 2018-01-01
      1 2020-03-03
      2 2008-09-04
      2 2021-08-08
      3 2019-10-02
      3 2022-01-02

I want to group by userid and assign row numbers, BUT anything before 2017 should be row number 0:

df2 <- data.frame(
  userid = c("1", "1", "1", "2", "2", "3", "3"),
  date = c("2016-10-23", "2018-01-01", "2020-03-03", "2008-09-04", "2021-08-08", "2019-10-02", "2022-01-02"),
  rownumber = c("0", "1", "2", "0", "1", "1", "2")
)

 userid       date rownumber
      1 2016-10-23         0
      1 2018-01-01         1
      1 2020-03-03         2
      2 2008-09-04         0
      2 2021-08-08         1
      3 2019-10-02         1
      3 2022-01-02         2

As you can see, the dates with years 2016 and 2008 have been assigned as 0 and the rownumber increments from 1 excluding those.

I have tried the below, but it does not assign 0 to dates before 2017.

df %>%
  group_by(userid) %>%
  mutate(rownumber = row_number()) %>%
  ungroup()

Thanks!

Body:
You can extract the year from the date. For each userid subtract the row number by number of values that are <= 2017.

library(dplyr)

df %>%
  mutate(date = as.Date(date),
         year = lubridate::year(date)) %>%
  arrange(userid, date) %>%
  group_by(userid) %>%
  mutate(rownumber = pmax(row_number() - sum(year <= 2017), 0)) %>%
  ungroup

#  userid date        year rownumber
#  <chr>  <date>     <dbl>     <int>
#1 1      2016-10-23  2016         0
#2 1      2018-01-01  2018         1
#3 1      2020-03-03  2020         2
#4 2      2008-09-04  2008         0
#5 2      2021-08-08  2021         1
#6 3      2019-10-02  2019         1
#7 3      2022-01-02  2022         2


问:
How to get the part of a file after the first line that matches a regular expression
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

```<code>cat file | grep 'TERMINATE'     # It is found on line 534
</code>```

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

答:
The following will print the line matching TERMINATE till the end of the file:

```<code>sed -n -e '/TERMINATE/,$p'
</code>```

Explained: -n disables default behavior of sed of printing each line after executing its script on it, -e indicated a script to sed, /TERMINATE/,$ is an address (line) range selection meaning the first line matching the TERMINATE regular expression (like grep) to the end of the file ($), and p is the print command which prints the current line.

This will print from the line that follows the line matching TERMINATE till the end of the file:
(from AFTER the matching line to EOF, NOT including the matching line)

```<code>sed -e '1,/TERMINATE/d'
</code>```

Explained: 1,/TERMINATE/ is an address (line) range selection meaning the first line for the input to the 1st line matching the TERMINATE regular expression, and d is the delete command which delete the current line and skip to the next line.  As sed default behavior is to print the lines, it will print the lines after TERMINATE  to the end of input.

If you want the lines before TERMINATE:

```<code>sed -e '/TERMINATE/,$d'
</code>```

And if you want both lines before and after TERMINATE in two different files in a single pass:

```<code>sed -e '1,/TERMINATE/w before
/TERMINATE/,$w after' file
</code>```

The before and after files will contain the line with terminate, so to process each you need to use:

```<code>head -n -1 before
tail -n +2 after
</code>```

IF you do not want to hard code the filenames in the sed script, you can:

```<code>before=before.txt
after=after.txt
sed -e "1,/TERMINATE/w $before
/TERMINATE/,\$w $after" file
</code>```

But then you have to escape the $ meaning the last line so the shell will not try to expand the $w variable (note that we now use double quotes around the script instead of single quotes).

I forgot to tell that the new line is important after the filenames in the script so that sed knows that the filenames end.

How would you replace the hardcoded TERMINATE by a variable?

You would make a variable for the matching text and then do it the same way as the previous example:

```<code>matchtext=TERMINATE
before=before.txt
after=after.txt
sed -e "1,/$matchtext/w $before
/$matchtext/,\$w $after" file
</code>```

to use a variable for the matching text with the previous examples:

```<code>## Print the line containing the matching text, till the end of the file:
## (from the matching line to EOF, including the matching line)
matchtext=TERMINATE
sed -n -e "/$matchtext/,\$p"
</code>```

```<code>## Print from the line that follows the line containing the
## matching text, till the end of the file:
## (from AFTER the matching line to EOF, NOT including the matching line)
matchtext=TERMINATE
sed -e "1,/$matchtext/d"
</code>```

```<code>## Print all the lines before the line containing the matching text:
## (from line-1 to BEFORE the matching line, NOT including the matching line)
matchtext=TERMINATE
sed -e "/$matchtext/,\$d"
</code>```

The important points about replacing text with variables in these cases are:

Variables ($variablename) enclosed in single quotes ['] won't "expand" but variables inside double quotes ["] will. So, you have to change all the single quotes to double quotes if they contain text you want to replace with a variable.

The sed ranges also contain a $ and are immediately followed by a letter like: $p, $d, $w. They will also look like variables to be expanded, so you have to escape those $ characters with a backslash [\] like: \$p, \$d, \$w.

Body:
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

cat file | grep 'TERMINATE'     # It is found on line 534

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

Body:
The following will print the line matching TERMINATE till the end of the file:

sed -n -e '/TERMINATE/,$p'

Explained: -n disables default behavior of sed of printing each line after executing its script on it, -e indicated a script to sed, /TERMINATE/,$ is an address (line) range selection meaning the first line matching the TERMINATE regular expression (like grep) to the end of the file ($), and p is the print command which prints the current line.

This will print from the line that follows the line matching TERMINATE till the end of the file:
(from AFTER the matching line to EOF, NOT including the matching line)

sed -e '1,/TERMINATE/d'

Explained: 1,/TERMINATE/ is an address (line) range selection meaning the first line for the input to the 1st line matching the TERMINATE regular expression, and d is the delete command which delete the current line and skip to the next line.  As sed default behavior is to print the lines, it will print the lines after TERMINATE  to the end of input.

If you want the lines before TERMINATE:

sed -e '/TERMINATE/,$d'

And if you want both lines before and after TERMINATE in two different files in a single pass:

sed -e '1,/TERMINATE/w before
/TERMINATE/,$w after' file

The before and after files will contain the line with terminate, so to process each you need to use:

head -n -1 before
tail -n +2 after

IF you do not want to hard code the filenames in the sed script, you can:

before=before.txt
after=after.txt
sed -e "1,/TERMINATE/w $before
/TERMINATE/,\$w $after" file

But then you have to escape the $ meaning the last line so the shell will not try to expand the $w variable (note that we now use double quotes around the script instead of single quotes).

I forgot to tell that the new line is important after the filenames in the script so that sed knows that the filenames end.

How would you replace the hardcoded TERMINATE by a variable?

You would make a variable for the matching text and then do it the same way as the previous example:

matchtext=TERMINATE
before=before.txt
after=after.txt
sed -e "1,/$matchtext/w $before
/$matchtext/,\$w $after" file

to use a variable for the matching text with the previous examples:

## Print the line containing the matching text, till the end of the file:
## (from the matching line to EOF, including the matching line)
matchtext=TERMINATE
sed -n -e "/$matchtext/,\$p"

## Print from the line that follows the line containing the
## matching text, till the end of the file:
## (from AFTER the matching line to EOF, NOT including the matching line)
matchtext=TERMINATE
sed -e "1,/$matchtext/d"

## Print all the lines before the line containing the matching text:
## (from line-1 to BEFORE the matching line, NOT including the matching line)
matchtext=TERMINATE
sed -e "/$matchtext/,\$d"

The important points about replacing text with variables in these cases are:

Variables ($variablename) enclosed in single quotes ['] won't "expand" but variables inside double quotes ["] will. So, you have to change all the single quotes to double quotes if they contain text you want to replace with a variable.

The sed ranges also contain a $ and are immediately followed by a letter like: $p, $d, $w. They will also look like variables to be expanded, so you have to escape those $ characters with a backslash [\] like: \$p, \$d, \$w.


问:
Flutter Plug In
Dart SDK Screen PrintFlutter Plugin Screen Print ImageHi I uninstalled the flutter plug in from the android studio by mistake how do I reinstall it again? As the result I cannot run any dart files nor start a new flutter project. I also keep getting and error that dart sdk files not configure. So in short flutter is not running from the android studios. I tried to uninstall android studios but that didn't work</p>

答: Run Android studio and from plugin setting search 'flutter' and then 'installed', like it's shown on this screenshot

Title: Flutter Plug In


问:
How do I center images in a Java Script random image generator?
I am making a random image generator for a school assignment, how do I center the image?
I am new to java script and would like to know how to center the images made by the generator.
I have tried a few different ways of centering the code but haven't found any way of doing it.
If there are workarounds to get it centered that is alright as I just need to have it centered.
Here is the code;</p>
```<code>    <html>
<head>
<title>Display random images</title>
<style>
body {
margin-top: 30px;
}
</style>
</head>

<script>
function displayRandomImages()
{

   //array of images with image location, height, and width
   var imageArray = [
   {
     //address URL of the image
     src: "https://i.insider.com/5d8a4d172e22af08c029c929?width=750&format=jpeg&auto=webp",
     //size for the image to be display on webpage
     width: "650",
     height: "500",
   },
   {
     src: "https://static.stacker.com/s3fs-public/styles/slide_desktop/s3/editedWWIIMonopolySPYSCAPE2000xpngv1587097885.PNG",
     width: "650",
     height: "500",

   },
   {
     src: "https://images-na.ssl-images-amazon.com/images/I/71IbpNx-3oL._SL1000_.jpg",
     width: "650",
     height: "500",
   },
   {
     src: "https://cdn.vox-cdn.com/thumbor/wj2qaxojsQT3DrUbP78SVW1fpMs=/0x0:1500x1500/1200x800/filters:focal(630x630:870x870)/cdn.vox-cdn.com/uploads/chorus_image/image/65772083/81C985A22GL._SL1500_.0.jpg",
     width: "650",
     height: "500",
    } ];

    //find the length of the array of images
    var arrayLength = imageArray.length;
    var newArray = [];
    for (var i = 0; i < arrayLength; i++) {
        newArray[i] = new Image();
        newArray[i].src = imageArray[i].src;
        newArray[i].width = imageArray[i].width;
        newArray[i].height = imageArray[i].height;
    }

  // create random image number
  function getRandomNum(min, max)
  {
      // generate and return a random number for the image to be displayed
      imgNo = Math.floor(Math.random() * (max - min + 1)) + min;
      return newArray[imgNo];
  }

  // 0 is first image and (preBuffer.length - 1) is last image of the array
  var newImage = getRandomNum(0, newArray.length - 1);

  // remove the previous images
  var images = document.getElementsByTagName('img');
  var l = images.length;
  for (var p = 0; p < l; p++) {
     images[0].parentNode.removeChild(images[0]);
  }
  // display the new random image
  document.body.appendChild(newImage);
}

</script>

<body>
<div>
<center>
<h2 style="color:green"> Random Image Generator </h2>
<h4> Press the button to display and change the image </h4>
<button onclick="displayRandomImages();"> Display Images </button>
</center>

</div>
</body>
</html>
</code>```

答:
Add a custom CSS to the image to render in the middle or add it into the center element by referring it to an Id.

//array of images with image location, height, and width
const imageArray = [
   {
     //address URL of the image
     src: "https://i.insider.com/5d8a4d172e22af08c029c929?width=750&format=jpeg&auto=webp",
     //size for the image to be display on webpage
     width: "450",
     height: "300",
   },
   {
     src: "https://static.stacker.com/s3fs-public/styles/slide_desktop/s3/editedWWIIMonopolySPYSCAPE2000xpngv1587097885.PNG",
     width: "450",
     height: "300",

   },
   {
     src: "https://images-na.ssl-images-amazon.com/images/I/71IbpNx-3oL._SL1000_.jpg",
     width: "450",
     height: "300",
   },
   {
     src: "https://cdn.vox-cdn.com/thumbor/wj2qaxojsQT3DrUbP78SVW1fpMs=/0x0:1500x1500/1200x800/filters:focal(630x630:870x870)/cdn.vox-cdn.com/uploads/chorus_image/image/65772083/81C985A22GL._SL1500_.0.jpg",
     width: "450",
     height: "300",
    }
];
var arrayLength = imageArray.length;
var newArray = [];
for (var i = 0; i < arrayLength; i++) {
    newArray[i] = new Image();
    newArray[i].src = imageArray[i].src;
    newArray[i].width = imageArray[i].width;
    newArray[i].height = imageArray[i].height;
    newArray[i].className = "center-image";
}

// create random image number
function getRandomNum(min, max) {
    // generate and return a random number for the image to be displayed
    imgNo = Math.floor(Math.random() * (max - min + 1)) + min;
    return newArray[imgNo];
}

function displayRandomImages() {
  // 0 is first image and (preBuffer.length - 1) is last image of the array
  var newImage = getRandomNum(0, imageArray.length - 1);
  // remove the previous images
  var images = document.getElementsByTagName('img');
  var l = images.length;
  for (var p = 0; p < l; p++) {
     images[0].parentNode.removeChild(images[0]);
  }
  // display the new random image
  document.body.appendChild(newImage);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin-top: 30px;
}

.center-image {
  display: block;
  margin: 0 auto;
}</code>```

 Random Image Generator

 Press the button to display and change the image

    <button onclick="displayRandomImages();"> Display Images </button>

```

Body:
I am making a random image generator for a school assignment, how do I center the image?
I am new to java script and would like to know how to center the images made by the generator.
I have tried a few different ways of centering the code but haven't found any way of doing it.
If there are workarounds to get it centered that is alright as I just need to have it centered.
Here is the code;

<title>Display random images</title>

 Random Image Generator

 Press the button to display and change the image

<button onclick="displayRandomImages();"> Display Images </button>

Body:
Add a custom CSS to the image to render in the middle or add it into the center element by referring it to an Id.

//array of images with image location, height, and width
const imageArray = [
   {
     //address URL of the image
     src: "https://i.insider.com/5d8a4d172e22af08c029c929?width=750&format=jpeg&auto=webp",
     //size for the image to be display on webpage
     width: "450",
     height: "300",
   },
   {
     src: "https://static.stacker.com/s3fs-public/styles/slide_desktop/s3/editedWWIIMonopolySPYSCAPE2000xpngv1587097885.PNG",
     width: "450",
     height: "300",

   },
   {
     src: "https://images-na.ssl-images-amazon.com/images/I/71IbpNx-3oL._SL1000_.jpg",
     width: "450",
     height: "300",
   },
   {
     src: "https://cdn.vox-cdn.com/thumbor/wj2qaxojsQT3DrUbP78SVW1fpMs=/0x0:1500x1500/1200x800/filters:focal(630x630:870x870)/cdn.vox-cdn.com/uploads/chorus_image/image/65772083/81C985A22GL._SL1500_.0.jpg",
     width: "450",
     height: "300",
    }
];
var arrayLength = imageArray.length;
var newArray = [];
for (var i = 0; i < arrayLength; i++) {
    newArray[i] = new Image();
    newArray[i].src = imageArray[i].src;
    newArray[i].width = imageArray[i].width;
    newArray[i].height = imageArray[i].height;
    newArray[i].className = "center-image";
}

// create random image number
function getRandomNum(min, max) {
    // generate and return a random number for the image to be displayed
    imgNo = Math.floor(Math.random() * (max - min + 1)) + min;
    return newArray[imgNo];
}

function displayRandomImages() {
  // 0 is first image and (preBuffer.length - 1) is last image of the array
  var newImage = getRandomNum(0, imageArray.length - 1);
  // remove the previous images
  var images = document.getElementsByTagName('img');
  var l = images.length;
  for (var p = 0; p < l; p++) {
     images[0].parentNode.removeChild(images[0]);
  }
  // display the new random image
  document.body.appendChild(newImage);
}

body {
  margin-top: 30px;
}

.center-image {
  display: block;
  margin: 0 auto;
}

<div>
  <center>
    <h2 style="color:green"> Random Image Generator </h2>
    <h4> Press the button to display and change the image </h4>
    <button onclick="displayRandomImages();"> Display Images </button>
  </center>
</div>


问:
How to run jmeter samplers parallel for multiple requests when one request is dependent on another request
I have three requests(req1,req2,req3) which execute based on the CSV config data, the first request will execute 1 time, request 2 will also execute 1 time and request 3 will execute 12 times, so request 2 input is dependent on the request 1 output and request3 input is dependent on request 2 output like that I have to loop for 10 times. so my question is, I want to run the requests with 10 users but when I run like that it's failing due to users are picking the requests randomly and getting lost the data and failing the HTTP requests, Can you please suggest to me which approach will help to run with multiple users parallel with the group of HTTP requests (req1 then req2 then req3) in the same order for 10 times.

I have tried with the Critical section controller which is executing one user at a time and the Parallel controller which is picking the requests randomly
Ex: It's picking Req2, Req3, and then Req1.

Below I am attaching my thread group structure, synchronized timer properties, and thread group properties.
[1]: https://i.stack.imgur.com/P1fMn.jpg

答:
The easiest is going for the Parallel Controller, it executes all its children in parallel so if you need to invoke req3 10 times - put it 10 times under the Parallel Controller.

You can use Test Fragment and Module Controller like:


问:
Flutter: right overflowed by 23 pixels ("add task" button)
so basically i'm making a button "add task" for my to-do list app and it shows "right overflowed by 23 pixels"

Here's my "home_page.dart" code for the "add task" button

```<code>_addTaskBar(){
  return Container(
   margin: const EdgeInsets.only(left:20, right:20, top:10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(DateFormat.yMMMMd().format(DateTime.now()),
                  style: subHeadingStyle,
                  ),
                  Text("Today",
                  style: headingStyle,
                  )
                ],
              ),
            MyButton(label: "+ Add Task", onTap: ()=>null)
          ],
        ),
    );
}
</code>```

And this is my "button.dart" code for the "add task" button as well

```<code> class MyButton extends StatelessWidget {
  final String label;
  final Function()? onTap;
  const MyButton({ Key? key, required this.label, required this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 120,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: primaryClr
        ),
        child: Text(
          label,
          style: const TextStyle(
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}
</code>```

The result of the code is this
enter image description here

I need help to anyone who can solve this issue of mine. Thank you

答:
Ok So from the code that you have added i have created an example for you.

As you have not provided the styles for the text, but i have used the max font size to overflow the button from right.

So I have used the Expanded widget for the MyButton class and removed the constant width and height for the AddTask buttons, check the code below you will get it.

```<code>import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: _addTaskBar(),
      ),
    );
  }

  _addTaskBar() {
    return Container(
      margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                DateFormat.yMMMMd().format(DateTime.now()),
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 32,
                ),
              ),
              const Text(
                "Today",
                style: const TextStyle(color: Colors.white),
              )
            ],
          ),
          Expanded(child: MyButton(label: "+ Add Task", onTap: () => null))
        ],
      ),
    );
  }
}

class MyButton extends StatelessWidget {
  final String label;
  final Function()? onTap;
  const MyButton({Key? key, required this.label, required this.onTap})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        GestureDetector(
          onTap: onTap,
          child: Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Colors.blue,
            ),
            child: Center(
              child: Text(
                label,
                style: const TextStyle(
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

</code>```

Let me know if it works.

Body:
so basically i'm making a button "add task" for my to-do list app and it shows "right overflowed by 23 pixels"

Here's my "home_page.dart" code for the "add task" button

_addTaskBar(){
  return Container(
   margin: const EdgeInsets.only(left:20, right:20, top:10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(DateFormat.yMMMMd().format(DateTime.now()),
                  style: subHeadingStyle,
                  ),
                  Text("Today",
                  style: headingStyle,
                  )
                ],
              ),
            MyButton(label: "+ Add Task", onTap: ()=>null)
          ],
        ),
    );
}

And this is my "button.dart" code for the "add task" button as well

 class MyButton extends StatelessWidget {
  final String label;
  final Function()? onTap;
  const MyButton({ Key? key, required this.label, required this.onTap}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: 120,
        height: 60,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20),
          color: primaryClr
        ),
        child: Text(
          label,
          style: const TextStyle(
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}

The result of the code is this
enter image description here

I need help to anyone who can solve this issue of mine. Thank you

Body:
Ok So from the code that you have added i have created an example for you.

As you have not provided the styles for the text, but i have used the max font size to overflow the button from right.

So I have used the Expanded widget for the MyButton class and removed the constant width and height for the AddTask buttons, check the code below you will get it.

import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

void main() {
  runApp(MaterialApp(
    home: MyApp(),
  ));
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: _addTaskBar(),
      ),
    );
  }

  _addTaskBar() {
    return Container(
      margin: const EdgeInsets.only(left: 20, right: 20, top: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                DateFormat.yMMMMd().format(DateTime.now()),
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 32,
                ),
              ),
              const Text(
                "Today",
                style: const TextStyle(color: Colors.white),
              )
            ],
          ),
          Expanded(child: MyButton(label: "+ Add Task", onTap: () => null))
        ],
      ),
    );
  }
}

class MyButton extends StatelessWidget {
  final String label;
  final Function()? onTap;
  const MyButton({Key? key, required this.label, required this.onTap})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        GestureDetector(
          onTap: onTap,
          child: Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(20),
              color: Colors.blue,
            ),
            child: Center(
              child: Text(
                label,
                style: const TextStyle(
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}

Let me know if it works.


答:
You just need the center then that will be something like this:

```<code><html>

<head>
  <title>Display random images</title>
  <style>
    body {
      margin-top: 30px;
    }

    img {
      display: block;
      margin: 50px auto;
    }
  </style>
</head>

<script>
  function displayRandomImages() {

    //array of images with image location, height, and width
    var imageArray = [{
        //address URL of the image
        src: "https://i.insider.com/5d8a4d172e22af08c029c929?width=750&format=jpeg&auto=webp",
        //size for the image to be display on webpage
        width: "650",
        height: "500",
      },
      {
        src: "https://static.stacker.com/s3fs-public/styles/slide_desktop/s3/editedWWIIMonopolySPYSCAPE2000xpngv1587097885.PNG",
        width: "650",
        height: "500",

      },
      {
        src: "https://images-na.ssl-images-amazon.com/images/I/71IbpNx-3oL._SL1000_.jpg",
        width: "650",
        height: "500",
      },
      {
        src: "https://cdn.vox-cdn.com/thumbor/wj2qaxojsQT3DrUbP78SVW1fpMs=/0x0:1500x1500/1200x800/filters:focal(630x630:870x870)/cdn.vox-cdn.com/uploads/chorus_image/image/65772083/81C985A22GL._SL1500_.0.jpg",
        width: "650",
        height: "500",
      }
    ];

    //find the length of the array of images
    var arrayLength = imageArray.length;
    var newArray = [];
    for (var i = 0; i < arrayLength; i++) {
      newArray[i] = new Image();
      newArray[i].src = imageArray[i].src;
      newArray[i].width = imageArray[i].width;
      newArray[i].height = imageArray[i].height;
    }

    // create random image number
    function getRandomNum(min, max) {
      // generate and return a random number for the image to be displayed
      imgNo = Math.floor(Math.random() * (max - min + 1)) + min;
      return newArray[imgNo];
    }

    // 0 is first image and (preBuffer.length - 1) is last image of the array
    var newImage = getRandomNum(0, newArray.length - 1);

    // remove the previous images
    var images = document.getElementsByTagName('img');
    var l = images.length;
    for (var p = 0; p < l; p++) {
      images[0].parentNode.removeChild(images[0]);
    }
    // display the new random image
    document.body.appendChild(newImage);
  }
</script>

<body>
  <div>
    <center>
      <h2 style="color:green"> Random Image Generator </h2>
      <h4> Press the button to display and change the image </h4>
      <button onclick="displayRandomImages();"> Display Images </button>
    </center>

  </div>
</body>

</html>
</code>```

I only updated your style blocks, with css for Image. That's all

Title: How do I center images in a Java Script random image generator?

Body:
You just need the center then that will be something like this:

<html>

<head>
  <title>Display random images</title>
  <style>
    body {
      margin-top: 30px;
    }

    img {
      display: block;
      margin: 50px auto;
    }
  </style>
</head>

<script>
  function displayRandomImages() {

    //array of images with image location, height, and width
    var imageArray = [{
        //address URL of the image
        src: "https://i.insider.com/5d8a4d172e22af08c029c929?width=750&format=jpeg&auto=webp",
        //size for the image to be display on webpage
        width: "650",
        height: "500",
      },
      {
        src: "https://static.stacker.com/s3fs-public/styles/slide_desktop/s3/editedWWIIMonopolySPYSCAPE2000xpngv1587097885.PNG",
        width: "650",
        height: "500",

      },
      {
        src: "https://images-na.ssl-images-amazon.com/images/I/71IbpNx-3oL._SL1000_.jpg",
        width: "650",
        height: "500",
      },
      {
        src: "https://cdn.vox-cdn.com/thumbor/wj2qaxojsQT3DrUbP78SVW1fpMs=/0x0:1500x1500/1200x800/filters:focal(630x630:870x870)/cdn.vox-cdn.com/uploads/chorus_image/image/65772083/81C985A22GL._SL1500_.0.jpg",
        width: "650",
        height: "500",
      }
    ];

    //find the length of the array of images
    var arrayLength = imageArray.length;
    var newArray = [];
    for (var i = 0; i < arrayLength; i++) {
      newArray[i] = new Image();
      newArray[i].src = imageArray[i].src;
      newArray[i].width = imageArray[i].width;
      newArray[i].height = imageArray[i].height;
    }

    // create random image number
    function getRandomNum(min, max) {
      // generate and return a random number for the image to be displayed
      imgNo = Math.floor(Math.random() * (max - min + 1)) + min;
      return newArray[imgNo];
    }

    // 0 is first image and (preBuffer.length - 1) is last image of the array
    var newImage = getRandomNum(0, newArray.length - 1);

    // remove the previous images
    var images = document.getElementsByTagName('img');
    var l = images.length;
    for (var p = 0; p < l; p++) {
      images[0].parentNode.removeChild(images[0]);
    }
    // display the new random image
    document.body.appendChild(newImage);
  }
</script>

<body>
  <div>
    <center>
      <h2 style="color:green"> Random Image Generator </h2>
      <h4> Press the button to display and change the image </h4>
      <button onclick="displayRandomImages();"> Display Images </button>
    </center>

  </div>
</body>

</html>

I only updated your style blocks, with css for Image. That's all


问:
Run one specific function inside observe only when we get data not when activity is recreated
I have this observer inside an activity and I want to make part of it run only when we have new data and not when the activity is recreated (like when you rotate screen)

```<code>signInViewModel.signInResponse.observe(this, {
                response->  when(response){
            is NetworkResult.Success ->{
                response.data?.let {
                    signInViewModel.saveJwt(it)

                }
            }

            is NetworkResult.Error ->{
                errorMsg.text = response.message.toString()

            }

            is NetworkResult.Loading -> {

            }
        }
        })
</code>```

I want to run this signInViewModel.saveJwt(it) only when we get new data and other part run when we get new data and when we recreate the activity.

答:
As I understand, you want to observe your NetworkResult only once when it's in (Success) state, and multiple times for other status as your replay for @Gouse Mohiddin answer. I'll recommend for your same @Gouse Mohiddin answer to use StateFlow with some different changes...

First of all you need to create some method in your ViewModel to reset your stateFlow to your default.

ViewModel

```<code>private val _signInResponse = MutableStateFlow<NetworkResult(NetworkResult.Loading)
val signInResponse : StateFlow<NetworkResult> = _signInResponse.asStateFlow()

fun resetSignInResponse(){
    _signInResponse.value = _signInResponse.value.copy(NetworkResult.Default)
}
</code>```

When you receive your new data use same

```<code>_signInResponse.value = _signInResponse.value.copy(NetworkResult.Success(jwt))
</code>```

Activity

```<code>signInViewModel.signInResponse.collect { response ->
        when (response) {
            is NetworkResult.Success -> {
                response.data?.let {
                    signInViewModel.saveJwt(it)
                    //After receiving success data, reset your state to default
                    //this will never run again unless you receive new data
                    signInViewModel.resetSignInResponse()
                }
            }

            is NetworkResult.Error -> {
                //this will run always if you hold an error in state
                errorMsg.text = response.message.toString()
            }

            is NetworkResult.Default -> {
                //Ignore Or Apply the default actions you want
            }
        }
    }
</code>```

and don't forget to reset your state to default before any updates (emits).

```<code>resetSignInResponse()
</code>```

Body:
I have this observer inside an activity and I want to make part of it run only when we have new data and not when the activity is recreated (like when you rotate screen)

signInViewModel.signInResponse.observe(this, {
                response->  when(response){
            is NetworkResult.Success ->{
                response.data?.let {
                    signInViewModel.saveJwt(it)

                }
            }

            is NetworkResult.Error ->{
                errorMsg.text = response.message.toString()

            }

            is NetworkResult.Loading -> {

            }
        }
        })

I want to run this signInViewModel.saveJwt(it) only when we get new data and other part run when we get new data and when we recreate the activity.

Body:
As I understand, you want to observe your NetworkResult only once when it's in (Success) state, and multiple times for other status as your replay for @Gouse Mohiddin answer. I'll recommend for your same @Gouse Mohiddin answer to use StateFlow with some different changes...

First of all you need to create some method in your ViewModel to reset your stateFlow to your default.

ViewModel

private val _signInResponse = MutableStateFlow<NetworkResult(NetworkResult.Loading)
val signInResponse : StateFlow<NetworkResult> = _signInResponse.asStateFlow()

fun resetSignInResponse(){
    _signInResponse.value = _signInResponse.value.copy(NetworkResult.Default)
}

When you receive your new data use same

_signInResponse.value = _signInResponse.value.copy(NetworkResult.Success(jwt))

Activity

signInViewModel.signInResponse.collect { response ->
        when (response) {
            is NetworkResult.Success -> {
                response.data?.let {
                    signInViewModel.saveJwt(it)
                    //After receiving success data, reset your state to default
                    //this will never run again unless you receive new data
                    signInViewModel.resetSignInResponse()
                }
            }

            is NetworkResult.Error -> {
                //this will run always if you hold an error in state
                errorMsg.text = response.message.toString()
            }

            is NetworkResult.Default -> {
                //Ignore Or Apply the default actions you want
            }
        }
    }

and don't forget to reset your state to default before any updates (emits).

resetSignInResponse()


问:
Why does eclipse SOMETIMES prompt me which device to launch my app on?
Why does eclipse SOMETIMES prompt me which device to launch my app on when there is only 1 phone connected to my machine? Sometimes, it stays like this for months.... how to fix?

It says my target phone is 2.3.4    and there is a small yellow exclamation warning next to it.

答:
Its because your application Target mode has set to manual. To solve :

```<code>Right Click on your project-> Run as -> Select Run Configurations ->
In that select Target Tab ->Select Automatic instead of manual

Click on Apply and run.
</code>```

Now your app doesn't prompt for a device.

For a reverse case Select Manual.

Hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
Its because your application Target mode has set to manual. To solve :

Right Click on your project-> Run as -> Select Run Configurations ->
In that select Target Tab ->Select Automatic instead of manual

Click on Apply and run.

Now your app doesn't prompt for a device.

For a reverse case Select Manual.

Hope it helps.


问:
Interface inheriting TypeScript real world usage
I have been learning typeScript for few days where I came across with the interface implementation in typeScript but could not understand it properly can anyone explain it a bit more for me with some real world example.</p>

答:
An interface is just simply a declaration of an API. It defines what members/fields are available and what their types are.

In TypeScript, an interface have 2 main uses:

Declaring a data set structure (similar to a struct in C)

Declaring an API.

An interface itself has no implementation. You must implement an interface.

Suppose we have the following interface:

```<code>interface IEmployee {
    firstName: string;
    lastName: string;
}

let employee: IEmployee = {}; // this errors, it does not properly implement the interface

// This is ok, it implements the interface
let employee: IEmployee = {
    firstName: "John",
    lastName: "Smith"
};
</code>```

This is a good, we assert that we aren't missing any keys when crafting an IEmployee object.

Now let's take another API example, suppose we want to make something stringifiable.

```<code>interface IStringifiable {
    stringify(): string;
}
</code>```

This interface declares that a single method name stringify must exists, it accepts no parameters, and should return a string.

```<code>class MyObject implements IStringifiable {
   ...

    public stringify(): string {
        return "...";
    }
}
</code>```

Now we have a class that implements the IStringifiable interface. Why is this useful? Because interfaces in itself is a type, therefore you can accept anything that is a or implements IStringifiable.

```<code>function toString(obj: IStringifiable) {
    console.log(obj.stringify());
}
</code>```

A lot of concepts here are part of the Object-Oriented Programming paradigm. So reading more on OOP make some of these concepts understandable.

Body:
An interface is just simply a declaration of an API. It defines what members/fields are available and what their types are.

In TypeScript, an interface have 2 main uses:

Declaring a data set structure (similar to a struct in C)

Declaring an API.

An interface itself has no implementation. You must implement an interface.

Suppose we have the following interface:

interface IEmployee {
    firstName: string;
    lastName: string;
}

let employee: IEmployee = {}; // this errors, it does not properly implement the interface

// This is ok, it implements the interface
let employee: IEmployee = {
    firstName: "John",
    lastName: "Smith"
};

This is a good, we assert that we aren't missing any keys when crafting an IEmployee object.

Now let's take another API example, suppose we want to make something stringifiable.

interface IStringifiable {
    stringify(): string;
}

This interface declares that a single method name stringify must exists, it accepts no parameters, and should return a string.

class MyObject implements IStringifiable {
   ...

    public stringify(): string {
        return "...";
    }
}

Now we have a class that implements the IStringifiable interface. Why is this useful? Because interfaces in itself is a type, therefore you can accept anything that is a or implements IStringifiable.

function toString(obj: IStringifiable) {
    console.log(obj.stringify());
}

A lot of concepts here are part of the Object-Oriented Programming paradigm. So reading more on OOP make some of these concepts understandable.


问:
Generating elements in Django from Python list
Im havin trouble generating elements from a for loop via iteration of a py list in Django.
Using Metro UI as front end framework.

```<code>import os
img_dir = os.listdir("static/img/sasha_banks")
#print(img_dir)
#  <img src="{% static 'img/sasha_banks/sasha_banks5.jpg' %}">
def sasha_files():
    sasha_dir = []
    for img in img_dir:
        sasha_dir.append(f'img/sasha_banks/{img}')
        print(sasha_dir)

sasha_files()
</code>```

Above python script works i jist cant seem to get to that sasha_dir list.

The commented  was the hard coded django that works, im just trying to read the directory, pushthe filepath and concat the files in dir and then iterate that list to create

```<code>{% for n in sasha_dir %}
      <img src="{% static sasha_dir[n] %}">
{% endfor %}

</code>```

答:
Use the inbuilt function glob

```<code>#Devil
from glob import glob
from ntpath import basename
img_dir = glob("static/img/sasha_banks/*")
print(sasha_dir)

def sasha_files():
    sasha_dir = []
    for img in img_dir:
        name = basename(img)
        sasha_dir.append('img/sasha_banks/' + name)
        print(sasha_dir)
</code>```

Body:
Im havin trouble generating elements from a for loop via iteration of a py list in Django.
Using Metro UI as front end framework.

import os
img_dir = os.listdir("static/img/sasha_banks")
#print(img_dir)
#
def sasha_files():
    sasha_dir = []
    for img in img_dir:
        sasha_dir.append(f'img/sasha_banks/{img}')
        print(sasha_dir)

sasha_files()

Above python script works i jist cant seem to get to that sasha_dir list.

The commented  was the hard coded django that works, im just trying to read the directory, pushthe filepath and concat the files in dir and then iterate that list to create

{% for n in sasha_dir %}

{% endfor %}

Body:
Use the inbuilt function glob

#Devil
from glob import glob
from ntpath import basename
img_dir = glob("static/img/sasha_banks/*")
print(sasha_dir)

def sasha_files():
    sasha_dir = []
    for img in img_dir:
        name = basename(img)
        sasha_dir.append('img/sasha_banks/' + name)
        print(sasha_dir)


问:
QmlProfiler : Plugin initialization failed: Cannot create OpenGL context
I use Qt 6.2.2 in ubuntu 20.04 and I install OpenGL like this:

```<code>sudo apt install libgl1-mesa-dev
</code>```

After I install my graphics card driver (NVDI 470.86) I get this error each time I open QtCreator IDE.

why did this happen and how can I fix this?

I cant compile examples that use qt quick like Qt Quick 3D - Custom Materials Example

QML debugging is enabled. Only use this in a safe environment.
qt.quick3d.general: Unable to find ideal GL version. QGLXContext:
Failed to create dummy context QRhiGles2: Failed to create temporary
context QRhiGles2: Failed to create context Failed to create RHI
(backend 2) Failed to initialize graphics backend for OpenGL.

output pictures:

output from glxinfo | egrep -i version

答:
I understand that qt creator save its settings in /home/username/.config/QtProject and It understand OpenGL from there.

So I delete my .config folder and reboot my system and let my OS create it again this Fix my problem but as @merosss said that he change his usermod to the video that was one way because qt creator will create it in that path and problem will fix again.

Since I install the NVIDIA driver it seems that Qt cant understand which OpenGL should use and that problem happens.

Body:
I use Qt 6.2.2 in ubuntu 20.04 and I install OpenGL like this:

sudo apt install libgl1-mesa-dev

After I install my graphics card driver (NVDI 470.86) I get this error each time I open QtCreator IDE.

why did this happen and how can I fix this?

I cant compile examples that use qt quick like Qt Quick 3D - Custom Materials Example

QML debugging is enabled. Only use this in a safe environment.
qt.quick3d.general: Unable to find ideal GL version. QGLXContext:
Failed to create dummy context QRhiGles2: Failed to create temporary
context QRhiGles2: Failed to create context Failed to create RHI
(backend 2) Failed to initialize graphics backend for OpenGL.

output pictures:

output from glxinfo | egrep -i version


问:
gatsby-plugin-preact is not working with react-bootstrap
I integrated react-bootstrap in my gatsby project but it is not working with gatsby-plugin-preact  plugin.
If I comment out that line in gatsby-config file then the project develop successfully else it's failing with below screenshot detail.
Any idea or help.
Thank you

答:
This should now be fixed, made a PR to correct it in Gatsby. It's not an issue in your setup, but upstream.

https://github.com/gatsbyjs/gatsby/pull/34666


问:
How can I sum the product of two list items using for loop in python?
I am trying to sum the product of two different list items in the same line using for loop, but I am not getting the output as expected.

My example code:

```<code>a = [1,2,3]
b = [4,5,6]

sum = 0              # optional element

score = ((sum+(a(i)*b(i)) for i in range(len(a)))

print score
</code>```

output:

```<code><generator object <genexpr> at 0x027284B8>
</code>```

expected output:

```<code>32                   # 0+(1*4)+(2*5)+(3*6)
</code>```

答:
an unconventional method: the LAMBDA function.</p>
```<code>a = [1,2,3]
b = [4,5,6]
pwr = sum(map(lambda a,b:a*b, a,b))
print(pwr)
</code>```

Body:
I am trying to sum the product of two different list items in the same line using for loop, but I am not getting the output as expected.

My example code:

a = [1,2,3]
b = [4,5,6]

sum = 0              # optional element

score = ((sum+(a(i)*b(i)) for i in range(len(a)))

print score

output:

<generator object <genexpr> at 0x027284B8>

expected output:

32                   # 0+(1*4)+(2*5)+(3*6)

Body:
an unconventional method: the LAMBDA function.

a = [1,2,3]
b = [4,5,6]
pwr = sum(map(lambda a,b:a*b, a,b))
print(pwr)


问:
React-admin rendering runtime resources multiple times
I'm following this design pattern from React-admin to define the parent Team resource,
but the useEffect hook is being called 4 times on every page refresh

The context provider is just to be able to pass the Teams list to a select in the layout, if I remove it, the same problem happens

Is this expected behaviour?

```<code>const AdminEnterprise = () => {
  return (
    <AdminContext
      disableTelemetry
      authProvider={authProvider}
      dataProvider={dataProvider}
    >
      <TeamResources />
    </AdminContext>
  );
};

const TeamResources = () => {
  const dataProvider = useDataProvider();
  const [state, dispatch] = useReducer(teamReducer, {
    loading : true,
    teams : []
  })

  useEffect(() => {
    //This is called 4 times on page refresh
    console.log('querying user teams')
    dataProvider.getList('userTeams')
      .then(({data}) =>{
        dispatch({
          teams: data,
          selected: data[0].id,
          loading: false
        })
      })
      .catch(error => {
        dispatch({
          error: error,
          loading: false
        })
      })
  }, [])

  return (
    <TeamContext.Provider value={[state, dispatch]}>
      {state.loading? <></> : (
        <AdminUI layout={MyLayout} loginPage={CustomLoginPage} theme={myTheme}>
          <Resource name={`teams/${state.selected}/projects`} list={ProjectList} options={{label: 'Projects' }}/>
          <Resource name={`teams/${state.selected}`} />
        </AdminUI>
      )}
    </TeamContext.Provider>
  )
}
</code>```

答:
The "expected" behaviour is for anything inside useEffect() with an empty dependency array ([] as the second argument) to only run once.

The AdminContext tree is likely re-rendering based on changes to dataProvider or some other side-effects of invoking dataProvider.getList(). We can't see that, so it's tough to help.

Here's at least a suggested method to verify that the problem isn't inside TeamResources:

```<code># in Test.jsx
const Test = () => {
  console.log('Test is rendering.');

  useEffect(() => {
    console.log('Test, inside useEffect');
  }, []);

  return <></>;
};

# in AdminContext.jsx

    <AdminContext
      disableTelemetry
      authProvider={authProvider}
      dataProvider={dataProvider}
    >
      <Test />
      <TeamResources />
    </AdminContext>
</code>```

I'd suspect that 'Test, inside useEffect' is going to be logged more often than expected too.

Body:
I'm following this design pattern from React-admin to define the parent Team resource,
but the useEffect hook is being called 4 times on every page refresh

The context provider is just to be able to pass the Teams list to a select in the layout, if I remove it, the same problem happens

Is this expected behaviour?

const AdminEnterprise = () => {
  return (
    <AdminContext
      disableTelemetry
      authProvider={authProvider}
      dataProvider={dataProvider}
    >
      <TeamResources />
    </AdminContext>
  );
};

const TeamResources = () => {
  const dataProvider = useDataProvider();
  const [state, dispatch] = useReducer(teamReducer, {
    loading : true,
    teams : []
  })

  useEffect(() => {
    //This is called 4 times on page refresh
    console.log('querying user teams')
    dataProvider.getList('userTeams')
      .then(({data}) =>{
        dispatch({
          teams: data,
          selected: data[0].id,
          loading: false
        })
      })
      .catch(error => {
        dispatch({
          error: error,
          loading: false
        })
      })
  }, [])

  return (
    <TeamContext.Provider value={[state, dispatch]}>
      {state.loading? <></> : (
        <AdminUI layout={MyLayout} loginPage={CustomLoginPage} theme={myTheme}>
          <Resource name={`teams/${state.selected}/projects`} list={ProjectList} options={{label: 'Projects' }}/>
          <Resource name={`teams/${state.selected}`} />
        </AdminUI>
      )}
    </TeamContext.Provider>
  )
}

Body:
The "expected" behaviour is for anything inside useEffect() with an empty dependency array ([] as the second argument) to only run once.

The AdminContext tree is likely re-rendering based on changes to dataProvider or some other side-effects of invoking dataProvider.getList(). We can't see that, so it's tough to help.

Here's at least a suggested method to verify that the problem isn't inside TeamResources:

# in Test.jsx
const Test = () => {
  console.log('Test is rendering.');

  useEffect(() => {
    console.log('Test, inside useEffect');
  }, []);

  return <></>;
};

# in AdminContext.jsx

    <AdminContext
      disableTelemetry
      authProvider={authProvider}
      dataProvider={dataProvider}
    >
      <Test />
      <TeamResources />
    </AdminContext>

I'd suspect that 'Test, inside useEffect' is going to be logged more often than expected too.


问:
How do we tell if two sprites are colliding in Pygame Zero?
I recently started coding in Pygame Zero before starting Pygame. I was making a game and the I need to see if two of the sprites are colliding. How should I approach this?

The two sprites:
[1]: https://i.stack.imgur.com/bRcqC.png
[2]: https://i.stack.imgur.com/FwlES.png

```<code>import pgzrun
import rando[enter image description here][1]m

WIDTH=400
HEIGHT=400
score=0

game_over=False

coin=Actor("coin")
fox=Actor("fox")

x=random.randint(0,WIDTH)

y=0

xf=170

fox.pos=(xf,150)
coin.pos=(x, 0 )

def draw():
  screen.fill((144,238,144))
  fox.draw()
  coin.draw()
  screen.draw.text("Score: "+str(score),(20,20),fontsize=30)

def relocate():
  global x
  global y
  y+=1
  coin.pos=(x, y )

def move():
    if keyboard.left :
        fox.x-=1
    if keyboard.right:
        fox.x+=1

def collide():
  global score
  global x
  global y

  if fox.rect.center==coin.rect.center:
    score+=1
    coin.pos=(x, 0 )

def update():
  global x
  global y
  relocate()
  if y>WIDTH-10:
    x=random.randint(0,WIDTH)
    y=0
    coin.pos=(x, y )
  move()
  collide()

pgzrun.go()
</code>```

答:
To tell if two sprites collide, use the colliderect() method.
Change the line:

  if fox.rect.center==coin.rect.center:
```
<p>to</p>
<pre class="lang-py prettyprint-override"><code>  if fox.colliderect(coin):
</code>```

Actors have all the same attributes and methods as Rect, including methods like .colliderect() which can be used to test whether two actors have collided. – Pygame Zero Builtins

Body:
I recently started coding in Pygame Zero before starting Pygame. I was making a game and the I need to see if two of the sprites are colliding. How should I approach this?

The two sprites:
[1]: https://i.stack.imgur.com/bRcqC.png
[2]: https://i.stack.imgur.com/FwlES.png

import pgzrun
import rando[enter image description here][1]m

WIDTH=400
HEIGHT=400
score=0

game_over=False

coin=Actor("coin")
fox=Actor("fox")

x=random.randint(0,WIDTH)

y=0

xf=170

fox.pos=(xf,150)
coin.pos=(x, 0 )

def draw():
  screen.fill((144,238,144))
  fox.draw()
  coin.draw()
  screen.draw.text("Score: "+str(score),(20,20),fontsize=30)

def relocate():
  global x
  global y
  y+=1
  coin.pos=(x, y )

def move():
    if keyboard.left :
        fox.x-=1
    if keyboard.right:
        fox.x+=1

def collide():
  global score
  global x
  global y

  if fox.rect.center==coin.rect.center:
    score+=1
    coin.pos=(x, 0 )

def update():
  global x
  global y
  relocate()
  if y>WIDTH-10:
    x=random.randint(0,WIDTH)
    y=0
    coin.pos=(x, y )
  move()
  collide()

pgzrun.go()

Body:
To tell if two sprites collide, use the colliderect() method.
Change the line:

  if fox.rect.center==coin.rect.center:

to

  if fox.colliderect(coin):

Actors have all the same attributes and methods as Rect, including methods like .colliderect() which can be used to test whether two actors have collided. – Pygame Zero Builtins


问:
Grafana - How to import/copy just ONE graph of a big Dashboard A to a Dashboard B?
a small question regarding dashboards and graphs in Grafana please.

How to import/copy just ONE graph of a big Dashboard A to a Dashboard B?

By that, I mean I do not want to import the entire dashboard, I do not want to clone the entire dashboard.

Just want to select one particular interesting graph from a dashboard A, to copy to my own dashboard.

So far, I only tried cloning the entire dashboard, then removing one by one those I do not need (which is all of them except the one I need, and I believe this is not the right way to do it)

Is there a smarter way, which allow to copy/import only one graph of a dashboard please?

Thank you

答:
I found even a simpler way. Go to dashboard-1 (source dashboard from where you want to copy). In panel dropdown, there is a copy option under More. click it:

Now go to dashboard-2 (destination where you want to copy this panel). Click on Add panel, there is an option to paste copied panel:


问:
How to globally handle errors thrown from WebFilter in Spring WebFlux?
How to intercept and handle errors globally in WebFlux when they are being thrown from WebFilter chain?

It is clear how to handle errors thrown from controllers: @ControllerAdvice and @ExceptionHandler help great.

This approach does not work when an exception is thrown from WebFilter components.

In the following configuration GET /first and GET /second responses intentionally induce exceptions thrown. Although @ExceptionHandler methods handleFirst, handleSecond are similar, the handleSecond is never called. I suppose that is because MyWebFilter does not let a ServerWebExchange go to the stage where GlobalErrorHandlers methods could be applied.

Response for GET /first:

```<code> HTTP 500 "hello first"                   // expected
 HTTP 500 "hello first"                   // actual
</code>```

Response for GET /second:

```<code> HTTP 404 "hello second"                                                         // expected
 HTTP 500 {"path": "/second", "status": 500, "error": "Internal Server Error" }  // actual
</code>```

```<code>@RestController
class MyController {

    @GetMapping("/first")
    String first(){
        throw new FirstException("hello first");
    }
}

@Component
class MyWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange swe, WebFilterChain wfc) {
        var path = swe.getRequest().getURI().getPath();
        if (path.contains("second")){
            throw new SecondException("hello second")
        }
    }
}

@ControllerAdvice
class GlobalErrorHandlers {

    @ExceptionHandler(FirstException::class)
    ResponseEntity<String> handleFirst(FirstException ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.message)
    }

    @ExceptionHandler(SecondException::class)
    ResponseEntity<String> handleSecond(SecondException ex) {
       return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.message)
    }
}
</code>```

答:
Three steps are required to get full control over all exceptions thrown from application endpoints handling code:

Implement org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler

Annotate with @ControllerAdvice (or just @Component)

Set @Priority less than 1 to let the custom handler run before the default one (WebFluxResponseStatusExceptionHandler)

The tricky part is where we get an instance implementing
ServerResponse.Context for passing to
ServerResponse.writeTo(exchange, context). I did not find the final
answer, and comments are welcome. In the internal Spring code they always create a new instance of context for each writeTo invocation,
although in all cases (I've manged to find) the context instance is immutable.
That is why I ended up using the same ResponseContextInstance for all responses.
At the moment no problems detected with this approach.

```<code>@ControllerAdvice
@Priority(0) /* should go before WebFluxResponseStatusExceptionHandler */
class CustomWebExceptionHandler : ErrorWebExceptionHandler {

    private val log = logger(CustomWebExceptionHandler::class)

    override fun handle(exchange: ServerWebExchange, ex: Throwable): Mono<Void> {
        log.error("handled ${ex.javaClass.simpleName}", ex)

        val sr = when (ex) {
            is FirstException -> handleFirst(ex)
            is SecondException -> handleSecond(ex)
            else -> defaultException(ex)
        }

        return sr.flatMap { it.writeTo(exchange, ResponseContextInstance) }.then()
    }

    private fun handleFirst(ex: FirstException): Mono<ServerResponse> {
        return ServerResponse
                   .status(HttpStatus.INTERNAL_SERVER_ERROR)
                   .bodyValue("first")
    }

    private fun handleSecond(ex: SecondException): Mono<ServerResponse> {
        return ServerResponse.status(HttpStatus.BAD_REQUEST).bodyValue("second")
    }

    private object ResponseContextInstance : ServerResponse.Context {

        val strategies: HandlerStrategies = HandlerStrategies.withDefaults()

        override fun messageWriters(): List<HttpMessageWriter<*>> {
            return strategies.messageWriters()
        }

        override fun viewResolvers(): List<ViewResolver> {
            return strategies.viewResolvers()
        }
    }
}
</code>```

Body:
How to intercept and handle errors globally in WebFlux when they are being thrown from WebFilter chain?

It is clear how to handle errors thrown from controllers: @ControllerAdvice and @ExceptionHandler help great.

This approach does not work when an exception is thrown from WebFilter components.

In the following configuration GET /first and GET /second responses intentionally induce exceptions thrown. Although @ExceptionHandler methods handleFirst, handleSecond are similar, the handleSecond is never called. I suppose that is because MyWebFilter does not let a ServerWebExchange go to the stage where GlobalErrorHandlers methods could be applied.

Response for GET /first:

 HTTP 500 "hello first"                   // expected
 HTTP 500 "hello first"                   // actual

Response for GET /second:

 HTTP 404 "hello second"                                                         // expected
 HTTP 500 {"path": "/second", "status": 500, "error": "Internal Server Error" }  // actual

@RestController
class MyController {

    @GetMapping("/first")
    String first(){
        throw new FirstException("hello first");
    }
}

@Component
class MyWebFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange swe, WebFilterChain wfc) {
        var path = swe.getRequest().getURI().getPath();
        if (path.contains("second")){
            throw new SecondException("hello second")
        }
    }
}

@ControllerAdvice
class GlobalErrorHandlers {

    @ExceptionHandler(FirstException::class)
    ResponseEntity<String> handleFirst(FirstException ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.message)
    }

    @ExceptionHandler(SecondException::class)
    ResponseEntity<String> handleSecond(SecondException ex) {
       return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.message)
    }
}

Body:
Three steps are required to get full control over all exceptions thrown from application endpoints handling code:

Implement org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler

Annotate with @ControllerAdvice (or just @Component)

Set @Priority less than 1 to let the custom handler run before the default one (WebFluxResponseStatusExceptionHandler)

The tricky part is where we get an instance implementing
ServerResponse.Context for passing to
ServerResponse.writeTo(exchange, context). I did not find the final
answer, and comments are welcome. In the internal Spring code they always create a new instance of context for each writeTo invocation,
although in all cases (I've manged to find) the context instance is immutable.
That is why I ended up using the same ResponseContextInstance for all responses.
At the moment no problems detected with this approach.

@ControllerAdvice
@Priority(0) /* should go before WebFluxResponseStatusExceptionHandler */
class CustomWebExceptionHandler : ErrorWebExceptionHandler {

    private val log = logger(CustomWebExceptionHandler::class)

    override fun handle(exchange: ServerWebExchange, ex: Throwable): Mono<Void> {
        log.error("handled ${ex.javaClass.simpleName}", ex)

        val sr = when (ex) {
            is FirstException -> handleFirst(ex)
            is SecondException -> handleSecond(ex)
            else -> defaultException(ex)
        }

        return sr.flatMap { it.writeTo(exchange, ResponseContextInstance) }.then()
    }

    private fun handleFirst(ex: FirstException): Mono<ServerResponse> {
        return ServerResponse
                   .status(HttpStatus.INTERNAL_SERVER_ERROR)
                   .bodyValue("first")
    }

    private fun handleSecond(ex: SecondException): Mono<ServerResponse> {
        return ServerResponse.status(HttpStatus.BAD_REQUEST).bodyValue("second")
    }

    private object ResponseContextInstance : ServerResponse.Context {

        val strategies: HandlerStrategies = HandlerStrategies.withDefaults()

        override fun messageWriters(): List<HttpMessageWriter<*>> {
            return strategies.messageWriters()
        }

        override fun viewResolvers(): List<ViewResolver> {
            return strategies.viewResolvers()
        }
    }
}


问:
can't play video with local file in android
i have avi file in local file directory
file:///storage/emulated/0/ionic_download/2022-02-07/18/18-59-32.avi
but the problem is that I want to play video with above file path.

data[i].toURL() is above file path

html

```<code> <video controls autoplay width="{{top_box_width}}" height="{{top_box_height}}">
        <source [src]="play_path" type="video/mp4">

      </video>
</code>```

.ts

```<code>let myURL = normalizeURL(data[i].toURL() ) + "#t=0.1";
          console.log("222"+myURL);
          this.play_path = this.sanitizer.bypassSecurityTrustResourceUrl(data[i].toURL());

          console.log('Cccccontent path cahnged ', this.play_path);
          this.dismiss_loading();
</code>```

both myURL and play_path is not playing video…
how can I play video?
thank you

chorme://inspect result is

what is really weird for me is that with fileopener.open
it works. so file path is not wrong or not found

```<code>   this.fileOpener.open("file:///storage/emulated/0/ionic_download/2022-02-07/18/18-59-32.avi", 'video/mp4')
    .then(() => console.log('File is opened'))
    .catch(e => {
      console.log('Error opening file', e);
      if(e.message == "File not found"){
        alert("파일이 없습니다.");
        this.localstorage_remove(file_name);
      }
    });
</code>```

答:
AFAIK you should not define savePath inside functions. Your html code cannot even find the variable savePath because its being defined and initialized much later after the whole HTML has been rendered.

Define your savePath variable as global then initialize it inside your function using this.savePath. Your code should work.

Body:
i have avi file in local file directory
file:///storage/emulated/0/ionic_download/2022-02-07/18/18-59-32.avi
but the problem is that I want to play video with above file path.

data[i].toURL() is above file path

html

 <video controls autoplay width="{{top_box_width}}" height="{{top_box_height}}">
        <source [src]="play_path" type="video/mp4">

      </video>

.ts

let myURL = normalizeURL(data[i].toURL() ) + "#t=0.1";
          console.log("222"+myURL);
          this.play_path = this.sanitizer.bypassSecurityTrustResourceUrl(data[i].toURL());

          console.log('Cccccontent path cahnged ', this.play_path);
          this.dismiss_loading();

both myURL and play_path is not playing video…
how can I play video?
thank you

chorme://inspect result is

what is really weird for me is that with fileopener.open
it works. so file path is not wrong or not found

   this.fileOpener.open("file:///storage/emulated/0/ionic_download/2022-02-07/18/18-59-32.avi", 'video/mp4')
    .then(() => console.log('File is opened'))
    .catch(e => {
      console.log('Error opening file', e);
      if(e.message == "File not found"){
        alert("파일이 없습니다.");
        this.localstorage_remove(file_name);
      }
    });


问:
R, data.table: How to prevent fread from inferring NAs for one column?
I have a csv that has a column with string values. One of these values is a the literal string NA, which I want to treat as a string. Other columns have actual NAs that I would like to treat as NAs. Is there a way for me to specify that fread should not automatically parse NAs for one column? I have tried using the colClasses argument, but this doesn't seem to work. (I suspect it runs the conversion after the automatic parsing of NAs happens, while I'm looking for something that works like pandas converters argument that seems to perform the casting while reading.)

MWE:

test.csv:

```<code>strings,other.values
NA,blah
blah,NA
</code>```

I want to read the NA in strings as the character sequence NA, but the NA in other.values as the value NA.

> library(data.table)
> df <- fread('test.csv', header=TRUE) # adding colClasses=c('strings'='character') doesn't help
> df
    strings other.values
1:    <NA>         blah
2:    blah         <NA>
> which(is.na(df), arr.ind=TRUE)
     row col
[1,]   1   1
[2,]   2   2
```
<p>desired output:</p>
<pre class="lang-r prettyprint-override"><code>> df
   strings other.values
1:      NA         blah
2:    blah         <NA>
> which(is.na(df), arr.ind=TRUE)
     row col
[2,]   2   2
</code>```

In case it's relevant, here's a comparison with Python's pandas, which does what I want in this case with its converters argument (though of course I want to do other stuff in R).

>>> import pandas as pd
>>> df = pd.read_csv('test.csv')
>>> df
  strings other.values
0     NaN         blah
1    blah          NaN
>>> df.isnull()
   strings  other.values
0     True         False
1    False          True
>>> df = pd.read_csv('test.csv', converters={'strings':str})
>>> df
  strings other.values
0      NA         blah
1    blah          NaN
>>> df.isnull()
   strings  other.values
0    False         False
1    False          True
```
<p>Edit: of course, it's possible in this simple case to just do something like this:</p>
<pre class="lang-r prettyprint-override"><code>> library(dplyr)
> df <- df |> mutate(strings = case_when(is.na(strings) ~ 'NA', TRUE ~ strings))
</code>```

But this seems like a hack and not generalizable in the way I'm hoping for (for instance, if there are blank spaces in the strings column that would get parsed as NAs, this would collapse the difference).

答:
One potential option is to add quotation marks to values in the "strings" column with a preprocessing step, i.e.

Contents of "test.csv":

```<code>strings,other.values
NA,blah
blah,NA
</code>```

library(data.table)

df <- fread(cmd = "sed 's/^/\"/;s/,/\",/' ~/Desktop/test.csv", header = TRUE)
df
#>    strings other.values
#> 1:      NA         blah
#> 2:    blah         <NA>
```
<p>If the "strings" column is at another position you can tweak the sed command to suit, e.g.
Contents of "test2.csv":</p>
```xx,yy,strings,other.values
1,string,NA,blah
2,test,blah,NA
```
<pre class="lang-r prettyprint-override"><code>df2 <- fread(cmd = "sed 's/,/,\"/2;s/,/\",/3' ~/Desktop/test2.csv", header = TRUE)
df2
#>    xx     yy strings other.values
#> 1:  1 string      NA         blah
#> 2:  2   test    blah         <NA>
</code>```

Body:
I have a csv that has a column with string values. One of these values is a the literal string NA, which I want to treat as a string. Other columns have actual NAs that I would like to treat as NAs. Is there a way for me to specify that fread should not automatically parse NAs for one column? I have tried using the colClasses argument, but this doesn't seem to work. (I suspect it runs the conversion after the automatic parsing of NAs happens, while I'm looking for something that works like pandas converters argument that seems to perform the casting while reading.)

MWE:

test.csv:

strings,other.values
NA,blah
blah,NA

I want to read the NA in strings as the character sequence NA, but the NA in other.values as the value NA.

> library(data.table)
> df <- fread('test.csv', header=TRUE) # adding colClasses=c('strings'='character') doesn't help
> df
    strings other.values
1:    <NA>         blah
2:    blah         <NA>
> which(is.na(df), arr.ind=TRUE)
     row col
[1,]   1   1
[2,]   2   2

desired output:

> df
   strings other.values
1:      NA         blah
2:    blah         <NA>
> which(is.na(df), arr.ind=TRUE)
     row col
[2,]   2   2

In case it's relevant, here's a comparison with Python's pandas, which does what I want in this case with its converters argument (though of course I want to do other stuff in R).

>>> import pandas as pd
>>> df = pd.read_csv('test.csv')
>>> df
  strings other.values
0     NaN         blah
1    blah          NaN
>>> df.isnull()
   strings  other.values
0     True         False
1    False          True
>>> df = pd.read_csv('test.csv', converters={'strings':str})
>>> df
  strings other.values
0      NA         blah
1    blah          NaN
>>> df.isnull()
   strings  other.values
0    False         False
1    False          True

Edit: of course, it's possible in this simple case to just do something like this:

> library(dplyr)
> df <- df |> mutate(strings = case_when(is.na(strings) ~ 'NA', TRUE ~ strings))

But this seems like a hack and not generalizable in the way I'm hoping for (for instance, if there are blank spaces in the strings column that would get parsed as NAs, this would collapse the difference).

Body:
One potential option is to add quotation marks to values in the "strings" column with a preprocessing step, i.e.

Contents of "test.csv":

strings,other.values
NA,blah
blah,NA

library(data.table)

df <- fread(cmd = "sed 's/^/\"/;s/,/\",/' ~/Desktop/test.csv", header = TRUE)
df
#>    strings other.values
#> 1:      NA         blah
#> 2:    blah         <NA>

If the "strings" column is at another position you can tweak the sed command to suit, e.g.
Contents of "test2.csv":

xx,yy,strings,other.values
1,string,NA,blah
2,test,blah,NA

df2 <- fread(cmd = "sed 's/,/,\"/2;s/,/\",/3' ~/Desktop/test2.csv", header = TRUE)
df2
#>    xx     yy strings other.values
#> 1:  1 string      NA         blah
#> 2:  2   test    blah         <NA>


问:
Decompressing Linux zImage
I'm trying to decompress a zImage. I have a firmware binary I dumped from a flash chip. Analyzing it with binwalk gives the following:

```<code>$ binwalk flash_dump.bin

DECIMAL       HEXADECIMAL     DESCRIPTION
--------------------------------------------------------------------------------
352832        0x56240         Linux kernel ARM boot executable zImage (big-endian)
10617408      0xA20240        Linux kernel ARM boot executable zImage (big-endian)
10630468      0xA23544        device tree image (dtb)
</code>```

I tried to separate the first Linux zImage:

```<code>$ dd if=flash_dump.bin of=zImage bs=1 skip=352832 count=10264576

10264576+0 records in
10264576+0 records out
10264576 bytes (10 MB, 9.8 MiB) copied, 13.7267 s, 748 kB/s
</code>```

Making sure it's still a zImage:

```<code>$ file zImage

zImage: Linux kernel ARM boot executable zImage (big-endian)
</code>```

Searching for the gZip header:

```<code>$ arm-none-eabi-objdump -EB -b binary -D -m armv5t zImage | grep 8b1f

15e4c:  b81c8b1f    ldmdalt ip, {r0, r1, r2, r3, r4, r8, r9, fp, pc}
401f8:  0b3d2bfe    bleq    0xf8b1f8
</code>```

I can't seem to find the gZip header.

How can I decompress the zImage? I would like to look at it through a disassembler like IDA Pro.

答:
(cant comment)

@Gao Yuan is not correct in this specific case, as its a header byte tag (otherwise known as a MAGIC) made up of 2 individual (8bit) bytes that is being looked for (as opposed to a 16bit value), the 1st is 1f the 2nd is 8b, and usually followed by 08 (the compression method).

IE. because it is a MAGIC it is not byte-swapped when written / created. It has to be recognisable across any endian platform, otherwise it defeats the purpose of being a MAGIC

I just tested this on a RPi:

xxd /boot/kernel.img  | grep '1f8b 08' (offset 0x4730 - kernel zImage)

xxd /boot/kernel8.img | grep '1f8b 08' (offset 0 - standard .gz)

And a Linux-m68k kernel for the Tadpole VME SBC:

xxd vmlinux.gz        | grep '1f8b 08' (offset 0 - standard .gz)

OP: the next byte you found after 1f8b was 0b which I would say is the compression method byte (just not a standard one). But something is fishy, as 15K HEX into a zImage is a bit excessive (the RPi zImage kernels are about 4-5K HEX) , but if thats the only value, then that is indead the Gzip header.

Title: Decompressing Linux zImage

Body:
I'm trying to decompress a zImage. I have a firmware binary I dumped from a flash chip. Analyzing it with binwalk gives the following:

$ binwalk flash_dump.bin

DECIMAL       HEXADECIMAL     DESCRIPTION
--------------------------------------------------------------------------------
352832        0x56240         Linux kernel ARM boot executable zImage (big-endian)
10617408      0xA20240        Linux kernel ARM boot executable zImage (big-endian)
10630468      0xA23544        device tree image (dtb)

I tried to separate the first Linux zImage:

$ dd if=flash_dump.bin of=zImage bs=1 skip=352832 count=10264576

10264576+0 records in
10264576+0 records out
10264576 bytes (10 MB, 9.8 MiB) copied, 13.7267 s, 748 kB/s

Making sure it's still a zImage:

$ file zImage

zImage: Linux kernel ARM boot executable zImage (big-endian)

Searching for the gZip header:

$ arm-none-eabi-objdump -EB -b binary -D -m armv5t zImage | grep 8b1f

15e4c:  b81c8b1f    ldmdalt ip, {r0, r1, r2, r3, r4, r8, r9, fp, pc}
401f8:  0b3d2bfe    bleq    0xf8b1f8

I can't seem to find the gZip header.

How can I decompress the zImage? I would like to look at it through a disassembler like IDA Pro.


问:
Is it possible to obtain the classes or methods of other class with out adding a reference of that class
In my project i am having 2 class libraries namely DAL and BAL . While adding reference only one reference is added and for the other i am getting some Circular Dependancy error. So is there any possibility to obtain the members of other class with out adding reference of that class.

答:
A circular dependency usually means there is a design flaw in your system. If there is some common functionality that both libraries need then perhaps extract that into a third assembly and reference that from both. </p>

<p>Alternatively, you could have a third project that references the other two and is responsible for handling communication between them, a mediator. </p>

Body:
A circular dependency usually means there is a design flaw in your system. If there is some common functionality that both libraries need then perhaps extract that into a third assembly and reference that from both.

Alternatively, you could have a third project that references the other two and is responsible for handling communication between them, a mediator.