问:
Firebase deleting value it shouldn't
I am programming an Android app using firebase. I have a section where a user sends a pickup request and that request shows up in the driver's request fragment.

To handle accept/deny I have set it up so when you click accept it creates another firebase child with accepted requests that I will then show as a new request item that has already been handled.

The problem is that when I create a new request and accept it if the user tries to send another one it gets created as an accepted request directly in firebase  and will not show as a new one. Not sure why this is happening since an accepted request are set to be created only in the original request's accept button clicklistener.

Debugging I get this on the console:

E/ImeBackDispatcher: Ime callback not found. Ignoring unregisterReceivedCallback. callbackId:

not sure if it has anything to do but I can't figure out why the issue happens.

Here I create the original Request

```<code>private void createrequest(){
    DatabaseReference userefdata = FirebaseDatabase.getInstance().getReference().child("Requests");

    userefdata.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot snap : snapshot.getChildren()) {

                String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();

                String drivid = snap.child("driverid").getValue(String.class);
                Boolean acted = snap.child("actedon").getValue(Boolean.class);

                if (Objects.equals(drivid, userID)){

                    Requestitem evt = new Requestitem(snap.child("_name").getValue(String.class),
                        snap.child("_major").getValue(String.class),
                        snap.child("time").getValue(String.class),
                        snap.child("riderid").getValue(String.class),
                        snap.child("driverid").getValue(String.class),
                        false
                    );
                    if(acted == true)
                    {
                        requestitemsaccted.add(evt);
                    }
                    else {
                        requestitems.add(evt);
                    }
                }
            }
            adapter.notifyDataSetChanged();
            adapter2.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}
</code>```

//Here, from the adapter I create the accepted request and delete the original one

```<code>public viewH(@NonNull View itemView) {
    super(itemView);

    ace = itemView.findViewById(R.id.bacc);

    String rideridd =  list2.get(pos).getRiderid();

    ace.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirebaseDatabase.getInstance().getReference("Requests").child(rideridd).addValueEventListener(new ValueEventListener() {

                @Override

                public void onDataChange(@NonNull DataSnapshot snapshot) {
                   snapshot.getRef().removeValue();
                    String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();

                    RequestAccepted acepted = new RequestAccepted(name.getText().toString(), major.getText().toString(), date.getText().toString(), rideridd, userID, true);
                    _database.getReferenceFromUrl("https://full-ride-59aee-default-rtdb.firebaseio.com/").child("RequestsAccepted").child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser())
                            .getUid()).setValue(acepted);
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                }

            });
            // create new item request acted on in firebase with this data then make it show in ride history

        }
    });
</code>```

Title: Firebase deleting value it shouldn't

Body:
I am programming an Android app using firebase. I have a section where a user sends a pickup request and that request shows up in the driver's request fragment.

To handle accept/deny I have set it up so when you click accept it creates another firebase child with accepted requests that I will then show as a new request item that has already been handled.

The problem is that when I create a new request and accept it if the user tries to send another one it gets created as an accepted request directly in firebase  and will not show as a new one. Not sure why this is happening since an accepted request are set to be created only in the original request's accept button clicklistener.

Debugging I get this on the console:

E/ImeBackDispatcher: Ime callback not found. Ignoring unregisterReceivedCallback. callbackId:

not sure if it has anything to do but I can't figure out why the issue happens.

Here I create the original Request

private void createrequest(){
    DatabaseReference userefdata = FirebaseDatabase.getInstance().getReference().child("Requests");

    userefdata.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            for (DataSnapshot snap : snapshot.getChildren()) {

                String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();

                String drivid = snap.child("driverid").getValue(String.class);
                Boolean acted = snap.child("actedon").getValue(Boolean.class);

                if (Objects.equals(drivid, userID)){

                    Requestitem evt = new Requestitem(snap.child("_name").getValue(String.class),
                        snap.child("_major").getValue(String.class),
                        snap.child("time").getValue(String.class),
                        snap.child("riderid").getValue(String.class),
                        snap.child("driverid").getValue(String.class),
                        false
                    );
                    if(acted == true)
                    {
                        requestitemsaccted.add(evt);
                    }
                    else {
                        requestitems.add(evt);
                    }
                }
            }
            adapter.notifyDataSetChanged();
            adapter2.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

//Here, from the adapter I create the accepted request and delete the original one

public viewH(@NonNull View itemView) {
    super(itemView);

    ace = itemView.findViewById(R.id.bacc);

    String rideridd =  list2.get(pos).getRiderid();

    ace.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirebaseDatabase.getInstance().getReference("Requests").child(rideridd).addValueEventListener(new ValueEventListener() {

                @Override

                public void onDataChange(@NonNull DataSnapshot snapshot) {
                   snapshot.getRef().removeValue();
                    String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();

                    RequestAccepted acepted = new RequestAccepted(name.getText().toString(), major.getText().toString(), date.getText().toString(), rideridd, userID, true);
                    _database.getReferenceFromUrl("https://full-ride-59aee-default-rtdb.firebaseio.com/").child("RequestsAccepted").child(Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser())
                            .getUid()).setValue(acepted);
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                }

            });
            // create new item request acted on in firebase with this data then make it show in ride history

        }
    });


来源: stackexchange

问:
Kotlin: Spring ExceptionHandler Not Working When Validating RequestBody
It seems I cannot get my @ControllerAdvice to work with Kotlin POJOs. Note, it works when I throw an exception and with path params but doesn't work when validating the body of a request.

ControllerAdvice

```<code>@ControllerAdvice
class ExceptionAdvice : ResponseEntityExceptionHandler() {
    companion object {
        private val log = LoggerFactory.getLogger(this::class.java.name)
    }

    @ResponseBody
    @ExceptionHandler(CustomException::class)
    fun onException(exception: CustomException): ResponseEntity<CustomError> {
        log.error(Generic.EXCEPTION_PROVIDER_LOG, exception.message, exception.errorType, exception.errorType.httpStatus)

        return ResponseEntity(
            CustomError(exception.errorType.error, exception.errorType.name), exception.errorType.httpStatus
        )
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException::class)
    fun onValidationFail(exception: ConstraintViolationException): CustomError {
        log.error("Request did not conform to spec. Constraints violated: {}", exception.toString())

        return CustomError(ErrorType.G001.error, ErrorType.G001.name)
    }
}
</code>```

Controller

```<code>@RestController
@RequestMapping(produces = ["application/json; charset=UTF-8"])
@Validated
class StoreDataController {
    companion object {
        private val log = LoggerFactory.getLogger(this::class.java.name)
    }

    @Autowired
    private lateinit var service: Service

    @PostMapping("/store-data")
    @Throws(CustomException::class)
    fun storeData(@Valid @RequestBody data: Data): ResponseEntity<String> {
        return ResponseEntity.ok(data.title)
    }
}
</code>```

Body

```<code>data class Data(
    @field:Pattern(regexp = "[\\w\\d ]+", message = "Title can only use letters, numbers and spaces") var title: String
)
</code>```

What Gets Returned

```<code>{
    "type": "about:blank",
    "title": "Bad Request",
    "status": 400,
    "detail": "Invalid request content.",
    "instance": "/api/v1/store-data"
}
</code>```

What should happen is the ControllerAdvice should intercept the error using the @ExceptionHandler(ConstraintViolationException::class) annotation. Do I need to do anything else here?

ContentLicense: CC BY-SA 4.0

Body:
It seems I cannot get my @ControllerAdvice to work with Kotlin POJOs. Note, it works when I throw an exception and with path params but doesn't work when validating the body of a request.

ControllerAdvice

@ControllerAdvice
class ExceptionAdvice : ResponseEntityExceptionHandler() {
    companion object {
        private val log = LoggerFactory.getLogger(this::class.java.name)
    }

    @ResponseBody
    @ExceptionHandler(CustomException::class)
    fun onException(exception: CustomException): ResponseEntity<CustomError> {
        log.error(Generic.EXCEPTION_PROVIDER_LOG, exception.message, exception.errorType, exception.errorType.httpStatus)

        return ResponseEntity(
            CustomError(exception.errorType.error, exception.errorType.name), exception.errorType.httpStatus
        )
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ConstraintViolationException::class)
    fun onValidationFail(exception: ConstraintViolationException): CustomError {
        log.error("Request did not conform to spec. Constraints violated: {}", exception.toString())

        return CustomError(ErrorType.G001.error, ErrorType.G001.name)
    }
}

Controller

@RestController
@RequestMapping(produces = ["application/json; charset=UTF-8"])
@Validated
class StoreDataController {
    companion object {
        private val log = LoggerFactory.getLogger(this::class.java.name)
    }

    @Autowired
    private lateinit var service: Service

    @PostMapping("/store-data")
    @Throws(CustomException::class)
    fun storeData(@Valid @RequestBody data: Data): ResponseEntity<String> {
        return ResponseEntity.ok(data.title)
    }
}

Body

data class Data(
    @field:Pattern(regexp = "[\\w\\d ]+", message = "Title can only use letters, numbers and spaces") var title: String
)

What Gets Returned

{
    "type": "about:blank",
    "title": "Bad Request",
    "status": 400,
    "detail": "Invalid request content.",
    "instance": "/api/v1/store-data"
}

What should happen is the ControllerAdvice should intercept the error using the @ExceptionHandler(ConstraintViolationException::class) annotation. Do I need to do anything else here?


问:
'Navbar' is defined but never used. eslint(no-unused-vars)
First time using react, I am trying to import components but they won't show up

import React from 'react';
import Navbar from './components/Navbar/Navbar';

function App() {
  return (

working?

  );
}

export default App;
```
<pre class="lang-js prettyprint-override"><code>import React from 'react'
import {BiSearch} from 'react-icons/bi'
import {BsPerson} from 'react-icons/bs'

function Navbar() {
  return (
    <div className='navbar'>
        <div className='logo'>
            <h2>BEACHES. </h2>
        </div>
        <ul className='nav-menu'>
            <li>Home</li>
            <li>Destinations</li>
            <li>Travel</li>
            <li>Book</li>
            <li>Views</li>
        </ul>
      <div className='nav-icons'>
        <BiSearch className='icon'/>
        <BsPerson className='icon'/>
      </div>
    </div>
  )
}

export default Navbar

</code>```

First, install the following module npm install --save-dev eslint-plugin-react.

Then, in your .eslintrc.json, under extends, include the following plugin:

'extends': [
    'plugin:react/recommended'
]
```

Body:
First time using react, I am trying to import components but they won't show up

import React from 'react';
import Navbar from './components/Navbar/Navbar';

function App() {
  return (

working?

  );
}

export default App;

import React from 'react'
import {BiSearch} from 'react-icons/bi'
import {BsPerson} from 'react-icons/bs'

function Navbar() {
  return (

BEACHES.

Home

Destinations

Travel

Book

Views

        <BiSearch className='icon'/>
        <BsPerson className='icon'/>

  )
}

export default Navbar

First, install the following module npm install --save-dev eslint-plugin-react.

Then, in your .eslintrc.json, under extends, include the following plugin:

'extends': [
    'plugin:react/recommended'
]


问:
Python: How to find a window of unique characters in a string
The objective of the part 2 for advent of code 2022 day 6:
You are given an input string. You need to return the amount of characters that need to be processed before the 'first start-of-message marker' is detected.

A start of message marker is the index of the last character in a unique subset of length 14 found in the input.

For example, if we are looking for a substring of length 3 and as input abababc we should get 6 because when c appears, we have abc which is the first substring of length 3.

I have completed part 2 for advent of code 2022 day 6, however I tried to make it more efficient by doing this:

```<code>def part2V2(inputLine):
    INPUT_LINE = inputLine.strip()
    chars = [False] * 26
    OFFSET = ord('a')
    LENGTH = len(INPUT_LINE)

    i = 0

    for j in range(LENGTH):
        index = ord(INPUT_LINE[j]) - OFFSET

        if chars[index] == False:
            chars[index] = True

            if j-i == 13: #13 since we are looking for 14 unique characters minus 1 for the index
                return j
        else:
            chars = [False] * 26
            chars[index] = True
            i = j

</code>```

As you can probably guess, this does not work, and I am not sure why.

Suppose we give the input:

```<code>'abababc'
</code>```

The answer that I expect for a window of size 3 would be 6 and that is exactly what I get, however for my real input the function returns None

Body:
The objective of the part 2 for advent of code 2022 day 6:
You are given an input string. You need to return the amount of characters that need to be processed before the 'first start-of-message marker' is detected.

A start of message marker is the index of the last character in a unique subset of length 14 found in the input.

For example, if we are looking for a substring of length 3 and as input abababc we should get 6 because when c appears, we have abc which is the first substring of length 3.

I have completed part 2 for advent of code 2022 day 6, however I tried to make it more efficient by doing this:

def part2V2(inputLine):
    INPUT_LINE = inputLine.strip()
    chars = [False] * 26
    OFFSET = ord('a')
    LENGTH = len(INPUT_LINE)

    i = 0

    for j in range(LENGTH):
        index = ord(INPUT_LINE[j]) - OFFSET

        if chars[index] == False:
            chars[index] = True

            if j-i == 13: #13 since we are looking for 14 unique characters minus 1 for the index
                return j
        else:
            chars = [False] * 26
            chars[index] = True
            i = j

As you can probably guess, this does not work, and I am not sure why.

Suppose we give the input:

'abababc'

The answer that I expect for a window of size 3 would be 6 and that is exactly what I get, however for my real input the function returns None


问:
Summing values in R using a for loop
I have a data frame with a list of countries and responses for variables. I want to sum how many responses are associated with each country using a for loop over my vector of different country_names so I don't have to do it manually.
For example this is for one country:

sum(government_trust$cntry == "Bulgaria")
#My vector of country names
country_names <- unique(government_trust$cntry)

country_names

[1] "Bulgaria"  "Croatia"   "Czechia"   "Estonia"   "Finland"   "France"    "Hungary"   "Lithuania" "Slovakia"
[10] "Slovenia"
```
<p>I want to apply my code above of sum(government_trust$cntry == "country name") to each country using a for loop</p>
<p>I've tried creating a for loop like this:</p>
<pre class="lang-r prettyprint-override"><code>countries_respondents <- vector("double", nrow(government_trust))
for (i in seq_along(government_trust$cntry)) {
 countries_respondents[i] <- sum(government_trust$cntry == unique(government_trust$cntry))
}
</code>```

but this doesn't seem to be working.

Title: Summing values in R using a for loop

Body:
I have a data frame with a list of countries and responses for variables. I want to sum how many responses are associated with each country using a for loop over my vector of different country_names so I don't have to do it manually.
For example this is for one country:

sum(government_trust$cntry == "Bulgaria")
#My vector of country names
country_names <- unique(government_trust$cntry)

country_names

[1] "Bulgaria"  "Croatia"   "Czechia"   "Estonia"   "Finland"   "France"    "Hungary"   "Lithuania" "Slovakia"
[10] "Slovenia"

I want to apply my code above of sum(government_trust$cntry == "country name") to each country using a for loop

I've tried creating a for loop like this:

countries_respondents <- vector("double", nrow(government_trust))
for (i in seq_along(government_trust$cntry)) {
 countries_respondents[i] <- sum(government_trust$cntry == unique(government_trust$cntry))
}

but this doesn't seem to be working.


问:
How to provide custom config for ImageMagick AppImage
Currently I am downloading the ImageMagick AppImage provided on the releases page to /usr/local/bin. (It needs to be accessible to multiple users.) I would like to provide a custom policy.xml config file but am not sure where to put it.

The docs state:

Under Linux and Linux, ImageMagick searches for each of the configuration files listed above by looking in the locations given below, in order, and loads them if found:

```<code>$MAGICK_CONFIGURE_PATH
$PREFIX/etc/ImageMagick-7
$PREFIX/share/ImageMagick-7
$XDG_CACHE_HOME/ImageMagick
$HOME/.config/ImageMagick
<client path>/etc/ImageMagick
</code>```

The environmental variable $PREFIX is the default install path (e.g. /usr/local). The client path is the execution path of your ImageMagick client (e.g. /usr/local) .

I was hoping to avoid having to use $MAGICK_CONFIGURE_PATH but am currently.

I did try putting the the policy.xml file under /usr/local/etc/ImageMagick-7 and /usr/local/share/ImageMagick-7, but $ magick -list policy showed the config still goes undetected. Here is the output:

```<code>$ magick -list policy

Path: /tmp/.mount_magickrmRmxG/usr/etc/ImageMagick-7/policy.xml
  Policy: Undefined
    rights: None

Path: [built-in]
  Policy: Undefined
    rights: None
</code>```

Is there a directory where global config can be placed under the given setup that will be automatically detected?

Body:
Currently I am downloading the ImageMagick AppImage provided on the releases page to /usr/local/bin. (It needs to be accessible to multiple users.) I would like to provide a custom policy.xml config file but am not sure where to put it.

The docs state:

Under Linux and Linux, ImageMagick searches for each of the configuration files listed above by looking in the locations given below, in order, and loads them if found:

$MAGICK_CONFIGURE_PATH
$PREFIX/etc/ImageMagick-7
$PREFIX/share/ImageMagick-7
$XDG_CACHE_HOME/ImageMagick
$HOME/.config/ImageMagick
<client path>/etc/ImageMagick

The environmental variable $PREFIX is the default install path (e.g. /usr/local). The client path is the execution path of your ImageMagick client (e.g. /usr/local) .

I was hoping to avoid having to use $MAGICK_CONFIGURE_PATH but am currently.

I did try putting the the policy.xml file under /usr/local/etc/ImageMagick-7 and /usr/local/share/ImageMagick-7, but $ magick -list policy showed the config still goes undetected. Here is the output:

$ magick -list policy

Path: /tmp/.mount_magickrmRmxG/usr/etc/ImageMagick-7/policy.xml
  Policy: Undefined
    rights: None

Path: [built-in]
  Policy: Undefined
    rights: None

Is there a directory where global config can be placed under the given setup that will be automatically detected?


问:
How to calculate maximum profitable trade amount when cross DEX arbitrage?
For example Token A costs 1.00$ on Uniswap and 1.05$ on Sushiswap.
So I can buy Token A on Uniswap and sell on Sushiswap for profit.

Let's suppose the next conditions:

Uniswap reserve pool = 100 ETH / 100000 USDC. 1 ETH = 1000 USDC

Sushiswap reserve pool = 97 ETH / 105000 USDC. 1 ETH = 1082 USDC

How to calculate an optimal swap amount (accounting price impact) on Uniswap to sell for the maximum profit on Sushiswap?


问:
How to pass an array into a Google Chart?
I'm trying to make a pie chart from the google api using an array of arrays I'm making using data from a server. I've confirmed the loop to make the array works as it should by logging the results to the console separate from the drawChart() function, but when I include the code in the chart function nothing happens and no data is displayed and I get no errors.

I've put the code outside of the function in an on change listener and it runs and builds the array as it should. For some reason it seems to do nothing when I put it in the drawChart() function itself. Here is the chart function from google with my code to build the custom array in it:

```<code>//Imports and displays pie chart:
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        //Array to hold other arrays of browser name and visit count
        var pieData = [["Browser", "Visits"]];
        //Declares variables to hold count of each browser visit
        var unknownVisits = 0, chromeVisits = 0, firefoxVisits = 0,
        ieVisits = 0, edgeVisits = 0, safariVisits = 0, mcVisits = 0, msVisits = 0, operaVisits = 0;
        //Loop to find amount of visits for each browser
        for (let i = 0; i < visits.length; i++) {
            if (visits[i].browser === browsers[0].name) {
                unknownVisits += 1;
            } else if (visits[i].browser === browsers[1].name) {
                chromeVisits += 1;
            } else if (visits[i].browser === browsers[2].name) {
                firefoxVisits += 1;
            } else if (visits[i].browser === browsers[3].name) {
                ieVisits += 1;
            } else if (visits[i].browser === browsers[4].name) {
                edgeVisits += 1;
            } else if (visits[i].browser === browsers[5].name) {
                safariVisits += 1;
            } else if (visits[i].browser === browsers[6].name) {
                mcVisits += 1;
            } else if (visits[i].browser === browsers[7].name) {
                msVisits += 1;
            } else if (visits[i].browser === browsers[8].name) {
                operaVisits += 1;
            }
        }
        //Makes array of visit counts
        var browserVisitCount = [unknownVisits, chromeVisits, firefoxVisits, ieVisits, edgeVisits, safariVisits, mcVisits, msVisits, operaVisits];
        //Loop to add browser names and visit times to pieData array
        for (let i=0; i<browsers.length;i++) {
            pieData[i+1] = [browsers[i].name, browserVisitCount[i]];
            console.log(pieData[i]);
        }

        var data = google.visualization.arrayToDataTable(pieData);

        var options = {
            title: 'Browsers'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
    }
</code>```

Information from the visits array and browsers arrays are set earlier in the program. I just need to know how to get the statement var data = google.visualization.arrayToDataTable(pieData); to accept the array I made.

```<code>var data = google.visualization.arrayToDataTable(pieData);
</code>```

Body:
I'm trying to make a pie chart from the google api using an array of arrays I'm making using data from a server. I've confirmed the loop to make the array works as it should by logging the results to the console separate from the drawChart() function, but when I include the code in the chart function nothing happens and no data is displayed and I get no errors.

I've put the code outside of the function in an on change listener and it runs and builds the array as it should. For some reason it seems to do nothing when I put it in the drawChart() function itself. Here is the chart function from google with my code to build the custom array in it:

//Imports and displays pie chart:
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        //Array to hold other arrays of browser name and visit count
        var pieData = [["Browser", "Visits"]];
        //Declares variables to hold count of each browser visit
        var unknownVisits = 0, chromeVisits = 0, firefoxVisits = 0,
        ieVisits = 0, edgeVisits = 0, safariVisits = 0, mcVisits = 0, msVisits = 0, operaVisits = 0;
        //Loop to find amount of visits for each browser
        for (let i = 0; i < visits.length; i++) {
            if (visits[i].browser === browsers[0].name) {
                unknownVisits += 1;
            } else if (visits[i].browser === browsers[1].name) {
                chromeVisits += 1;
            } else if (visits[i].browser === browsers[2].name) {
                firefoxVisits += 1;
            } else if (visits[i].browser === browsers[3].name) {
                ieVisits += 1;
            } else if (visits[i].browser === browsers[4].name) {
                edgeVisits += 1;
            } else if (visits[i].browser === browsers[5].name) {
                safariVisits += 1;
            } else if (visits[i].browser === browsers[6].name) {
                mcVisits += 1;
            } else if (visits[i].browser === browsers[7].name) {
                msVisits += 1;
            } else if (visits[i].browser === browsers[8].name) {
                operaVisits += 1;
            }
        }
        //Makes array of visit counts
        var browserVisitCount = [unknownVisits, chromeVisits, firefoxVisits, ieVisits, edgeVisits, safariVisits, mcVisits, msVisits, operaVisits];
        //Loop to add browser names and visit times to pieData array
        for (let i=0; i<browsers.length;i++) {
            pieData[i+1] = [browsers[i].name, browserVisitCount[i]];
            console.log(pieData[i]);
        }

        var data = google.visualization.arrayToDataTable(pieData);

        var options = {
            title: 'Browsers'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(data, options);
    }

Information from the visits array and browsers arrays are set earlier in the program. I just need to know how to get the statement var data = google.visualization.arrayToDataTable(pieData); to accept the array I made.

var data = google.visualization.arrayToDataTable(pieData);


问:
URP camera stacking causes character meshes to break
First of all, please understand that I am using a translator.
I'm making a first person game and I've split it into two cameras. A camera that renders the main camera and the player's arms. FYI it's a URP and the camera sometimes doesn't render the hand mesh for the player's arm.

I have no idea what the heck is going on.


问:
Preserve previously uploaded file
I'm working on an ASP.Net Core MVC project and I created a dropzone to upload my files like below:

function readFile(input) {
  if (input.files && input.files[0]) {
    let arr = input.files // guardamos el array de archivos que estan sin leer en este punto
    for (let i = 0; i < input.files.length; i++) { // lo recorremos
      let reader = new FileReader(); // cada vez que queramos leer un archivo redefinimos el reader, si usamos la misma instancia nos saltara el error (Uncaught InvalidStateError: Failed to execute 'readAsDataURL' on 'FileReader': The object is already busy reading Blobs.)
      reader.readAsDataURL(arr[i]); // leemos el archivo en el indice indicado
      reader.addEventListener("load",() => { // al terminar de cargar el archivo
        var htmlPreview = `

` +
          '' +
          "
" +
          input.files[i].name +
          "

";
      var wrapperZone = $(input).parent();
      var previewZone = $(input)
        .parent()
        .parent()
        .find(".preview-zone");
      var boxZone = $(input)
        .parent()
        .parent()
        .find(".preview-zone")
        .find(".box")
        .find(".box-body");
      wrapperZone.removeClass("dragover");
      previewZone.removeClass("hidden");
      boxZone.append(htmlPreview);
      })
    }
  };
}

function reset(e) {
  e.wrap("<form>")
    .closest("form")
    .get(0)
    .reset();
  e.unwrap();
}

$(".dropzone").change(function() {
  readFile(this);
});

$(".dropzone-wrapper").on("dragover", function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).addClass("dragover");
});

$(".dropzone-wrapper").on("dragleave", function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).removeClass("dragover");
});

$(".remove-preview").on("click", function() {
  var boxZone = $(this)
    .parents(".preview-zone")
    .find(".box-body");
  var previewZone = $(this).parents(".preview-zone");
  var dropzone = $(this)
    .parents(".form-group")
    .find(".dropzone");
  boxZone.empty();
  previewZone.addClass("hidden");
  reset(dropzone);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  padding: 50px 100px;
}

.box {
  position: relative;
  background: #ffffff;
  width: 100%;
}

.box-header {
  color: #444;
  display: block;
  padding: 10px;
  position: relative;
  margin-bottom: 10px;
}

.box-tools {
  position: absolute;
  right: 10px;
  top: 5px;
}

.box-body{
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  margin-bottom: 15px;
}

.box-element{
  display: grid;
  height: 100px;
  width: 80px;
  grid-template-rows: 80% 20%;
  font-size: 10px;
}

.box-element img{
  height: 70px;
  width: 70px;
}

.dropzone-wrapper {
  border: 2px dashed #91b0b3;
  color: #92b0b3;
  position: relative;
  height: 150px;
}

.dropzone-desc {
  position: absolute;
  margin: 0 auto;
  left: 0;
  right: 0;
  text-align: center;
  width: 40%;
  top: 60px;
  font-size: 16px;
}

.dropzone,
.dropzone:focus {
  outline: none !important;
  width: 100%;
  cursor: pointer;
}

.input-file {
  position: absolute;
  width: 100%;
  height: 150px;
}

.dropzone-wrapper:hover,
.dropzone-wrapper.dragover {
  background: #ecf0f5;
}

.preview-zone {
  text-align: center;
}

.preview-zone .box {
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="normalize.css">
    <link rel="stylesheet" href="estilos.css">
    <title>Document</title>

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

10sec

Preview

                        <button type="button" class="btn btn-danger btn-xs remove-preview">
                                              Reset
                                           </button>

Choose an image file or drag it here.

                  <input type="file" class="dropzone input-file" multiple asp-for="@Model.Files10" />

```

The problem now is that I want to preserve the previously uploaded files, ie:
If you upload a file and then want to upload a new file, the previous one is deleted in the input (in the dropzone if the previous one remains),
I want the old file to stay and not be deleted, unless the reset button is clicked.

Is it possible to make the input save the old files when inserting a new one?

Title: Preserve previously uploaded file

Body:
I'm working on an ASP.Net Core MVC project and I created a dropzone to upload my files like below:

function readFile(input) {
  if (input.files && input.files[0]) {
    let arr = input.files // guardamos el array de archivos que estan sin leer en este punto
    for (let i = 0; i < input.files.length; i++) { // lo recorremos
      let reader = new FileReader(); // cada vez que queramos leer un archivo redefinimos el reader, si usamos la misma instancia nos saltara el error (Uncaught InvalidStateError: Failed to execute 'readAsDataURL' on 'FileReader': The object is already busy reading Blobs.)
      reader.readAsDataURL(arr[i]); // leemos el archivo en el indice indicado
      reader.addEventListener("load",() => { // al terminar de cargar el archivo
        var htmlPreview = `

` +
          '' +
          "
" +
          input.files[i].name +
          "

";
      var wrapperZone = $(input).parent();
      var previewZone = $(input)
        .parent()
        .parent()
        .find(".preview-zone");
      var boxZone = $(input)
        .parent()
        .parent()
        .find(".preview-zone")
        .find(".box")
        .find(".box-body");
      wrapperZone.removeClass("dragover");
      previewZone.removeClass("hidden");
      boxZone.append(htmlPreview);
      })
    }
  };
}

function reset(e) {
  e.wrap("<form>")
    .closest("form")
    .get(0)
    .reset();
  e.unwrap();
}

$(".dropzone").change(function() {
  readFile(this);
});

$(".dropzone-wrapper").on("dragover", function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).addClass("dragover");
});

$(".dropzone-wrapper").on("dragleave", function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).removeClass("dragover");
});

$(".remove-preview").on("click", function() {
  var boxZone = $(this)
    .parents(".preview-zone")
    .find(".box-body");
  var previewZone = $(this).parents(".preview-zone");
  var dropzone = $(this)
    .parents(".form-group")
    .find(".dropzone");
  boxZone.empty();
  previewZone.addClass("hidden");
  reset(dropzone);
});

.container {
  padding: 50px 100px;
}

.box {
  position: relative;
  background: #ffffff;
  width: 100%;
}

.box-header {
  color: #444;
  display: block;
  padding: 10px;
  position: relative;
  margin-bottom: 10px;
}

.box-tools {
  position: absolute;
  right: 10px;
  top: 5px;
}

.box-body{
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  margin-bottom: 15px;
}

.box-element{
  display: grid;
  height: 100px;
  width: 80px;
  grid-template-rows: 80% 20%;
  font-size: 10px;
}

.box-element img{
  height: 70px;
  width: 70px;
}

.dropzone-wrapper {
  border: 2px dashed #91b0b3;
  color: #92b0b3;
  position: relative;
  height: 150px;
}

.dropzone-desc {
  position: absolute;
  margin: 0 auto;
  left: 0;
  right: 0;
  text-align: center;
  width: 40%;
  top: 60px;
  font-size: 16px;
}

.dropzone,
.dropzone:focus {
  outline: none !important;
  width: 100%;
  cursor: pointer;
}

.input-file {
  position: absolute;
  width: 100%;
  height: 150px;
}

.dropzone-wrapper:hover,
.dropzone-wrapper.dragover {
  background: #ecf0f5;
}

.preview-zone {
  text-align: center;
}

.preview-zone .box {
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="normalize.css">
    <link rel="stylesheet" href="estilos.css">
    <title>Document</title>

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

10sec

Preview

                        <button type="button" class="btn btn-danger btn-xs remove-preview">
                                              Reset
                                           </button>

Choose an image file or drag it here.

                  <input type="file" class="dropzone input-file" multiple asp-for="@Model.Files10" />

The problem now is that I want to preserve the previously uploaded files, ie:
If you upload a file and then want to upload a new file, the previous one is deleted in the input (in the dropzone if the previous one remains),
I want the old file to stay and not be deleted, unless the reset button is clicked.

Is it possible to make the input save the old files when inserting a new one?


问:
Permissions and performance issues using Windows 11 + WSL2 (Ubuntu), Docker Desktop & WordPress via docker-compose local environment
I am working on a project handed over by a previous developer which utilises docker desktop and a docker-compose.yml file to bring up a WordPress project on my Windows PC. This worked okay on my last PC (Windows 10), I've now upgraded to a new PC running on Windows 11.

The project worked fine with a non WSL version of docker, just using hyper-v and docker-compose with some mounted volumes to create the containers and code up a bespoke WordPress theme (running on roots/sage 8).

Since moving to Windows 11, the project has been almost unusable due to massively slow pagespeed (30 seconds minimum to load just about anything).

I tried to solve this by switching to WSL2. I followed tutorials from Microsoft & Docker to get WSL2 setup with Ubuntu.

I did a totally clean install of:

WSL2

Ubuntu

Docker Desktop

VS Code

My understanding is that adding the project files directly into Ubuntu is the best way to go as it should be a lot faster than trying to mount the files from Windows, so I setup SSH keys and cloned the repo into my /home/andy/ directory.

Running docker-compose up successfully fires up the website but I then get hit with loads of issues I never encountered while running the project via docker desktop without WSL2.

WordPress or the web user seems to be lacking permissions to write to the wp-content directory
-- Can't install any plugins
-- Can't upload media

VS code (launched via code . in the project directory) doesn't have permission to write to anywhere in wp-content

FileZilla is unable to create any folders within wp-content including in wp-content/uploads

I need to get this project working, I'm obviously not a docker or linux expert, I just need to get it fired up so I can continue coding with WordPress!

I've trawled through most pages of Google's search results for people having similar issues and I've done a fresh install of the WSL2/Docker setup multiple times after trying different things to get this to work but nothing is working.

I've tried:

adding to the docker-entrypoint.sh chown -R www-data:www-data /var/www/html
-- This was to try and give the www-data user ownership of everything mounted into the var/www/html directory, which appeared initially to help but broke other permissions, like Filezilla being able to write to wp-content

Ensured that all the directories/files in my project folder had the correct permissions for WordPress 755 for directories & 644 for files
-- Had no effect on the issue

Attempted to set 777 recursively on the entire project directory in Ubuntu
-- Still had issues with FileZilla & VS Code, and for some reason, when I did docker-compose up the permissions on wp-content reset themselves from 777 to 755

Added user:$USER within the wordpress part of the docker-compose.yml file, and then did USER=root docker-compose up
-- This appeared to give WordPress the permissions/access needed in order to write to wp-content as I could now download and install plugins, and upload media, but the entire backend of WordPress was very slow and I still couldn't save files with VS code, or download with FileZilla.

Attempted to take ownership of the /home/andy directory where my project files live via sudo chown -R andy /home/andy/
-- This allowed VS Code & FileZilla to both work as expected, saving files and downloading files from a remote server into Ubuntu via WSL2

With weird root user hacky solution + chown on the user directory, I appeared to have got everything "working", but wp-admin was so ridiculously slow, it was barely usable.

Another post I came across said that using .local to access the site was a bad idea since that could cause slow performance with docker, so I then changed the website url in my hosts file, and did a find and replace on the DB/Files to reflect the change, and now the backend of WordPress works fast, but appears to have permissions issues as lots of plugins are complaining about not having the correct permissions and I'm unable to download / install or even deactivate existing plugins.

I'm basically at a total loss at this point as for how to get this working. If anyone has any suggestions I'd be very grateful.

Thanks!


问:
How do I make line 25 execute?
```<code>import logo from './logo.svg';
import './App.css';
import { useState } from 'react';
import axios from 'axios'

function App() {

  function test(){
    /* eslint-disable no-undef */
    chrome.tabs.query({active: true, currentWindow:true}, tabs=>{
      const activeTabId = tabs[0].id;

      chrome.scripting.executeScript(
        {
          target: {tabId: activeTabId},
          function: ()=>{

            var tab= document.getElementsByClassName("styles__BodyRow-sc-4myuz0-3 cnRgPY");
            var list=[];

            for(var i=0;i<tab.length;i++){
              if(tab[i].children[7].innerText!="$0.00"){
                tab[i].style['background-color']="red";

                  id = "success";

              }
            }

          }

        }
      )
    })
  }

      var id = "try again";

    const [OrderID, setOrderNumber] = useState(id);
    const [Date, setDate] = useState("");
    const [DasherName, setDasher] = useState("");
    const [Cost, setCost] = useState("");

    const handleSubmit = (e) => {
      e.preventDefault();

      const object = { OrderID, Date, DasherName, Cost };

      axios
        .post(
          "https://sheet.best/api/sheets/****************************",
          object
        )
        .then((response) => {
          console.log(response);
        });
    };

  return (
    <div className="App">
      <button onClick={test}>Search</button>
      <button onClick={handleSubmit}>Paste</button>

    </div>
  );
}

export default App;
</code>```

Whenever I run the program, I get "try again" instead of "sucess". I think I should make the variable id global but idk how to. I been trying for so long, but I can't seem to make the variable id global so that when I run handleSubmit, it outputs success. Everything else works (this is a web scrapper for my computer science project). I am wondering if I can do something so that the handleSubmit button can reach the id within the test function. Can anyone help?

Title: How do I make line 25 execute?

Body:
import logo from './logo.svg';
import './App.css';
import { useState } from 'react';
import axios from 'axios'

function App() {

  function test(){
    /* eslint-disable no-undef */
    chrome.tabs.query({active: true, currentWindow:true}, tabs=>{
      const activeTabId = tabs[0].id;

      chrome.scripting.executeScript(
        {
          target: {tabId: activeTabId},
          function: ()=>{

            var tab= document.getElementsByClassName("styles__BodyRow-sc-4myuz0-3 cnRgPY");
            var list=[];

            for(var i=0;i<tab.length;i++){
              if(tab[i].children[7].innerText!="$0.00"){
                tab[i].style['background-color']="red";

                  id = "success";

              }
            }

          }

        }
      )
    })
  }

      var id = "try again";

    const [OrderID, setOrderNumber] = useState(id);
    const [Date, setDate] = useState("");
    const [DasherName, setDasher] = useState("");
    const [Cost, setCost] = useState("");

    const handleSubmit = (e) => {
      e.preventDefault();

      const object = { OrderID, Date, DasherName, Cost };

      axios
        .post(
          "https://sheet.best/api/sheets/****************************",
          object
        )
        .then((response) => {
          console.log(response);
        });
    };

  return (

      <button onClick={test}>Search</button>
      <button onClick={handleSubmit}>Paste</button>

  );
}

export default App;

Whenever I run the program, I get "try again" instead of "sucess". I think I should make the variable id global but idk how to. I been trying for so long, but I can't seem to make the variable id global so that when I run handleSubmit, it outputs success. Everything else works (this is a web scrapper for my computer science project). I am wondering if I can do something so that the handleSubmit button can reach the id within the test function. Can anyone help?


问:
Raw string encoding from input()
I'm trying to scan a variable directory, said variable is defined by an input(), yet the program throws out this issue:
(unicode error) 'unicodeescape' codec can't decode bytes in position 320-321: truncated \UXXXXXXXX escape

Current code: Not Working

```<code>import os
import time

print("Enter directory name.\nDirectory name example:\nC:\Users\example\Documents")

dirname = input()

with os.scandir(dirname) as dir_entries:
    for entry in dir_entries:
        info = entry.stat()
        file_name = os.path.basename(entry)

        my_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(info.st_ctime))
        rawmb = (info.st_size/(1024*1024))
        truncated = round(rawmb, 3)

        print(file_name)
        print(my_time)
        print(truncated,"MB")
        print('===========================')
</code>```

I considered using \\ or / instead of \ during the input, but that makes copying the directory from the file explorer impossible.

I have no idea how to include an r in front of the input() string.

.decode,.encode didn't seem to work for me either, but I most likely just used them wrong.

Edit #1
Tried the solution from J_H

Do this after input(): for ch in dirname: print(ch, ord(ch))

Result:
Same error.

Title: Raw string encoding from input()

Body:
I'm trying to scan a variable directory, said variable is defined by an input(), yet the program throws out this issue:
(unicode error) 'unicodeescape' codec can't decode bytes in position 320-321: truncated \UXXXXXXXX escape

Current code: Not Working

import os
import time

print("Enter directory name.\nDirectory name example:\nC:\Users\example\Documents")

dirname = input()

with os.scandir(dirname) as dir_entries:
    for entry in dir_entries:
        info = entry.stat()
        file_name = os.path.basename(entry)

        my_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(info.st_ctime))
        rawmb = (info.st_size/(1024*1024))
        truncated = round(rawmb, 3)

        print(file_name)
        print(my_time)
        print(truncated,"MB")
        print('===========================')

I considered using \\ or / instead of \ during the input, but that makes copying the directory from the file explorer impossible.

I have no idea how to include an r in front of the input() string.

.decode,.encode didn't seem to work for me either, but I most likely just used them wrong.

Edit #1
Tried the solution from J_H

Do this after input(): for ch in dirname: print(ch, ord(ch))

Result:
Same error.


问:
Manipulating JSON in Angular
Objective: I am trying to build a website URL by concatenating a variety of variables.  I get some from JSON file (audience, country, language) + using constants (baseUrl, tailUrl) + some logic applied to an attribute from JSON file (subdir)

Struggle: I have a service that's getting objects from a JSON and then those objects are being used within the app.  My original struggle was to map an object from an array to something else (solved using map and switch/case and that worked fine for an array).  However, I am having trouble using the map function with these JSON objects.

So in the .html, I am able to loop through the JSON objects just fine, like so:
`

```<code><table class="table table-striped">
  <thead>
    <tr>
      <th>Audience</th>
      <th>Country</th>
      <th>Language</th>
      <th>URL</th>
    </tr>
  </thead>
  <tbody>
  <tr *ngFor="let i of siteUrl; let b =index">
    <td>{{i.audience}}</td>
    <td>{{i.country}}</td>
    <td>{{i.language}}</td>
    <td>{{(baseUrl)+(i.audience+"/")+(i.country+"/")+(i.language+"/")+(tailUrl)}}</td>
  </tr>
  </tbody>
</table>
</code>```

`

However, when I try to do map the objects from the service, I am unable to do so

`

```<code>    ngOnInit(){
        {
            this.baseUrl=baseUrlConst;
            this.tailUrl=urlTailConst;
            this.siteService=smap.map(item =>{
                switch (item.audience) {
                    case 'ABC':
                        item.audiencesubdir = 'DEF';
                        break;
                    case 'UVW':
                        item.audiencesubdir = 'XYZ';
                }
            })
        }
    }
</code>```

`

I tried arrays instead of JSON and that works fine, but the objects in the JSON itself don't like this function.  My understanding of Angular is novice.

Title: Manipulating JSON in Angular

Body:
Objective: I am trying to build a website URL by concatenating a variety of variables.  I get some from JSON file (audience, country, language) + using constants (baseUrl, tailUrl) + some logic applied to an attribute from JSON file (subdir)

Struggle: I have a service that's getting objects from a JSON and then those objects are being used within the app.  My original struggle was to map an object from an array to something else (solved using map and switch/case and that worked fine for an array).  However, I am having trouble using the map function with these JSON objects.

So in the .html, I am able to loop through the JSON objects just fine, like so:
`

      Audience
      Country
      Language
      URL

    {{i.audience}}
    {{i.country}}
    {{i.language}}
    {{(baseUrl)+(i.audience+"/")+(i.country+"/")+(i.language+"/")+(tailUrl)}}

`

However, when I try to do map the objects from the service, I am unable to do so

`

    ngOnInit(){
        {
            this.baseUrl=baseUrlConst;
            this.tailUrl=urlTailConst;
            this.siteService=smap.map(item =>{
                switch (item.audience) {
                    case 'ABC':
                        item.audiencesubdir = 'DEF';
                        break;
                    case 'UVW':
                        item.audiencesubdir = 'XYZ';
                }
            })
        }
    }

`

I tried arrays instead of JSON and that works fine, but the objects in the JSON itself don't like this function.  My understanding of Angular is novice.


问:
Can not make POST, getting error "Cannot deserialize value of type `java.time.LocalDateTime` from Object value"
I have built android app. The application gets date from a string field.
I parse that string to right format to get LocalDateTime.

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime date = LocalDateTime.parse(routeDate.getText().toString(), dateTimeFormatter);
```
<p>but when i make post request it fails. My backend is springboot app. I get from it error:</p>
<pre class="lang-java prettyprint-override"><code>WARN 29948 --- [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.time.LocalDateTime` from Object value (token `JsonToken.START_OBJECT`)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 9] (through reference chain: com.university.logisticsappbe.model.api.CreateCheckpointRequest["date"])]
</code>```

By logging out date to console I get 2022-02-02T10:00

Any ideas what problem it could be?

On angular web application post works.

Body:
I have built android app. The application gets date from a string field.
I parse that string to right format to get LocalDateTime.

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime date = LocalDateTime.parse(routeDate.getText().toString(), dateTimeFormatter);

but when i make post request it fails. My backend is springboot app. I get from it error:

WARN 29948 --- [nio-8080-exec-5] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.time.LocalDateTime` from Object value (token `JsonToken.START_OBJECT`)<EOL> at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 9] (through reference chain: com.university.logisticsappbe.model.api.CreateCheckpointRequest["date"])]

By logging out date to console I get 2022-02-02T10:00

Any ideas what problem it could be?

On angular web application post works.


问:
Room-based code is causing the following error: android.app.Application cannot be cast to com.example.mathreps.MathRepsApplication
I am working on adding data persistence to an app using the Room library, based on this documentation. My database only has one column where a String corresponding to a user-selected radio button is to be placed. However, as soon as I attempt to insert a new object (in this case, an Attempt), it gives me the following error:

```<code>java.lang.ClassCastException: android.app.Application cannot be cast to com.example.mathreps.MathRepsApplication.
</code>```

I believe this error comes from the following block of code within my Rating fragment:

```<code>private val dataViewModel: MathRepsViewModel by activityViewModels {
    MathRepsViewModel.MathRepsViewModelFactory(
        (activity?.application as MathRepsApplication).database
            .attemptDao()
    )
}
</code>```

Which relates to a different class called MathRepsApplication

```<code>class MathRepsApplication: Application() {
    val database: AttemptRoomDatabase by lazy {AttemptRoomDatabase.getDatabase(this)}
}
</code>```

Since this problem most likely relates to multiple classes and packages, here is the link to the repository for the project.

My attempts to fix this have been unsuccessful, with them mostly consisting of heavily reviewing the database implementation and not much else, as I don't exactly know where to start.

Body:
I am working on adding data persistence to an app using the Room library, based on this documentation. My database only has one column where a String corresponding to a user-selected radio button is to be placed. However, as soon as I attempt to insert a new object (in this case, an Attempt), it gives me the following error:

java.lang.ClassCastException: android.app.Application cannot be cast to com.example.mathreps.MathRepsApplication.

I believe this error comes from the following block of code within my Rating fragment:

private val dataViewModel: MathRepsViewModel by activityViewModels {
    MathRepsViewModel.MathRepsViewModelFactory(
        (activity?.application as MathRepsApplication).database
            .attemptDao()
    )
}

Which relates to a different class called MathRepsApplication

class MathRepsApplication: Application() {
    val database: AttemptRoomDatabase by lazy {AttemptRoomDatabase.getDatabase(this)}
}

Since this problem most likely relates to multiple classes and packages, here is the link to the repository for the project.

My attempts to fix this have been unsuccessful, with them mostly consisting of heavily reviewing the database implementation and not much else, as I don't exactly know where to start.


问:
Why sync in vscode is working properly after updated python?
I have updated my conda env (python version and every other packages that I have inside it).
After that, I can not sync my commits properly. It gives me to enter password of my git. Even though my account is logged in.
The interesting thing is that push and pull are working correctly, the only issue is sync buttom.

I have tried to push and pull and it is working properly, but sync buttom every time ask about my git password


问:
React aria merge props causing initial styling to be ignored Next.js TypeScript
When I use react aria's mergeProps to merge button props and then pass to my component it causes it to override (I'm guessing) the initial props, but not all. The background color won't appear but everything else does, and the styling works fine on hover or any secondary "conditional" props.
Code:

```<code>export default function Button(props: ButtonProps): ReactElement {
  const p = { ...DEFAULT_PROPS, ...props };

  const ref = useRef<HTMLButtonElement>(null);
  const { buttonProps, isPressed } = useButton(p, ref);
  const { hoverProps, isHovered } = useHover({ isDisabled: p.isDisabled });
  const behaviorProps = mergeProps(buttonProps, hoverProps);

  return (
    <button
      className={clsx([
        'button-main',
        {
          'is-hovered': isHovered,
          'is-pressed': isPressed,
          'is-secondary': p.variant === 'secondary',
        },
      ])}
      {...behaviorProps}
    >
      {p.children}
    </button>
  );
}
</code>```

Body:
When I use react aria's mergeProps to merge button props and then pass to my component it causes it to override (I'm guessing) the initial props, but not all. The background color won't appear but everything else does, and the styling works fine on hover or any secondary "conditional" props.
Code:

export default function Button(props: ButtonProps): ReactElement {
  const p = { ...DEFAULT_PROPS, ...props };

  const ref = useRef<HTMLButtonElement>(null);
  const { buttonProps, isPressed } = useButton(p, ref);
  const { hoverProps, isHovered } = useHover({ isDisabled: p.isDisabled });
  const behaviorProps = mergeProps(buttonProps, hoverProps);

  return (
    <button
      className={clsx([
        'button-main',
        {
          'is-hovered': isHovered,
          'is-pressed': isPressed,
          'is-secondary': p.variant === 'secondary',
        },
      ])}
      {...behaviorProps}
    >
      {p.children}
    </button>
  );
}


问:
Using LoopStream together with FadeInOutSampleProvider using NAudio
I'm already using Loopstream in my project, this solution: https://www.markheath.net/post/looped-playback-in-net-with-naudio

Now I want to use FadeInOutSampleProvider as well. I'm not sure how I can go about that? I can't chain it like I can FadeInOutSampleProvider -> VolumeSampleProvider for example so I'm stumped.

Example that does not work:

```<code>var audioFile = new AudioFileReader(soundFile);
var fadeInOut = new FadeInOutSampleProvider(audioFile);
var looping = new LoopStream(fadeInOut)
</code>```

Error:

Cannot convert from 'NAudio.Wave.SampleProviders.FadeInOutSampleProvider' to 'NAudio.Wave.WaveStream'

Body:
I'm already using Loopstream in my project, this solution: https://www.markheath.net/post/looped-playback-in-net-with-naudio

Now I want to use FadeInOutSampleProvider as well. I'm not sure how I can go about that? I can't chain it like I can FadeInOutSampleProvider -> VolumeSampleProvider for example so I'm stumped.

Example that does not work:

var audioFile = new AudioFileReader(soundFile);
var fadeInOut = new FadeInOutSampleProvider(audioFile);
var looping = new LoopStream(fadeInOut)

Error:

Cannot convert from 'NAudio.Wave.SampleProviders.FadeInOutSampleProvider' to 'NAudio.Wave.WaveStream'


问:
Variable Errors for smcure package
```<code>smcure(Surv(DURATION,DEFAULT)~ PURPOSE+RESIDENCE,cureform=~PURPOSE+RESIDENCE,
    data=CD,model="ph",nboot=500)
</code>```

Error in [[<-.data.frame(*tmp*, i, value = c(6L, 1L, 3L, 2L, 9L, 6L,  :
replacement has 1810 rows, data has 905

```<code>smcure(Surv(DURATION,DEFAULT)~.,cureform=~.,
    data=CD,model="ph",nboot=500)
</code>```

Error in data[, cvars]:
! Can't subset columns that don't exist.
✖ Column . doesn't exist.

What do these errors mean?

I'm using library(smcure) to model cure models for credit default data.

Title: Variable Errors for smcure package

Body:
smcure(Surv(DURATION,DEFAULT)~ PURPOSE+RESIDENCE,cureform=~PURPOSE+RESIDENCE,
    data=CD,model="ph",nboot=500)

Error in [[<-.data.frame(*tmp*, i, value = c(6L, 1L, 3L, 2L, 9L, 6L,  :
replacement has 1810 rows, data has 905

smcure(Surv(DURATION,DEFAULT)~.,cureform=~.,
    data=CD,model="ph",nboot=500)

Error in data[, cvars]:
! Can't subset columns that don't exist.
✖ Column . doesn't exist.

What do these errors mean?

I'm using library(smcure) to model cure models for credit default data.


问:
python change a files creation and modification time without having to use a subcommand?
I want to change the modification and creation time of any file with python. This would be the command I use in Linux:

```<code>touch -a -m -t 201512180130.09 ./file.jpg
</code>```

Then I check the following I can see the date is changed correctly:

```<code>$ls -l --time-style=full-iso
-rw-rw-r--  1 me me 44570 2015-12-18 01:30:09.000000000 -0500 file.jpg

$exiftool ./file.jpg | grep -i date
File Modification Date/Time     : 2015:12:18 01:30:09-05:00
File Access Date/Time           : 2015:12:18 01:30:09-05:00
File Inode Change Date/Time     : 2022:12:13 19:39:43-05:00
</code>```

I tried using the Pathlib('./file.jpg').touch() and os.utime('./file.jpg', None). neither worked.
How can I do this in Python without having to use os or subprocess commands?

Body:
I want to change the modification and creation time of any file with python. This would be the command I use in Linux:

touch -a -m -t 201512180130.09 ./file.jpg

Then I check the following I can see the date is changed correctly:

$ls -l --time-style=full-iso
-rw-rw-r--  1 me me 44570 2015-12-18 01:30:09.000000000 -0500 file.jpg

$exiftool ./file.jpg | grep -i date
File Modification Date/Time     : 2015:12:18 01:30:09-05:00
File Access Date/Time           : 2015:12:18 01:30:09-05:00
File Inode Change Date/Time     : 2022:12:13 19:39:43-05:00

I tried using the Pathlib('./file.jpg').touch() and os.utime('./file.jpg', None). neither worked.
How can I do this in Python without having to use os or subprocess commands?


问:
Process oversampled distribution data to normal distribution data?
First, sorry for my poor English skills.

I have data to preprocess, and some columns' distributions are like below figure.

My first opinion is down sample those peak area so that data can have normal-like distribution.

my question is,

if undersampling is good way to preprocess, is there a way to automatically downsampling several columns using for loop? (ex> select SMOTE parameter automatically?)

if undersampling is not good way, can you recommend better way to preprocess distribution?


问:
How do i duplicate my webcam in the same window screen using python?
I'm new to python 3.10. I have the below python code outputting my webcam screen using python. How would I duplicate the webcam output within the same window. One screen on the left of the window and the second screen on the right hand side of the window? Something simple with no buttons. Or so I thought ;)  proving more difficult than anticipated!

and no, "Integrate OpenCV webcam into a Kivy user interface" does not answer the question. I dont want to add button using kivy, i want to duplicate the webcam in the same screen window instance. i tried using kivy with a box layout in 'horizontal' orientation, but cannot figure bring my stream into the 2 box horizontal box layout.
(adding kivy code below)

```<code>import cv2
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

cap=cv2.VideoCapture(0)
cap.release()
cv2.destroyAllWindows()
cap=cv2.VideoCapture(0)
while cap.isOpened():
    ret, frame=cap.read()
    cv2.imshow('VR',frame)
    cv2.imshow('VR', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

class VRWindow(Screen):
    def cam_connect(self):
        cap=cv2.VideoCapture(0)
        while cap.isOpened():
            ret, frame=cap.read()
            cv2.imshow('VR',frame)
            # if cv2.waitKey(1) & 0xFF == ord('q'):
            #     break
    pass

class Window(Screen):
    pass

class ScreenManger(ScreenManager):
    pass

kv = Builder.load_file('vrgui.kv')

class VRApp(App):
     def build(self):
        layout = boxLayout()
        layout.orientation = 'horizontal'

        return kv

if __name__ == '__main__':
    VRApp().run()
</code>```

kv file

```<code>ScreenManager:
    VRWindow:
    Window:

<VRWindow>:
    name: "first"

    FloatLayout:
        #orientation:'horizontal'
            Label:
            text: 'VRLeft'
            size: root.width, root.height
            pos_hint: {'x': 0, 'y': .0}
            size_hint: .5, 1.0
            root.cam_connect()
        Label:
            text: 'VRRight'
            size: root.width, root.height
            pos_hint: {'x': .5, 'y': .0}
            size_hint: .5, 1.0
            #root.cam_connect()
<Window>:
    name: "second"

    FloatLayout:
        #orientation:'horizontal'
        size: root.width, root.height
        pos_hint: {'x': 0, 'y': .0}
        size_hint: 1.0, 1.0
        #root.cam_connect()
</code>```

Thank you for your time.

Body:
I'm new to python 3.10. I have the below python code outputting my webcam screen using python. How would I duplicate the webcam output within the same window. One screen on the left of the window and the second screen on the right hand side of the window? Something simple with no buttons. Or so I thought ;)  proving more difficult than anticipated!

and no, "Integrate OpenCV webcam into a Kivy user interface" does not answer the question. I dont want to add button using kivy, i want to duplicate the webcam in the same screen window instance. i tried using kivy with a box layout in 'horizontal' orientation, but cannot figure bring my stream into the 2 box horizontal box layout.
(adding kivy code below)

import cv2
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout

cap=cv2.VideoCapture(0)
cap.release()
cv2.destroyAllWindows()
cap=cv2.VideoCapture(0)
while cap.isOpened():
    ret, frame=cap.read()
    cv2.imshow('VR',frame)
    cv2.imshow('VR', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

class VRWindow(Screen):
    def cam_connect(self):
        cap=cv2.VideoCapture(0)
        while cap.isOpened():
            ret, frame=cap.read()
            cv2.imshow('VR',frame)
            # if cv2.waitKey(1) & 0xFF == ord('q'):
            #     break
    pass

class Window(Screen):
    pass

class ScreenManger(ScreenManager):
    pass

kv = Builder.load_file('vrgui.kv')

class VRApp(App):
     def build(self):
        layout = boxLayout()
        layout.orientation = 'horizontal'

        return kv

if __name__ == '__main__':
    VRApp().run()

kv file

ScreenManager:
    VRWindow:
    Window:

<VRWindow>:
    name: "first"

    FloatLayout:
        #orientation:'horizontal'
            Label:
            text: 'VRLeft'
            size: root.width, root.height
            pos_hint: {'x': 0, 'y': .0}
            size_hint: .5, 1.0
            root.cam_connect()
        Label:
            text: 'VRRight'
            size: root.width, root.height
            pos_hint: {'x': .5, 'y': .0}
            size_hint: .5, 1.0
            #root.cam_connect()
<Window>:
    name: "second"

    FloatLayout:
        #orientation:'horizontal'
        size: root.width, root.height
        pos_hint: {'x': 0, 'y': .0}
        size_hint: 1.0, 1.0
        #root.cam_connect()

Thank you for your time.


问:
My Windows application freezes using Background worker threads
I have written an application that uses background workers for long running tasks.  At times, after the task is completed, the application will freeze.  It doesn't do it right away, it will do it after the application sits idle for a little bit of time.

To try to find out where it is hanging, in my development environment I ran it and waited for it to freeze.  I then went to Debug > Break All.  It is hanging in the Main() method in Program.cs:

```<code>static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new Main());
    }
}
</code>```

The Application.Run line is highlighted as where the application is hung.  When I hover my cursor over the carat in the left border I get a tool tip saying "This is the next statement to execute when this thread returns from the current function."

In looking at this code I realized that it is calling the "main" form of the application, which I named "Main."  So my first question is does this matter since the current method is named "Main" also?  If so, what are the ramifications of renaming the form, if that is possible?

If that is not an issue, then it would go back to the background worker I would imagine.  The application never freezes if those long running tasks are never ran.  I know that you should never try to access the UI thread from a background worker thread and I don't think I'm doing that but here is some code that hopefully someone may spot something:

First I start the thread from the UI thread passing in an argument:

```<code>bgwInternal.RunWorkerAsync(clients)
</code>```

In the DoWork method it calculates and creates invoices for the passed in argument (clients).  It creates PDF files and saves them to disk.  None of that  work tries to access the UI.  It does use the ProgressChanged event handler to update a progress bar and a label in the UI:

```<code>
</code>```
```<code>    private void bgwInternal_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        pgbProgress.Value = e.ProgressPercentage;
        lblProgress.Text = e.ProgressPercentage.ToString();
    }
</code>```
```<code>
</code>```

And finally the RunWorkerCompleted event handler:

```<code>        private void bgwInternal_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Error occurred during invoice creation.\n\r\n\rError Message: " + e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (!e.Cancelled)
            {
                MessageBox.Show("Invoice Creation Complete", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Invoice Creation Cancelled", "Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            btnCreateInv.Enabled = true;
            btnClose.Enabled = true;
            btnCancel.Enabled = false;
        }
</code>```

Could it be hanging because I'm accessing UI elements in this event handler?

One final note, I was using Application.DoEvents():

```<code>                while (bgwInternal.IsBusy)
                {
                    Application.DoEvents();
                }
</code>```

But I commented that out to see if it would make a difference and it did not.

Not having a lot of multithreading experience I chose to use background worker threads because they are simple and straightforward.  Other than using Debug > Break All I really don't know how to track down the exact reason this is happening.

Any thoughts / ideas would be greatly appreciated.

Thanks.

Body:
I have written an application that uses background workers for long running tasks.  At times, after the task is completed, the application will freeze.  It doesn't do it right away, it will do it after the application sits idle for a little bit of time.

To try to find out where it is hanging, in my development environment I ran it and waited for it to freeze.  I then went to Debug > Break All.  It is hanging in the Main() method in Program.cs:

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Application.Run(new Main());
    }
}

The Application.Run line is highlighted as where the application is hung.  When I hover my cursor over the carat in the left border I get a tool tip saying "This is the next statement to execute when this thread returns from the current function."

In looking at this code I realized that it is calling the "main" form of the application, which I named "Main."  So my first question is does this matter since the current method is named "Main" also?  If so, what are the ramifications of renaming the form, if that is possible?

If that is not an issue, then it would go back to the background worker I would imagine.  The application never freezes if those long running tasks are never ran.  I know that you should never try to access the UI thread from a background worker thread and I don't think I'm doing that but here is some code that hopefully someone may spot something:

First I start the thread from the UI thread passing in an argument:

bgwInternal.RunWorkerAsync(clients)

In the DoWork method it calculates and creates invoices for the passed in argument (clients).  It creates PDF files and saves them to disk.  None of that  work tries to access the UI.  It does use the ProgressChanged event handler to update a progress bar and a label in the UI:

    private void bgwInternal_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        pgbProgress.Value = e.ProgressPercentage;
        lblProgress.Text = e.ProgressPercentage.ToString();
    }

And finally the RunWorkerCompleted event handler:

        private void bgwInternal_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MessageBox.Show("Error occurred during invoice creation.\n\r\n\rError Message: " + e.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (!e.Cancelled)
            {
                MessageBox.Show("Invoice Creation Complete", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Invoice Creation Cancelled", "Cancelled", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            btnCreateInv.Enabled = true;
            btnClose.Enabled = true;
            btnCancel.Enabled = false;
        }

Could it be hanging because I'm accessing UI elements in this event handler?

One final note, I was using Application.DoEvents():

                while (bgwInternal.IsBusy)
                {
                    Application.DoEvents();
                }

But I commented that out to see if it would make a difference and it did not.

Not having a lot of multithreading experience I chose to use background worker threads because they are simple and straightforward.  Other than using Debug > Break All I really don't know how to track down the exact reason this is happening.

Any thoughts / ideas would be greatly appreciated.

Thanks.


问:
Slurm: error in reading shell script when using mpirun. How can I fix this?
I am submitting a job on the debug queue on Niagara (Slurm scheduler) and am getting the following error:

```<code>SALLOC: error: _fork_command: Unable to exec command "/mypath/test.sh": Permission denied
</code>```

I have checked the permissions of the file test.sh and it is readable, in fact I have been using the same file for serial jobs with no problems. I am trying to use mpirun for a parallel job and that's when I get the error.

My shell script is as follows:

```<code>#!/bin/bash

#SBATCH --account= xxxx
#SBATCH --nodes=2
#SBATCH --ntasks=160
#SBATCH --time=3:30:00
#SBATCH --job-name "sNucRNASeq"

pushd /mypath/
mpirun --np 4 R --no-save < Rscript test.R
Rscript test.R

</code>```

I have tried chmod -rwx test.sh, it did not make a difference.
Am I missing something with regards to letting all the processors access the file? How can I by-pass the error?

The test.R script referred to above is pretty simple:

```<code>library(pbdMPI)

init()

rank<-comm.rank()
size<-comm.size()

myfiles<-load("ListofFiles.RData")

y <- scatter(lapply(myfiles, readRDS))
comm.print(str(y))

finalize()
</code>```

Body:
I am submitting a job on the debug queue on Niagara (Slurm scheduler) and am getting the following error:

SALLOC: error: _fork_command: Unable to exec command "/mypath/test.sh": Permission denied

I have checked the permissions of the file test.sh and it is readable, in fact I have been using the same file for serial jobs with no problems. I am trying to use mpirun for a parallel job and that's when I get the error.

My shell script is as follows:

#!/bin/bash

#SBATCH --account= xxxx
#SBATCH --nodes=2
#SBATCH --ntasks=160
#SBATCH --time=3:30:00
#SBATCH --job-name "sNucRNASeq"

pushd /mypath/
mpirun --np 4 R --no-save < Rscript test.R
Rscript test.R

I have tried chmod -rwx test.sh, it did not make a difference.
Am I missing something with regards to letting all the processors access the file? How can I by-pass the error?

The test.R script referred to above is pretty simple:

library(pbdMPI)

init()

rank<-comm.rank()
size<-comm.size()

myfiles<-load("ListofFiles.RData")

y <- scatter(lapply(myfiles, readRDS))
comm.print(str(y))

finalize()


问:
Problem with Networking in unity and mirror
I am about to try my hand at developing a small fps multiplayer game. I have encountered a problem with networking. Namely, I have a player that can fire a gun.

When I use the player in single player everything works fine and I can shoot and the target registers the hits. But when I shoot at another player it depends if the host or the player is shooting. If the host shoots, everything works and the bullet comes out of the player, so to speak. However, when I shoot from another client, the bullet spawns at 0,0,0. Also, when I shoot at the host, only the life indicator of the client goes down, although that of the host (the other player) should go down.

// This is the OnCollisionEnter for the bullet
[ServerCallback]
    void OnCollisionEnter(Collider other)
    {
        Debug.Log($"...collider name: {other.gameObject.name}");
        CustomStats stats = other.gameObject.GetComponent<CustomStats>();

        Debug.Log($"stats exist: {stats != null}, collider name: {other.gameObject.name}");

        if (stats != null )
        {
            if (stats is PlayerStats)
            {
                Debug.Log("Impact on player!");
                if (gameObject.GetComponentInParent<InputMananger>()?.gameObject.name != other.gameObject.name)
                {
                    ((PlayerStats)stats).TakeDamage(10);
                }

            } else if (stats is EnemyStats)
            {
                Debug.Log("Impact on enemy!");
                ((EnemyStats)stats).TakeDamage(10);
            }
        }
    }
```
<pre class="lang-cs prettyprint-override"><code>// This is the calss which is called if the player shoots
public void Shoot()
    {
        if (isLocalPlayer)
        {
            gun = GetComponentInChildren<Gun>();

            Debug.Log("PewPew!");
            CmdFire();
        }

        /*
        if (hitInfo.collider == null) return;

        if (hitEnemy)
        {
            hitInfo.collider.GetComponent<EnemyStats>()?.TakeDamage(gun.damage);
            hitEnemy = false;
        }
        if (hitPlayer)
        {

            CmdFire();
            /*
             Debug.Log("player");
            NetworkIdentity hitPlayerNet = hitInfo.collider.GetComponent<NetworkIdentity>();
            if (hitPlayerNet != null)
            {
                PlayerStats playersStats = hitPlayerNet.gameObject.GetComponent<PlayerStats>();
                Debug.Log($"player script: {playersStats == null}");
                playersStats?.TakeDamge(gun.damage);
            }
                hitPlayer = false;
        }
        */

        hitPlayer = false;
    }

    // this is called on the server
    [Command]
    void CmdFire()
    {
        Debug.Log(" Caller spawn projectile!");
        GameObject projectile = Instantiate(projectilePrefab, projectileMount.position, cameraMount.rotation);
        projectile.GetComponent<Projectile>()?.SetDamage(10);
        projectile.transform.SetParent(projectileMount);

        NetworkServer.Spawn(projectile);
        RpcOnFire();
    }

    // this is called on the tank that fired for all observers
    [ClientRpc]
    void RpcOnFire()
    {
        Debug.Log(" start animation on caller!");
        // shoot animation
    }
</code>```

I have tried many different ways to access the other player. Currently I have a script on the bullet that has an "OnCollisionEnter" function that I want to use to access my collider. In the single player it works as mentioned above but when I shoot from the host to the client it doesn't work.

Body:
I am about to try my hand at developing a small fps multiplayer game. I have encountered a problem with networking. Namely, I have a player that can fire a gun.

When I use the player in single player everything works fine and I can shoot and the target registers the hits. But when I shoot at another player it depends if the host or the player is shooting. If the host shoots, everything works and the bullet comes out of the player, so to speak. However, when I shoot from another client, the bullet spawns at 0,0,0. Also, when I shoot at the host, only the life indicator of the client goes down, although that of the host (the other player) should go down.

// This is the OnCollisionEnter for the bullet
[ServerCallback]
    void OnCollisionEnter(Collider other)
    {
        Debug.Log($"...collider name: {other.gameObject.name}");
        CustomStats stats = other.gameObject.GetComponent<CustomStats>();

        Debug.Log($"stats exist: {stats != null}, collider name: {other.gameObject.name}");

        if (stats != null )
        {
            if (stats is PlayerStats)
            {
                Debug.Log("Impact on player!");
                if (gameObject.GetComponentInParent<InputMananger>()?.gameObject.name != other.gameObject.name)
                {
                    ((PlayerStats)stats).TakeDamage(10);
                }

            } else if (stats is EnemyStats)
            {
                Debug.Log("Impact on enemy!");
                ((EnemyStats)stats).TakeDamage(10);
            }
        }
    }

// This is the calss which is called if the player shoots
public void Shoot()
    {
        if (isLocalPlayer)
        {
            gun = GetComponentInChildren<Gun>();

            Debug.Log("PewPew!");
            CmdFire();
        }

        /*
        if (hitInfo.collider == null) return;

        if (hitEnemy)
        {
            hitInfo.collider.GetComponent<EnemyStats>()?.TakeDamage(gun.damage);
            hitEnemy = false;
        }
        if (hitPlayer)
        {

            CmdFire();
            /*
             Debug.Log("player");
            NetworkIdentity hitPlayerNet = hitInfo.collider.GetComponent<NetworkIdentity>();
            if (hitPlayerNet != null)
            {
                PlayerStats playersStats = hitPlayerNet.gameObject.GetComponent<PlayerStats>();
                Debug.Log($"player script: {playersStats == null}");
                playersStats?.TakeDamge(gun.damage);
            }
                hitPlayer = false;
        }
        */

        hitPlayer = false;
    }

    // this is called on the server
    [Command]
    void CmdFire()
    {
        Debug.Log(" Caller spawn projectile!");
        GameObject projectile = Instantiate(projectilePrefab, projectileMount.position, cameraMount.rotation);
        projectile.GetComponent<Projectile>()?.SetDamage(10);
        projectile.transform.SetParent(projectileMount);

        NetworkServer.Spawn(projectile);
        RpcOnFire();
    }

    // this is called on the tank that fired for all observers
    [ClientRpc]
    void RpcOnFire()
    {
        Debug.Log(" start animation on caller!");
        // shoot animation
    }

I have tried many different ways to access the other player. Currently I have a script on the bullet that has an "OnCollisionEnter" function that I want to use to access my collider. In the single player it works as mentioned above but when I shoot from the host to the client it doesn't work.


问:
Detect Color in Google sheets
Hi is there any formula that can detect color in google sheets?

For example if this cell fills color re then the other cell detects it  and write the word "red".

Title: Detect Color in Google sheets


问:
GitHub repository download
Someone set up a project in a GitHub repository for me to modify.
I did the following steps:

I created a new folder on my laptop.

cd to it and ran: git init

went to github: it gave me an option to download a zip file of the repository set up for me.

I downloaded the zip file and extracted it into my new folder.

updated and tested changes I made to source code.

I did a 'git status' but it doesn't show me the files that I have modified.

Did I set up the project wrong locally?
What is the correct procedure?

Thx,
Jim

i tried git status, but it didn't show me any modified files.

Title: GitHub repository download


问:
DataStax Astra Role unauthorized for operation Rest API Table Select
I am using Postman to make an HTTP rest call to DataStax Astra Cassandra DB to select on a table but it's telling me I don't have select table permission even though the user for the token I'm providing does have that permission.

Here are my inputs

Authorization Type

```<code>API Key
</code>```

Key

```<code>X-Cassandra-Token
</code>```

Value

```<code>$ASTRA_DB_APPLICATION_TOKEN
</code>```

^ of course replaced with my actual token AstraCS::...

And here is the json response I get back

```<code>{
    "description": "Role unauthorized for operation: Not authorized to access keyspace.table for SELECT (from source api: rest)",
    "code": 401
}
</code>```

I double checked that the role associated with the token does have the select table permission.

Body:
I am using Postman to make an HTTP rest call to DataStax Astra Cassandra DB to select on a table but it's telling me I don't have select table permission even though the user for the token I'm providing does have that permission.

Here are my inputs

Authorization Type

API Key

Key

X-Cassandra-Token

Value

$ASTRA_DB_APPLICATION_TOKEN

^ of course replaced with my actual token AstraCS::...

And here is the json response I get back

{
    "description": "Role unauthorized for operation: Not authorized to access keyspace.table for SELECT (from source api: rest)",
    "code": 401
}

I double checked that the role associated with the token does have the select table permission.


问:
Java Card Applet trigger proactive CAT command in process method
I need to get the current time and reset the UICC in an APDU command processed in the process method of the Applet. I'm concerned about the statement in the uicc.toolkit.ProactiveHandlerSystem.getTheHandler() method:

The applet shall get the reference of the handler at its triggering, the beginning of
the processToolkit method.

I assume I will get a HANDLER_NOT_AVAILABLE ToolkitException when trying to get the handler anywhere else except the processToolkit method.

Has anyone experience with this?

What are the alternatives to get the time and execute the reset?

I could get the time in advance after the PROFILE DOWNLOAD event or in the last STATUS event before the process command is triggered. But this would mean to poll the time continuously even if the my APDU command is not called.  I could wait for the next STATUS command and listen to it to execute the reset, but this would be a delay of 30 seconds.


问:
Get cmake to find a custom config file
A cmake project I want to build depends on SDL2, and it comes with the following instruction:

Create a helper called /usr/local/lib/cmake/SDL2/sdl2-config.cmake (because SDL2 doesn't have an SDL2::SDL2 alias) containing:

```<code>if(NOT TARGET SDL2::SDL2
   AND EXISTS "/usr/lib/x86_64-linux-gnu/cmake/SDL2/sdl2-config.cmake")

    include(/usr/lib/x86_64-linux-gnu/cmake/SDL2/sdl2-config.cmake)

    add_library(SDL2 SHARED IMPORTED)
    set_target_properties(SDL2
      PROPERTIES
        IMPORTED_LOCATION "${libdir}/libSDL2.so"
        INTERFACE_INCLUDE_DIRECTORIES "${SDL2_INCLUDE_DIRS}"
    )
    add_library(SDL2::SDL2 ALIAS SDL2)

endif()
</code>```

The problem is that this file isn't found by my cmake (I put a message(...) at the beginning to verify this). If I change the dependency in my CMakeLists.txt from SDL2::SDL2 to just SDL2, it works fine and reads from /usr/lib/x86_64-linux-gnu/cmake/SDL2/sdl2-config.cmake. But this shouldn't be necessary.

How can I get cmake to find this custom file, or how do I find out where to put it?

Title: Get cmake to find a custom config file

Body:
A cmake project I want to build depends on SDL2, and it comes with the following instruction:

Create a helper called /usr/local/lib/cmake/SDL2/sdl2-config.cmake (because SDL2 doesn't have an SDL2::SDL2 alias) containing:

if(NOT TARGET SDL2::SDL2
   AND EXISTS "/usr/lib/x86_64-linux-gnu/cmake/SDL2/sdl2-config.cmake")

    include(/usr/lib/x86_64-linux-gnu/cmake/SDL2/sdl2-config.cmake)

    add_library(SDL2 SHARED IMPORTED)
    set_target_properties(SDL2
      PROPERTIES
        IMPORTED_LOCATION "${libdir}/libSDL2.so"
        INTERFACE_INCLUDE_DIRECTORIES "${SDL2_INCLUDE_DIRS}"
    )
    add_library(SDL2::SDL2 ALIAS SDL2)

endif()

The problem is that this file isn't found by my cmake (I put a message(...) at the beginning to verify this). If I change the dependency in my CMakeLists.txt from SDL2::SDL2 to just SDL2, it works fine and reads from /usr/lib/x86_64-linux-gnu/cmake/SDL2/sdl2-config.cmake. But this shouldn't be necessary.

How can I get cmake to find this custom file, or how do I find out where to put it?


问:
Encode a special character in Webhooks Payload URL GitHub
In GitHib --> /Project/ --> Settings --> Hooks --> Payload URL

Im trying to enter my URL as

```<code>https://username:@p@ssword_@jenkins.link.com:8080/github_webhook/
</code>```

I assume it's throwing an error for the @ right after the colon ":" . How can I enter this in the link?

Body:
In GitHib --> /Project/ --> Settings --> Hooks --> Payload URL

Im trying to enter my URL as

https://username:@p@ssword_@jenkins.link.com:8080/github_webhook/

I assume it's throwing an error for the @ right after the colon ":" . How can I enter this in the link?


问:
JSX element type 'RecoilNexus' does not have any construct or call signatures
When I'm using recoil-nexus with recoil, I'm getting following error.

JSX element type 'RecoilNexus' does not have any construct or call signatures

The code snippet is as following.
Most examples are showing the cases to use recoil-nexus in the app.tsx or app.js.
But I wanna use that in my custom component in node module.

```<code>export function MyRoot(props: MyRootProps): JSX.Element {

  return (
    <RecoilRoot>
      <RecoilNexus />
      {...}
    </RecoilRoot>
  );
}
</code>```

I'd like to know if I can use recoil-nexus in the React component instead of app.tsx in node module.
I build it in node module and use in may main app.

Body:
When I'm using recoil-nexus with recoil, I'm getting following error.

JSX element type 'RecoilNexus' does not have any construct or call signatures

The code snippet is as following.
Most examples are showing the cases to use recoil-nexus in the app.tsx or app.js.
But I wanna use that in my custom component in node module.

export function MyRoot(props: MyRootProps): JSX.Element {

  return (
    <RecoilRoot>
      <RecoilNexus />
      {...}
    </RecoilRoot>
  );
}

I'd like to know if I can use recoil-nexus in the React component instead of app.tsx in node module.
I build it in node module and use in may main app.


问:
Proxying from transparent proxy to HTTP Connect proxy
Our environment requires that all requests to the public internet go through a proxy that uses HTTP tunneling (HTTP Connect). I have a service from a vendor that is not able to use an HTTP Connect proxy.

My plan is to set up a transparent proxy that the service can send traffic to, which will redirect traffic to the HTTP Connect proxy.

```<code>service -> transparent proxy -> http connect proxy -> public internet
</code>```

Is it possible to redirect this traffic without decrypting and re-encrypting the HTTPS request? I won't be able to install any custom certs on the initial service to allow this (and I don't want to view the contents of the HTTP messages anyway). Also, are there any proxies that are made specifically to do this, or will I need to write my own?

Body:
Our environment requires that all requests to the public internet go through a proxy that uses HTTP tunneling (HTTP Connect). I have a service from a vendor that is not able to use an HTTP Connect proxy.

My plan is to set up a transparent proxy that the service can send traffic to, which will redirect traffic to the HTTP Connect proxy.

service -> transparent proxy -> http connect proxy -> public internet

Is it possible to redirect this traffic without decrypting and re-encrypting the HTTPS request? I won't be able to install any custom certs on the initial service to allow this (and I don't want to view the contents of the HTTP messages anyway). Also, are there any proxies that are made specifically to do this, or will I need to write my own?


问:
Python AES decryption
I have a Typescript code I've been trying to convert to Python (I am interested in the decrypting part) but I kept getting bad output, what I am doing wrong?

Code I want to translate:
Typescript

```<code>import CryptoJS from 'crypto-js';
let encrypted = undefined;
let decrypted = undefined;
let key = "d76d312b4647849345285b7c11dbb9e6"
let data = "Data to be encrypted"

encrypted = CryptoJS.AES.encrypt(data, key);
console.log(encrypted.toString()) //results to output like this: U2FsdGVkX198Jnuf6hHeS1bDSP5mrn/+ciFwd5l4Yiw=

decrypted = CryptoJS.AES.decrypt(encrypted, key).toString(CryptoJS.enc.Utf8);
console.log(decrypted) //results to "Data to be encrypted"
</code>```

Python

import base64
from Crypto.Cipher import AES

key = b'b9730baff3f457f7e98be4351387fcbd'

data = "Some_encrypted_base64_here"

unb64_ciphertext = base64.b64decode(data.encode())

decryption_cipher = AES.new(key, AES.MODE_CBC)#, nonce=nonce)
output_data = decryption_cipher.decrypt(unb64_ciphertext)

print("Decrypted message: ", output_data.decode("utf-8", "ignore"))
```

I tried to change the AES moode but that didn't help either

Title: Python AES decryption

Body:
I have a Typescript code I've been trying to convert to Python (I am interested in the decrypting part) but I kept getting bad output, what I am doing wrong?

Code I want to translate:
Typescript

import CryptoJS from 'crypto-js';
let encrypted = undefined;
let decrypted = undefined;
let key = "d76d312b4647849345285b7c11dbb9e6"
let data = "Data to be encrypted"

encrypted = CryptoJS.AES.encrypt(data, key);
console.log(encrypted.toString()) //results to output like this: U2FsdGVkX198Jnuf6hHeS1bDSP5mrn/+ciFwd5l4Yiw=

decrypted = CryptoJS.AES.decrypt(encrypted, key).toString(CryptoJS.enc.Utf8);
console.log(decrypted) //results to "Data to be encrypted"

Python

import base64
from Crypto.Cipher import AES

key = b'b9730baff3f457f7e98be4351387fcbd'

data = "Some_encrypted_base64_here"

unb64_ciphertext = base64.b64decode(data.encode())

decryption_cipher = AES.new(key, AES.MODE_CBC)#, nonce=nonce)
output_data = decryption_cipher.decrypt(unb64_ciphertext)

print("Decrypted message: ", output_data.decode("utf-8", "ignore"))

I tried to change the AES moode but that didn't help either