问:
How to throw custom exception in php while parsing csv files?
I'm writing php code to parse a csv file. I have to validate the basic data type for all the fields in the csv fileds and should throw an instance of a CsvParserException if there is any broken data in the csv file. I've given a generic exception but I want to give a custom exception which is an instance of CsvParserException.

Below is my code. I'm not sure how to to properly handle this.

```<code><?php

namespace app;

class CsvParser{

    public function parse() {
        $row = 1;
        $flag = true;
        if (($handle = fopen("file.csv", "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                $num = count($data);
                echo "<p> $num fields in line $row: <br /></p>\n";
                echo $num;
                $row++;
                if($flag) { $flag = false; continue; } // this is to skip the first line
                for ($c=0; $c < $num; $c++) {
                    echo "data[0] is = ". $data[0] . " data[c] is = ". $data[$c]. " <br />\n";
                    if(!((isset($data[0])) && (is_numeric($data[0])))) {
                        throw new \Exception('Id is not valid');
                    }
                    if(!((isset($data[1])) && (is_string($data[1])))) {
                        throw new \Exception('This is not a valid string. ');
                    }
                    if(!((isset($data[2])) && (is_string($data[2])))) {
                        throw new \Exception('This is not a valid string. ');
                    }
                    $date = strtotime($data[3]);
                    $splitData = explode('|', $data[4]);
                    foreach($splitData as $value) {
                        if(!((isset($value)) && (is_numeric($value)))) {
                            throw new \Exception('Integers is not valid');
                        }
                    }
                }
            }
            fclose($handle);
        }
    }
}

?>
</code>```

Can someone please help ?

Body:
I'm writing php code to parse a csv file. I have to validate the basic data type for all the fields in the csv fileds and should throw an instance of a CsvParserException if there is any broken data in the csv file. I've given a generic exception but I want to give a custom exception which is an instance of CsvParserException.

Below is my code. I'm not sure how to to properly handle this.

<?php

namespace app;

class CsvParser{

    public function parse() {
        $row = 1;
        $flag = true;
        if (($handle = fopen("file.csv", "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                $num = count($data);
                echo "
 $num fields in line $row:

\n";
                echo $num;
                $row++;
                if($flag) { $flag = false; continue; } // this is to skip the first line
                for ($c=0; $c < $num; $c++) {
                    echo "data[0] is = ". $data[0] . " data[c] is = ". $data[$c]. "
\n";
                    if(!((isset($data[0])) && (is_numeric($data[0])))) {
                        throw new \Exception('Id is not valid');
                    }
                    if(!((isset($data[1])) && (is_string($data[1])))) {
                        throw new \Exception('This is not a valid string. ');
                    }
                    if(!((isset($data[2])) && (is_string($data[2])))) {
                        throw new \Exception('This is not a valid string. ');
                    }
                    $date = strtotime($data[3]);
                    $splitData = explode('|', $data[4]);
                    foreach($splitData as $value) {
                        if(!((isset($value)) && (is_numeric($value)))) {
                            throw new \Exception('Integers is not valid');
                        }
                    }
                }
            }
            fclose($handle);
        }
    }
}

?>

Can someone please help ?


来源: stackexchange

问:
Add payment in django project to extend an expiration date of posts./
I have a project where the user can post an Ad and this Ad will be available only for 30 days.

I need to add a payment method to extend the Expiration date of the Ad.

Here is my Ad creation view .

```<code>class AdvertiseCreateView(APIView):
permission_classes = [IsAuthenticated]
def post(self, request):
    serializer = AdvertiseSerializer(data=request.data)
    user = request.user
    if serializer.is_valid():
        print(user)
        serializer.save(owner = user)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

List view:

```<code>class AdvertisesListView(APIView):
def get(self, request):
    advertises = Advertise.objects.filter(Q (expiration_date__gt = Now()))
    serializer = AdvertiseSerializer(advertises, many=True)
    return Response(serializer.data, status = status.HTTP_200_OK)
</code>```

Models:

```<code>class Advertise(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise")
category = models.CharField(max_length= 200, choices = CATEGORY)
location = models.CharField(max_length= 200, choices = LOCATIONS)
description = models.TextField(max_length=600)
price = models.FloatField(max_length=100)
expiration_date  = models.DateField(default = Expire_date, blank=True, null=True) #Expire date come from another file
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)

class Meta:
    ordering = ['created_at']

def __str__(self):
    return self.category
</code>```

So the thing is when the user make his payment the  expire date extends.

I need help in payment part.

Thanks in Advance.

ContentLicense: CC BY-SA 4.0

Body:
I have a project where the user can post an Ad and this Ad will be available only for 30 days.

I need to add a payment method to extend the Expiration date of the Ad.

Here is my Ad creation view .

class AdvertiseCreateView(APIView):
permission_classes = [IsAuthenticated]
def post(self, request):
    serializer = AdvertiseSerializer(data=request.data)
    user = request.user
    if serializer.is_valid():
        print(user)
        serializer.save(owner = user)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

List view:

class AdvertisesListView(APIView):
def get(self, request):
    advertises = Advertise.objects.filter(Q (expiration_date__gt = Now()))
    serializer = AdvertiseSerializer(advertises, many=True)
    return Response(serializer.data, status = status.HTTP_200_OK)

Models:

class Advertise(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="advertise")
category = models.CharField(max_length= 200, choices = CATEGORY)
location = models.CharField(max_length= 200, choices = LOCATIONS)
description = models.TextField(max_length=600)
price = models.FloatField(max_length=100)
expiration_date  = models.DateField(default = Expire_date, blank=True, null=True) #Expire date come from another file
created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True, blank=True, null=True)

class Meta:
    ordering = ['created_at']

def __str__(self):
    return self.category

So the thing is when the user make his payment the  expire date extends.

I need help in payment part.

Thanks in Advance.


问:
Using a raspberry pi with pymongo and neopixels together
So, I am beginning a project where I want to use a Raspberry Pi to take input from a MongoDB database from the web and translate it into neopixel colours. I am running a virtual environment.

My problem is that when I run the code normally (python project.py) pymongo works fine, but the neopixels do not, because the neopixels need sudo authorization. When I run (sudo python project.py) neopixels work, but pymongo thows an error of module not found.

Is there a way I can either run neopixels without sudo or a reason that pymongo does not work in sudo?

Here is the code for clarification:

```<code>
import os
import time
import board
from rainbowio import colorwheel
import neopixel
from pymongo import MongoClient
from dotenv import load_dotenv

load_dotenv()

client = MongoClient(os.getenv('MONGO_URI'))
db = client["led"]
collection = db["users"]
cursor = collection.find().sort([('_id', -1)]).limit(1)
results = cursor[0]
message = results['input'].upper()
msg = message
print(results)
print(msg)

letters = []

pixel_pin = board.D18
num_pixels = 150
pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.3, auto_write=False)

for letter in msg:
    letters.append(letter)

def colour_chase(color, wait):
    for i in range(num_pixels):
        pixels[i] = color
        time.sleep(wait)
        pixels.show()
    time.sleep(0.5)

def rainbow_cycle(wait):
    for j in range(255):
        for i in range(num_pixels):
            rc_index = (i * 256 // num_pixels) + j
            pixels[i] = colorwheel(rc_index & 255)
        pixels.show()
        time.sleep(wait)
CODE = {
' ': '(0, 0, 0)',
"'": '(50, 50, 50)',
'(': '(100, 100, 100)',
')': '(125, 125, 125)',
',': '(150, 150, 150)',
'/': '(175, 175, 175)',
'-': '(200, 2000, 200)',
'.': '(255, 255, 255)',
'0': '(255, 25, 0)',
'1': '(255, 50, 0)',
'2': '(255, 75, 0)',
'3': '(255, 100, 0)',
'4': '(255, 125, 0)',
'5': '(255, 255, 0)',
'6': '(255, 255, 25)',
'7': '(255, 255, 50)',
'8': '(255, 255, 75)',
'9': '(255, 255, 100)',
':': '(255, 255, 125)',
';': '(255, 255, 150)',
'?': '(255, 255, 175)',
'A': '(255, 255, 200)',
'B': '(255, 255, 225)',
'C': '(0, 255, 0)',
'D': '(0, 255, 25)',
'E': '(0, 255, 50)',
'F': '(0, 255, 100)',
'G': '(0, 255, 125)',
'H': '(0, 255, 150)',
'I': '(0, 255, 175)',
'J': '(0, 255, 200)',
'K': '(0, 255, 255)',
'L': '(0, 0, 255)',
'M': '(0, 50, 255)',
'N': '(0, 100, 255)',
'O': '(0, 150, 255)',
'P': '(0, 200, 255)',
'Q': '(0, 255, 255)',
'R': '(255, 0, 25)',
'S': '(255, 0, 50)',
'T': '(255, 0, 75)',
'U': '(255, 0, 100)',
'V': '(255, 0, 125)',
'W': '(255, 0, 150)',
'X': '(255, 0, 200)',
'Y': '(255, 0, 255)',
'Z': '(255, 100, 100)',
'_': '(255, 100, 200)'}

while True:
    codeLetter = ""
    for value in letters:
        codeLetter += CODE[value]
        colour_chase(codeLetter, 0.05)

    #rainbow_cycle(0)

</code>```

I tried to run this in different virtual environments and without a virtual environment and I get the same results. I uninstalled pymongo and reinstalled a few times.

Body:
So, I am beginning a project where I want to use a Raspberry Pi to take input from a MongoDB database from the web and translate it into neopixel colours. I am running a virtual environment.

My problem is that when I run the code normally (python project.py) pymongo works fine, but the neopixels do not, because the neopixels need sudo authorization. When I run (sudo python project.py) neopixels work, but pymongo thows an error of module not found.

Is there a way I can either run neopixels without sudo or a reason that pymongo does not work in sudo?

Here is the code for clarification:

import os
import time
import board
from rainbowio import colorwheel
import neopixel
from pymongo import MongoClient
from dotenv import load_dotenv

load_dotenv()

client = MongoClient(os.getenv('MONGO_URI'))
db = client["led"]
collection = db["users"]
cursor = collection.find().sort([('_id', -1)]).limit(1)
results = cursor[0]
message = results['input'].upper()
msg = message
print(results)
print(msg)

letters = []

pixel_pin = board.D18
num_pixels = 150
pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.3, auto_write=False)

for letter in msg:
    letters.append(letter)

def colour_chase(color, wait):
    for i in range(num_pixels):
        pixels[i] = color
        time.sleep(wait)
        pixels.show()
    time.sleep(0.5)

def rainbow_cycle(wait):
    for j in range(255):
        for i in range(num_pixels):
            rc_index = (i * 256 // num_pixels) + j
            pixels[i] = colorwheel(rc_index & 255)
        pixels.show()
        time.sleep(wait)
CODE = {
' ': '(0, 0, 0)',
"'": '(50, 50, 50)',
'(': '(100, 100, 100)',
')': '(125, 125, 125)',
',': '(150, 150, 150)',
'/': '(175, 175, 175)',
'-': '(200, 2000, 200)',
'.': '(255, 255, 255)',
'0': '(255, 25, 0)',
'1': '(255, 50, 0)',
'2': '(255, 75, 0)',
'3': '(255, 100, 0)',
'4': '(255, 125, 0)',
'5': '(255, 255, 0)',
'6': '(255, 255, 25)',
'7': '(255, 255, 50)',
'8': '(255, 255, 75)',
'9': '(255, 255, 100)',
':': '(255, 255, 125)',
';': '(255, 255, 150)',
'?': '(255, 255, 175)',
'A': '(255, 255, 200)',
'B': '(255, 255, 225)',
'C': '(0, 255, 0)',
'D': '(0, 255, 25)',
'E': '(0, 255, 50)',
'F': '(0, 255, 100)',
'G': '(0, 255, 125)',
'H': '(0, 255, 150)',
'I': '(0, 255, 175)',
'J': '(0, 255, 200)',
'K': '(0, 255, 255)',
'L': '(0, 0, 255)',
'M': '(0, 50, 255)',
'N': '(0, 100, 255)',
'O': '(0, 150, 255)',
'P': '(0, 200, 255)',
'Q': '(0, 255, 255)',
'R': '(255, 0, 25)',
'S': '(255, 0, 50)',
'T': '(255, 0, 75)',
'U': '(255, 0, 100)',
'V': '(255, 0, 125)',
'W': '(255, 0, 150)',
'X': '(255, 0, 200)',
'Y': '(255, 0, 255)',
'Z': '(255, 100, 100)',
'_': '(255, 100, 200)'}

while True:
    codeLetter = ""
    for value in letters:
        codeLetter += CODE[value]
        colour_chase(codeLetter, 0.05)

    #rainbow_cycle(0)

I tried to run this in different virtual environments and without a virtual environment and I get the same results. I uninstalled pymongo and reinstalled a few times.


问:
Calloc vs. malloc for pointer to struct
In dynamically allocating memory for a struct, I ran across some code that does

struct simulation *sim_one = calloc(1, sizeof(*sim_one));
```
<p>Is there any reason to prefer using <code>calloc</code> over <code>malloc</code> for structs? In this context, do they do the same thing? Also, I've only ever seen <code>sizeof</code> called with a datatype; however, the <code>calloc</code> example calls <code>sizeof</code> on a pointer to a variable <code>sim_one</code> which, I would think, doesn't exist at the moment when <code>sizeof</code> is called, but compilation and execution leads to no errors. See below for the <code>malloc</code> example.</p>
<pre class="lang-c prettyprint-override"><code>struct simulation *sim_two = malloc(sizeof(struct simulation));
</code>```

The latter option is syntax for which I am familiar from allocations such as double *var = malloc(sizeof(double)).

I define the structs here for clarity:

struct particle {
  double x;
  double y;
  double z;
};

struct simulation {
  struct particle particles[100];
};

int main(){
  struct simulation *sim_one = calloc(1, sizeof(*sim_one));       // why?
  struct simulation *sim_two = malloc(sizeof(struct simulation)); // familiar malloc syntax
}
```

Title: Calloc vs. malloc for pointer to struct

Body:
In dynamically allocating memory for a struct, I ran across some code that does

struct simulation *sim_one = calloc(1, sizeof(*sim_one));

Is there any reason to prefer using calloc over malloc for structs? In this context, do they do the same thing? Also, I've only ever seen sizeof called with a datatype; however, the calloc example calls sizeof on a pointer to a variable sim_one which, I would think, doesn't exist at the moment when sizeof is called, but compilation and execution leads to no errors. See below for the malloc example.

struct simulation *sim_two = malloc(sizeof(struct simulation));

The latter option is syntax for which I am familiar from allocations such as double *var = malloc(sizeof(double)).

I define the structs here for clarity:

struct particle {
  double x;
  double y;
  double z;
};

struct simulation {
  struct particle particles[100];
};

int main(){
  struct simulation *sim_one = calloc(1, sizeof(*sim_one));       // why?
  struct simulation *sim_two = malloc(sizeof(struct simulation)); // familiar malloc syntax
}


问:
Powershell - Create a JSON object with arrays - System.Collections.Hashtable issue
I want to create a JSON object in powershell, for sending messages to slack from a build pipeline.
The JSON I will be creating looks like this :

```<code>    {
   "blocks":[
      {
         "type":"header",
         "text":{
            "type":"plain_text",
            "text":"Release completed"
         }
      },
      {
         "type":"divider"
      },
      {
         "type":"section",
         "fields":[
            {
               "type":"mrkdwn",
               "text":"*Release number*\nRelease-17"
            },
            {
               "type":"mrkdwn",
               "text":"*User*\nJohn.Smith"
            },
            {
               "type":"mrkdwn",
               "text":"*Source version*\n20230110.1"
            }
         ]
      }
   ]
}
</code>```

So it has an array in there, and a few things that I am struggling with!
So far, I am doing the following :

```<code>$jsonBase = @{}
$blocksList = New-Object System.Collections.ArrayList #this is the main 'blocks' array

$fieldsList = New-Object System.Collections.ArrayList #create a list for the 'fields' section
$fieldsList.Add(@{"type"="mrkdwn";"text"="*Release number*\nRelease-17";})
$fieldsList.Add(@{"type"="mrkdwn";"text"="*User*\nJohn.Smith";})
$fieldsList.Add(@{"type"="mrkdwn";"text"="*Source version*\n20230110.1";})

$textData = @{"type"="plain_text";"text"="Release completed";} #create an object for the header text
$dividerData = @{"type"="divider";} #create an object for the divider

$blocksList.Add(@{"type"="header"; "text"=$textData})
$blocksList.Add(@{"type"="divider"})
$blocksList.Add(@{"type"="section"; "fields"=$fieldsList;})

$jsonBase.Add("blocks",$blocksList)

write-output $jsonBase | ConvertTo-Json
</code>```

But my outputted JSON is not correct at all!

```<code>{
    "blocks":  [
                   {
                       "text":  "System.Collections.Hashtable",
                       "type":  "header"
                   },
                   {
                       "type":  "divider"
                   },
                   {
                       "fields":  "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable",
                       "type":  "section"
                   }
               ]
}
</code>```

Body:
I want to create a JSON object in powershell, for sending messages to slack from a build pipeline.
The JSON I will be creating looks like this :

    {
   "blocks":[
      {
         "type":"header",
         "text":{
            "type":"plain_text",
            "text":"Release completed"
         }
      },
      {
         "type":"divider"
      },
      {
         "type":"section",
         "fields":[
            {
               "type":"mrkdwn",
               "text":"*Release number*\nRelease-17"
            },
            {
               "type":"mrkdwn",
               "text":"*User*\nJohn.Smith"
            },
            {
               "type":"mrkdwn",
               "text":"*Source version*\n20230110.1"
            }
         ]
      }
   ]
}

So it has an array in there, and a few things that I am struggling with!
So far, I am doing the following :

$jsonBase = @{}
$blocksList = New-Object System.Collections.ArrayList #this is the main 'blocks' array

$fieldsList = New-Object System.Collections.ArrayList #create a list for the 'fields' section
$fieldsList.Add(@{"type"="mrkdwn";"text"="*Release number*\nRelease-17";})
$fieldsList.Add(@{"type"="mrkdwn";"text"="*User*\nJohn.Smith";})
$fieldsList.Add(@{"type"="mrkdwn";"text"="*Source version*\n20230110.1";})

$textData = @{"type"="plain_text";"text"="Release completed";} #create an object for the header text
$dividerData = @{"type"="divider";} #create an object for the divider

$blocksList.Add(@{"type"="header"; "text"=$textData})
$blocksList.Add(@{"type"="divider"})
$blocksList.Add(@{"type"="section"; "fields"=$fieldsList;})

$jsonBase.Add("blocks",$blocksList)

write-output $jsonBase | ConvertTo-Json

But my outputted JSON is not correct at all!

{
    "blocks":  [
                   {
                       "text":  "System.Collections.Hashtable",
                       "type":  "header"
                   },
                   {
                       "type":  "divider"
                   },
                   {
                       "fields":  "System.Collections.Hashtable System.Collections.Hashtable System.Collections.Hashtable",
                       "type":  "section"
                   }
               ]
}


问:
File Upload to S3 is occasionally 0 KB
We are using S3 to store excel files. I first parse through the file to grab some data to save to the database before I upload it to the S3 bucket. Though I have yet to get this to happen on my local machine, when this is deployed, the tester sometimes sees the uploaded file being 0 KB even though it was parsed and data was saved to the database.It doesn't happen on my machine and only happens when deployed intermittently. Any ideas of how to resolve this?</p>
```<code>    [HttpPost("ingesttestmatrix")]
    [ProducesResponseType(typeof(TestMatrixResponse), StatusCodes.Status200OK)]
    public ActionResult<string> IngestTestMatrix([FromForm] Guid authenticateduserid, [FromForm] Guid testeventid, IFormFile filename)
    {
        TestMatrixResponse rsp = new TestMatrixResponse();
        List<string> BadDataColumns = new List<string>();
        Guid TestMatrixID = Guid.NewGuid();
        //string newDictName = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\TempFiles" + Guid.NewGuid();
        string newDictName = AppContext.BaseDirectory + @"\TempLLDBFiles" + Guid.NewGuid();
        System.IO.Directory.CreateDirectory(newDictName);
        string baseFileName = Request.Form.Files[0].FileName;
        string newFileName = newDictName + @"\" + baseFileName;

        try
        {
            //create file from stream and then open it for ingesting
            var file = Request.Form.Files[0];
            if (file.Length > 0)
            {
                    using (FileStream fileStream = new FileStream(newFileName, FileMode.Create))
                    {
                        file.CopyTo(fileStream);
                        fileStream.Close();
                    }
            }
            //Do some cool db stuff
            Model.Managers.AmazonFileManager.UploadFile(newFileName, testeventid.ToString()).Wait();
      }
      catch (Exception ex)
        {
            rsp.message = ex.Message.Replace("\"", "");
            LoggingEvent lge = new LoggingEvent(LoggingEventTypeEnum.Error, "Ingest Test Matrix ", ex.Message, authenticateduserid.ToString());
            LoggingEventController leController = new LoggingEventController();
            leController.InsertLoggingEvent(authenticateduserid, lge, LoggingEventTypeEnum.Error);
            rsp.success = false;
       }};

    public static async Task UploadFile(string filePath, string itemGuid)
    {

        try
        {
            var s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
            var fileTransferUtility = new TransferUtility(s3Client);
            string bucketName = "";
            if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("AWSBucketName")))
                bucketName = Environment.GetEnvironmentVariable("AWSBucketName");
            else
                bucketName = _iConfig.GetSection("AWSBucketName").Value;

            PutObjectRequest putObjectRequest = new PutObjectRequest
            {

                BucketName = bucketName,
                StorageClass = S3StorageClass.Standard,
                Key = itemGuid + "/",
                ContentBody = itemGuid
            };

            await s3Client.PutObjectAsync(putObjectRequest);

            string fileKey = itemGuid + "/" + Path.GetFileName(filePath);
            await fileTransferUtility.UploadAsync(filePath, bucketName, fileKey);
        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            if (amazonS3Exception.ErrorCode != null &&
                (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                ||
                amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
            {
                throw new Exception("AWS Error: Check the provided AWS Credentials.");
            }
            else
            {
                throw new Exception("AWS Error: " + amazonS3Exception.Message);
            }
        }
    }
</code>```

Title: File Upload to S3 is occasionally 0 KB

Body:
We are using S3 to store excel files. I first parse through the file to grab some data to save to the database before I upload it to the S3 bucket. Though I have yet to get this to happen on my local machine, when this is deployed, the tester sometimes sees the uploaded file being 0 KB even though it was parsed and data was saved to the database.It doesn't happen on my machine and only happens when deployed intermittently. Any ideas of how to resolve this?

    [HttpPost("ingesttestmatrix")]
    [ProducesResponseType(typeof(TestMatrixResponse), StatusCodes.Status200OK)]
    public ActionResult<string> IngestTestMatrix([FromForm] Guid authenticateduserid, [FromForm] Guid testeventid, IFormFile filename)
    {
        TestMatrixResponse rsp = new TestMatrixResponse();
        List<string> BadDataColumns = new List<string>();
        Guid TestMatrixID = Guid.NewGuid();
        //string newDictName = System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\TempFiles" + Guid.NewGuid();
        string newDictName = AppContext.BaseDirectory + @"\TempLLDBFiles" + Guid.NewGuid();
        System.IO.Directory.CreateDirectory(newDictName);
        string baseFileName = Request.Form.Files[0].FileName;
        string newFileName = newDictName + @"\" + baseFileName;

        try
        {
            //create file from stream and then open it for ingesting
            var file = Request.Form.Files[0];
            if (file.Length > 0)
            {
                    using (FileStream fileStream = new FileStream(newFileName, FileMode.Create))
                    {
                        file.CopyTo(fileStream);
                        fileStream.Close();
                    }
            }
            //Do some cool db stuff
            Model.Managers.AmazonFileManager.UploadFile(newFileName, testeventid.ToString()).Wait();
      }
      catch (Exception ex)
        {
            rsp.message = ex.Message.Replace("\"", "");
            LoggingEvent lge = new LoggingEvent(LoggingEventTypeEnum.Error, "Ingest Test Matrix ", ex.Message, authenticateduserid.ToString());
            LoggingEventController leController = new LoggingEventController();
            leController.InsertLoggingEvent(authenticateduserid, lge, LoggingEventTypeEnum.Error);
            rsp.success = false;
       }};

    public static async Task UploadFile(string filePath, string itemGuid)
    {

        try
        {
            var s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);
            var fileTransferUtility = new TransferUtility(s3Client);
            string bucketName = "";
            if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("AWSBucketName")))
                bucketName = Environment.GetEnvironmentVariable("AWSBucketName");
            else
                bucketName = _iConfig.GetSection("AWSBucketName").Value;

            PutObjectRequest putObjectRequest = new PutObjectRequest
            {

                BucketName = bucketName,
                StorageClass = S3StorageClass.Standard,
                Key = itemGuid + "/",
                ContentBody = itemGuid
            };

            await s3Client.PutObjectAsync(putObjectRequest);

            string fileKey = itemGuid + "/" + Path.GetFileName(filePath);
            await fileTransferUtility.UploadAsync(filePath, bucketName, fileKey);
        }
        catch (AmazonS3Exception amazonS3Exception)
        {
            if (amazonS3Exception.ErrorCode != null &&
                (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                ||
                amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
            {
                throw new Exception("AWS Error: Check the provided AWS Credentials.");
            }
            else
            {
                throw new Exception("AWS Error: " + amazonS3Exception.Message);
            }
        }
    }


问:
R - Why are the values printing to each row, instead of down one column when using 'ddply'?
My new data frame isn't printing properly ...
Why are the values printing to each row, instead of down one column when using 'ddply'?

housing_df <- subset(housing_df,housing_df$zip5 == 98074)

#  Creating a function that calculates cost per sq foot.
sqft_cost <- function(data)
    {(housing_df$Sale.Price)/(housing_df$square_feet_total_living)
}
# using applying function using ddply
sqft_cost1 <- ddply(housing_df, .(addr_full), .fun=sqft_cost)

names(sqft_cost1)[1] <- 'Address'
names(sqft_cost1)[2] <- 'Cost Per SQFT'
head(sqft_cost1)
```


问:
MySQL Query to list all URLs in Media Library - WordPress
A plugin is installed on my site that is offloading everything in media library to an s3 bucket that we have lost access to. To resolve this, I would like to do a MySQL Query to list all full media library URLs, which I can then use to download. To note, when going to the library and individually selecting an image the URL displays the S3 bucket URL which is what I want.

I have found a few php options and plugins, although when I try using them I am getting a blank page. I am assuming this is due to how the plugin is overriding the wordpress URL with the s3 bucket URLs. I tried going through postmeta although I am unsure how to query properly for what I am trying to achieve.

The query below displays a partial, URL but not the full URL

```<code>SELECT * FROM `wp_postmeta`
INNER JOIN wp_posts on wp_posts.id = wp_postmeta.post_id
WHERE wp_postmeta.meta_key = "_wp_attached_file"
ORDER BY `wp_postmeta`.`post_id` DESC
</code>```

Body:
A plugin is installed on my site that is offloading everything in media library to an s3 bucket that we have lost access to. To resolve this, I would like to do a MySQL Query to list all full media library URLs, which I can then use to download. To note, when going to the library and individually selecting an image the URL displays the S3 bucket URL which is what I want.

I have found a few php options and plugins, although when I try using them I am getting a blank page. I am assuming this is due to how the plugin is overriding the wordpress URL with the s3 bucket URLs. I tried going through postmeta although I am unsure how to query properly for what I am trying to achieve.

The query below displays a partial, URL but not the full URL

SELECT * FROM `wp_postmeta`
INNER JOIN wp_posts on wp_posts.id = wp_postmeta.post_id
WHERE wp_postmeta.meta_key = "_wp_attached_file"
ORDER BY `wp_postmeta`.`post_id` DESC


问:
Next.js problems setting up google authorization
I'm trying to set up a next.js(13) app, and I'm trying to add Google authorization to it. There is not much to my code, but it throws errors.

_app.js:

```<code>import '../styles/globals.css'
import {SessionProvider} from "next-auth/react"

    export default function App({ Component, pageProps, session }) {
      return (
        <SessionProvider session={session}>
          <Component {...pageProps} />
        </SessionProvider>
      )
    }
</code>```

[...nextauth].js:

```<code>import NextAuth from 'next-auth/next';
import GoogleProvider from 'next-auth/providers/google';

export default NextAuth({
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        }),
    ],
    secret: process.env.JWT_SECRET
});
</code>```

When I run it I get this Warning: Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. and this error:  TypeError: Cannot read properties of null (reading 'useState')

Any suggestions would be appreciated!

Body:
I'm trying to set up a next.js(13) app, and I'm trying to add Google authorization to it. There is not much to my code, but it throws errors.

_app.js:

import '../styles/globals.css'
import {SessionProvider} from "next-auth/react"

    export default function App({ Component, pageProps, session }) {
      return (
        <SessionProvider session={session}>
          <Component {...pageProps} />
        </SessionProvider>
      )
    }

[...nextauth].js:

import NextAuth from 'next-auth/next';
import GoogleProvider from 'next-auth/providers/google';

export default NextAuth({
    providers: [
        GoogleProvider({
            clientId: process.env.GOOGLE_CLIENT_ID,
            clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        }),
    ],
    secret: process.env.JWT_SECRET
});

When I run it I get this Warning: Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. and this error:  TypeError: Cannot read properties of null (reading 'useState')

Any suggestions would be appreciated!


问:
Privoxy -> Postman Interceptor -> SOCKS Proxy chain failing
I am developing an application, and would like to chain requests from this application through Postman Interceptor followed by a SOCKS5 proxy.

Application -> Privoxy -> Postman Interceptor -> SOCKS5 Server -> Web Server

I was hoping this would work for my Privoxy config:

```<code>forward / localhost:5555
forward-socks5 / user:pass@server.com:1080
</code>```

And from my application, route requests through localhost:8118 (Privoxy).

Unfortunately, the requests only seem to be going through Postman, and not the SOCKS5 server as well.  I also tried to use localhost:5555 as a "parent proxy" to the SOCKS5 proxy, like so:

```<code>forward-socks5 / user:pass@server.com:1080 localhost:5555
</code>```

I also tried appending a single whitespace + a period to the end of these configuration lines, in all possible permutations, hoping that one would result in the expected behavior.

Body:
I am developing an application, and would like to chain requests from this application through Postman Interceptor followed by a SOCKS5 proxy.

Application -> Privoxy -> Postman Interceptor -> SOCKS5 Server -> Web Server

I was hoping this would work for my Privoxy config:

forward / localhost:5555
forward-socks5 / user:pass@server.com:1080

And from my application, route requests through localhost:8118 (Privoxy).

Unfortunately, the requests only seem to be going through Postman, and not the SOCKS5 server as well.  I also tried to use localhost:5555 as a "parent proxy" to the SOCKS5 proxy, like so:

forward-socks5 / user:pass@server.com:1080 localhost:5555

I also tried appending a single whitespace + a period to the end of these configuration lines, in all possible permutations, hoping that one would result in the expected behavior.


问:
Nvim Dap produces error on Mac OS when running debugger on Rust code
I am having a problem trying to debug rust with Neovim on a Macbook Air M2 with Ventura 13.1 installed.

I have already installed llvm by brew install llvm and VSCode is also installed, where the extension CodeLLDB is active. In my Mac, this is found with the following path: /Users/jj/.vscode/extensions/vadimcn.vscode-lldb-1.8.1/adapter/codelldb

Then, I tried to follow the instructions as best I could from here to get this to work.

Under Packer I have the following installed:

```<code>    use("mfussenegger/nvim-dap")
    use({
        "rcarriga/nvim-dap-ui",
        requires = {
            "mfussenegger/nvim-dap",
            "theHamsta/nvim-dap-virtual-text",
            "nvim-telescope/telescope-dap.nvim",
        },
    })

    use("simrat39/rust-tools.nvim")

</code>```

Part of my init.lua file is the following:

```<code>require("dap").adapters.codelldb = {
  type = "server",
  port = "${port}",
  executable = {
    command = "/Users/jj/.vscode/extensions/vadimcn.vscode-lldb-1.8.1/adapter/codelldb",
    args = { "--port", "${port}" },
},
}

require("dap").configurations.rust = {
{
  name = "Launch file",
  type = "codelldb",
  request = "launch",
  program = function()
    return vim.fn.input("Path to executable: ", vim.fn.getcwd() .. "/", "file")
  end,
  cwd = "${workspaceFolder}",
  stopOnEntry = false,
},
}

require("nvim-dap-virtual-text").setup()
require("dapui").setup()

local dap, dapui = require("dap"), require("dapui")
dap.listeners.after.event_initialized["dapui_config"] = function()
    dapui.open()
end
dap.listeners.before.event_terminated["dapui_config"] = function()
    dapui.close()
end
dap.listeners.before.event_exited["dapui_config"] = function()
    dapui.close()
end

require("rust-tools").setup({
    tools = {
        executor = require("rust-tools.executors").termopen,
        reload_workspace_from_cargo_toml = true,

        inlay_hints = {
            lifetimeElisionHints = {
                enable = true,
                useParameterNames = true,
            },
            auto = true,
            only_current_line = true,
            show_parameter_hints = true,
            parameter_hints_prefix = "<- ",
            other_hints_prefix = "-> ",
        },
    },

    server = {
        capabilities = capabilities,
        on_attach = on_attach,
        standalone = true,

        settings = {
            ["rust-analyzer"] = {
                assist = {
                    importPrefix = "by_self",
                },
                cargo = {
                    allFeatures = true,
                },
                checkOnSave = {
                    command = "clippy",
                },
                lens = {
                    references = true,
                    methodReferences = true,
                },
            },
        },
    },

    dap = {
    adapter = require("dap").adapters.codelldb,
    },
})
</code>```

Then, when I run the debugger, it allows me to toggle breakpoints, and then tries to start up, but then gives me the following error:

```<code>[debug-adapter stderr] [2023-01-11T14:49:13.755Z ERROR codelldb::debug_session] '/Users/jj' doesn't contain any 'host' platform architectures: arm64, armv7, armv7f, armv7k, armv7s, armv7m, armv7em, armv6m, armv6, armv5, armv4, arm, thumbv7, thumbv7k, thumbv7s, thumbv7f, thumbv7m, thumbv7em, thumbv6m, thumbv6, thumbv5, thumbv4t, thumb, x86_64, x86_64, arm64, arm64e, arm64, arm64e
</code>```

Maybe something is wrong with the lua config, but I have searched everything and still can't find anything that fixes this.

Then, if I try and use the rust-tools command "RustDebuggables" it gives me a response of Resolved locations: 0 and then it says the following:

```<code>Debug adapter didn't respond. Either the adapter is slow (then wait and ignore this) or there is a problem with your adapter or `rt_lldb` configuration. Check the logs for errors (:help dap.set_log_level)
</code>```

I really don't know what else to put to make this work. Any suggestions would be welcome.

Body:
I am having a problem trying to debug rust with Neovim on a Macbook Air M2 with Ventura 13.1 installed.

I have already installed llvm by brew install llvm and VSCode is also installed, where the extension CodeLLDB is active. In my Mac, this is found with the following path: /Users/jj/.vscode/extensions/vadimcn.vscode-lldb-1.8.1/adapter/codelldb

Then, I tried to follow the instructions as best I could from here to get this to work.

Under Packer I have the following installed:

    use("mfussenegger/nvim-dap")
    use({
        "rcarriga/nvim-dap-ui",
        requires = {
            "mfussenegger/nvim-dap",
            "theHamsta/nvim-dap-virtual-text",
            "nvim-telescope/telescope-dap.nvim",
        },
    })

    use("simrat39/rust-tools.nvim")

Part of my init.lua file is the following:

require("dap").adapters.codelldb = {
  type = "server",
  port = "${port}",
  executable = {
    command = "/Users/jj/.vscode/extensions/vadimcn.vscode-lldb-1.8.1/adapter/codelldb",
    args = { "--port", "${port}" },
},
}

require("dap").configurations.rust = {
{
  name = "Launch file",
  type = "codelldb",
  request = "launch",
  program = function()
    return vim.fn.input("Path to executable: ", vim.fn.getcwd() .. "/", "file")
  end,
  cwd = "${workspaceFolder}",
  stopOnEntry = false,
},
}

require("nvim-dap-virtual-text").setup()
require("dapui").setup()

local dap, dapui = require("dap"), require("dapui")
dap.listeners.after.event_initialized["dapui_config"] = function()
    dapui.open()
end
dap.listeners.before.event_terminated["dapui_config"] = function()
    dapui.close()
end
dap.listeners.before.event_exited["dapui_config"] = function()
    dapui.close()
end

require("rust-tools").setup({
    tools = {
        executor = require("rust-tools.executors").termopen,
        reload_workspace_from_cargo_toml = true,

        inlay_hints = {
            lifetimeElisionHints = {
                enable = true,
                useParameterNames = true,
            },
            auto = true,
            only_current_line = true,
            show_parameter_hints = true,
            parameter_hints_prefix = "<- ",
            other_hints_prefix = "-> ",
        },
    },

    server = {
        capabilities = capabilities,
        on_attach = on_attach,
        standalone = true,

        settings = {
            ["rust-analyzer"] = {
                assist = {
                    importPrefix = "by_self",
                },
                cargo = {
                    allFeatures = true,
                },
                checkOnSave = {
                    command = "clippy",
                },
                lens = {
                    references = true,
                    methodReferences = true,
                },
            },
        },
    },

    dap = {
    adapter = require("dap").adapters.codelldb,
    },
})

Then, when I run the debugger, it allows me to toggle breakpoints, and then tries to start up, but then gives me the following error:

[debug-adapter stderr] [2023-01-11T14:49:13.755Z ERROR codelldb::debug_session] '/Users/jj' doesn't contain any 'host' platform architectures: arm64, armv7, armv7f, armv7k, armv7s, armv7m, armv7em, armv6m, armv6, armv5, armv4, arm, thumbv7, thumbv7k, thumbv7s, thumbv7f, thumbv7m, thumbv7em, thumbv6m, thumbv6, thumbv5, thumbv4t, thumb, x86_64, x86_64, arm64, arm64e, arm64, arm64e

Maybe something is wrong with the lua config, but I have searched everything and still can't find anything that fixes this.

Then, if I try and use the rust-tools command "RustDebuggables" it gives me a response of Resolved locations: 0 and then it says the following:

Debug adapter didn't respond. Either the adapter is slow (then wait and ignore this) or there is a problem with your adapter or `rt_lldb` configuration. Check the logs for errors (:help dap.set_log_level)

I really don't know what else to put to make this work. Any suggestions would be welcome.


问:
markdown display picture well locally but not in browser
My issue is like that:
I insert some pictures in the markdown file. It displays well in VSCode preview, but don't display when I upload it to sharepoint.

I tried both the two types as below.
Please refer to code here:

```<code>![ValueCAN4-2](DPS/Intrepid_ValueCAN4_2.png)
---
---
<img src="DPS/Intrepid_ValueCAN4_2.png">
***
</code>```

Refer to the display

Body:
My issue is like that:
I insert some pictures in the markdown file. It displays well in VSCode preview, but don't display when I upload it to sharepoint.

I tried both the two types as below.
Please refer to code here:

![ValueCAN4-2](DPS/Intrepid_ValueCAN4_2.png)
---
---

***

Refer to the display


问:
How do I get the variable and get it to sort the numbers and print how many passed?
I am somewhat new coding, and tried to make a "macro" of sorts to roll a large amount of dice, and show how many hit, and while I have not got to it yet, apply a modifier if x number was rolled, I am trying to get a variable, "roll dice" for the number from the variable, and then show how many were above a number from another variable.

```<code>import random

#whatisneededtoday will be used to bring up other pieces of code that is needed for the        diffrent actions

whatisneededtoday = input('Select an action attack, psychic, charge, unit table.')

#typeofattack will dictate whether a meele attack is going to be made or a ranged attack

if whatisneededtoday [1] == 't':

  typeofattack = input('meele or ranged? ')

  if typeofattack[0] == 'r':

    print(typeofattack)
    bs = input('what is your balistic skill? ')
    print(bs)
    dice = input('how many dice are needed to roll?')
    randomlist = [random.randint(1,6) for i in range (int(dice))]

    for i in randomlist:
      if randomlist[i] >= int(bs):
        print(dice)

        #if typeofattack[0] == 'm':
         #print(typeofattack)
        #ws = input('what is your weapon skill? ')
        #print(ws)
        #meelehittingphase = input('how many dice are needed to roll? ')

#if whatisneededtoday [0] == 'p':
  #print ("test psychic")
#if whatisneededtoday [0] == 'c':
  #print("charge test")
#if whatisneededtoday [0] == 'u':
  #print("unit table test")`
</code>```

I was hoping for it to take the variables dice, "roll" them, and if they are equal or greater then(gettint this from the variable bs) count them as hit, and if they are x number, either add more hits, wound, or do other affects.`

Body:
I am somewhat new coding, and tried to make a "macro" of sorts to roll a large amount of dice, and show how many hit, and while I have not got to it yet, apply a modifier if x number was rolled, I am trying to get a variable, "roll dice" for the number from the variable, and then show how many were above a number from another variable.

import random

#whatisneededtoday will be used to bring up other pieces of code that is needed for the        diffrent actions

whatisneededtoday = input('Select an action attack, psychic, charge, unit table.')

#typeofattack will dictate whether a meele attack is going to be made or a ranged attack

if whatisneededtoday [1] == 't':

  typeofattack = input('meele or ranged? ')

  if typeofattack[0] == 'r':

    print(typeofattack)
    bs = input('what is your balistic skill? ')
    print(bs)
    dice = input('how many dice are needed to roll?')
    randomlist = [random.randint(1,6) for i in range (int(dice))]

    for i in randomlist:
      if randomlist[i] >= int(bs):
        print(dice)

        #if typeofattack[0] == 'm':
         #print(typeofattack)
        #ws = input('what is your weapon skill? ')
        #print(ws)
        #meelehittingphase = input('how many dice are needed to roll? ')

#if whatisneededtoday [0] == 'p':
  #print ("test psychic")
#if whatisneededtoday [0] == 'c':
  #print("charge test")
#if whatisneededtoday [0] == 'u':
  #print("unit table test")`

I was hoping for it to take the variables dice, "roll" them, and if they are equal or greater then(gettint this from the variable bs) count them as hit, and if they are x number, either add more hits, wound, or do other affects.`


问:
How do you get Xcode Cloud to download Git LFS images?
I am trying to run Xcode Cloud on my unit tests, which include a large number of snapshot tests using png images that are all stored using Git LFS. But when I run the tests on Xcode Cloud, the logs indicate that the images aren't on disk, implying they haven't been downloaded from Git LFS. The documentation says Xcode Cloud comes with Git LFS support but doesn't indicate you need to do anything special to set it up for Xcode Cloud. I've connected Xcode Cloud to my repo, and it shows the tests running, but they're failing because the images are missing.

I have a .gitattributes file at the root level of my repository which contains rules for adding various image file formats to Git LFS. For example, one line says:

*.png filter=lfs diff=lfs merge=lfs -text

What am I missing here? How do I get Xcode Cloud to fetch Git LFS files when it checks out my repo?


问:
How can I make a dropdown menu with no submit button in tkinter?
I have a problem. whenever I create a optionmenu in tkinter, I have to submit its data using a button, but I don't think this is simple enough for the user. Is there a way to get a optionmenu submit its data without the submit button?

I want the dropdown menu to update instantly after the user selects one of the options.


问:
Performance of Salesforce duplicate matching with fuzzy match criteria
We're using Salesforce for Master Data Management (MDM). We're intending to have a custom Apex REST API to check for duplicate account (PersonAccount) objects using the findDuplicates method from the Datacloud namespace.

If we have a Duplicate Rule that has multiple Matching Rules with each Matching Rule having one or more matching criteria (some of which will probably be fuzzy matching criteria) will there be performance issues if we're trying to find duplicates over 1 million records?

For the sake of this discussion lets say there's a Duplicate Rule with 5 Matching Rules and each Matching Rule has 2 matching criterias and in 3 of the Matching Rules one of the criteria is a fuzzy match e.g.

```<code>(Exact Mobile AND Exact Postcode) OR
(Fuzzy Email AND Exact Postcode) OR
(Fuzzy Surname AND Exact DOB) OR
(Exact Mobile AND Fuzzy Surname) OR
(Exact DOB AND Exact Mobile)
</code>```

Will there be performance issues if we're trying to find duplicates over 1 million records?

Hoping this will be microseconds and not something like 20 seconds as the invocation of the custom Apex REST API to check for duplicates will be block the UI. I suspect the fuzzy matching which might use distance algorithms would be hard or impossible to index and as such probably wouldn't be very performant.

Body:
We're using Salesforce for Master Data Management (MDM). We're intending to have a custom Apex REST API to check for duplicate account (PersonAccount) objects using the findDuplicates method from the Datacloud namespace.

If we have a Duplicate Rule that has multiple Matching Rules with each Matching Rule having one or more matching criteria (some of which will probably be fuzzy matching criteria) will there be performance issues if we're trying to find duplicates over 1 million records?

For the sake of this discussion lets say there's a Duplicate Rule with 5 Matching Rules and each Matching Rule has 2 matching criterias and in 3 of the Matching Rules one of the criteria is a fuzzy match e.g.

(Exact Mobile AND Exact Postcode) OR
(Fuzzy Email AND Exact Postcode) OR
(Fuzzy Surname AND Exact DOB) OR
(Exact Mobile AND Fuzzy Surname) OR
(Exact DOB AND Exact Mobile)

Will there be performance issues if we're trying to find duplicates over 1 million records?

Hoping this will be microseconds and not something like 20 seconds as the invocation of the custom Apex REST API to check for duplicates will be block the UI. I suspect the fuzzy matching which might use distance algorithms would be hard or impossible to index and as such probably wouldn't be very performant.


问:
How to achieve child routing in NextJS
How to achieve the equivalent of Angular's child routing in NextJS?

For example going to /todos would display a todo list, then you click a todo item and go to /todos/{id}.

The behaviour that I would like to happen, would be to still have the todos list visible on the screen, from the parent component, and have the todo item details displayed in a designated area for child routing

Title: How to achieve child routing in NextJS


问:
Excel Time sheet issue for Clocked hours
I have a time sheet that shows the Employee Name what action they performed and a unique identifier to the part they are working on in the WO #. I need a way to give a report to each employee of the work they performed on each day (Should be 8 hours). I need to find a way to extract in a different sheet or separate each employee per day and add up the hours for them.

Image of data that needs to be fixed

I can manually sort it and extract the data but I can't spend the time doing the manual extraction every time. The data comes in text csv file so to get the dates correct I already perform a

```<code>Sub ApplyF2()
    Selection.Value = Selection.FormulaR1C1
End Sub
</code>```

to the date to get the dates correct

Body:
I have a time sheet that shows the Employee Name what action they performed and a unique identifier to the part they are working on in the WO #. I need a way to give a report to each employee of the work they performed on each day (Should be 8 hours). I need to find a way to extract in a different sheet or separate each employee per day and add up the hours for them.

Image of data that needs to be fixed

I can manually sort it and extract the data but I can't spend the time doing the manual extraction every time. The data comes in text csv file so to get the dates correct I already perform a

Sub ApplyF2()
    Selection.Value = Selection.FormulaR1C1
End Sub

to the date to get the dates correct


问:
ERROR from PowerShell - ConvertFrom-Json : Invalid JSON primitive:
I've seen many post and researched to no avail.  I did not write this script initially and was told it was working fine until being moved to another network location.  I will share complete script.

it connects to an input file where provider id's are entered, connects to a website API to retrieve names, address, phone number of those providers, then writes that information back to an output file.

I would sincerely appreciate any help with this.

This is the error:

```<code>At G:\somepath\NPI Search\NPI.ps1:42 char:18
+ ...        $NPI_Results = ConvertFrom-Json -InputObject $Response.Content
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
</code>```

Version Info:

```<code>Name                           Value
----                           -----
PSVersion                      5.1.19041.2364
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.2364
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
</code>```

Below this is the complete script

```<code>$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

$INPUT_FILE = "$($scriptDir)\input.csv"
$OUTPUT_FILE = "$($scriptDir)\results.csv"
$API_URL = "https://npiregistry.cms.hhs.gov/api/resultsDemo2/"
$NPI_PATTERN = "^\d{10}$"
$result = @{}

Write-Host "NPI Resolver v1.0`n`n"
Write-Host "[STATUS] Attempting to read NPI Numbers from $($INPUT_FILE)."
try {
    $input = Get-Content -LiteralPath $INPUT_FILE
} catch {
    Write-Host "`n[!!ERROR!!] Unable to open input.csv. Please ensure it is in the same directory as this program.`n"
    exit 1
}
Write-Host "`n[STATUS] Success!`n"
# Write header
$output = "NPI NUMBER,RESULT,LAST UPDATE,NAME,DESCRIPTION,CREDENTIAL,STATUS,ADDRESS 1 LABEL, ADDRESS 1,TELEPHONE 1,ADDRESS 2 LABEL,ADDRESS 2,TELEPHONE 2`n"
# Iterate through each line in input.csv
foreach ($line in $input) {
    # Check if line is a 10 digit number, if not ignore the line
    if ($line -match $NPI_PATTERN) {
        try {
            Write-Host "[STATUS] Requesting results for $($line)..."
            $Response = Invoke-WebRequest -Uri "$($API_URL)?number=$($line)&enumeration_type=&taxonomy_description=&first_name=&last_name=&organization_name=&address_purpose=&city=&state=&postal_code=&country_code=&limit=&skip="
        } catch {
            Write-Host "`n[!!ERROR!!] Error communicating with $($API_URL)`n"
            exit 1
        }
        # Interpret JSON results

        $NPI_Results = ConvertFrom-Json -InputObject $Response.Content

        # Check if a result was found
        if ($NPI_Results.result_count -eq "1") {
            $output = $output + "$($NPI_Results.results.number),SUCCESS,$($NPI_RESULTS.results.basic.last_updated),$($NPI_RESULTS.results.basic.name),`"$($NPI_RESULTS.results.taxonomies.desc)`",$($NPI_RESULTS.results.basic.credential),$($NPI_RESULTS.results.basic.status)"
            foreach ($address in $NPI_Results.results.addresses) {
                $output = $output + ",$($address.address_purpose),`"$($address.address_1), $($address.address_2), $($address.city), $($address.state), $($address.postal_code), $($address.country_code)`",$($address.telephone_number)"
            }
        } else {
            $output = $output + "$($line),NONE"
        }
        $output = $output + "`n"
    }
}
# Save results
try {
    $output | Out-File -LiteralPath $OUTPUT_FILE
} catch {
    Write-Host "`n[!!ERROR!!] Unable to save results.csv. Please close the file if you have it open already and re-run.`n"
    exit 1
}
Write-Host "`n[STATUS] Complete! Check results in $($OUTPUT_File).`n"
</code>```

Body:
I've seen many post and researched to no avail.  I did not write this script initially and was told it was working fine until being moved to another network location.  I will share complete script.

it connects to an input file where provider id's are entered, connects to a website API to retrieve names, address, phone number of those providers, then writes that information back to an output file.

I would sincerely appreciate any help with this.

This is the error:

At G:\somepath\NPI Search\NPI.ps1:42 char:18
+ ...        $NPI_Results = ConvertFrom-Json -InputObject $Response.Content
+                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

Version Info:

Name                           Value
----                           -----
PSVersion                      5.1.19041.2364
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.19041.2364
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Below this is the complete script

$scriptDir = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

$INPUT_FILE = "$($scriptDir)\input.csv"
$OUTPUT_FILE = "$($scriptDir)\results.csv"
$API_URL = "https://npiregistry.cms.hhs.gov/api/resultsDemo2/"
$NPI_PATTERN = "^\d{10}$"
$result = @{}

Write-Host "NPI Resolver v1.0`n`n"
Write-Host "[STATUS] Attempting to read NPI Numbers from $($INPUT_FILE)."
try {
    $input = Get-Content -LiteralPath $INPUT_FILE
} catch {
    Write-Host "`n[!!ERROR!!] Unable to open input.csv. Please ensure it is in the same directory as this program.`n"
    exit 1
}
Write-Host "`n[STATUS] Success!`n"
# Write header
$output = "NPI NUMBER,RESULT,LAST UPDATE,NAME,DESCRIPTION,CREDENTIAL,STATUS,ADDRESS 1 LABEL, ADDRESS 1,TELEPHONE 1,ADDRESS 2 LABEL,ADDRESS 2,TELEPHONE 2`n"
# Iterate through each line in input.csv
foreach ($line in $input) {
    # Check if line is a 10 digit number, if not ignore the line
    if ($line -match $NPI_PATTERN) {
        try {
            Write-Host "[STATUS] Requesting results for $($line)..."
            $Response = Invoke-WebRequest -Uri "$($API_URL)?number=$($line)&enumeration_type=&taxonomy_description=&first_name=&last_name=&organization_name=&address_purpose=&city=&state=&postal_code=&country_code=&limit=&skip="
        } catch {
            Write-Host "`n[!!ERROR!!] Error communicating with $($API_URL)`n"
            exit 1
        }
        # Interpret JSON results

        $NPI_Results = ConvertFrom-Json -InputObject $Response.Content

        # Check if a result was found
        if ($NPI_Results.result_count -eq "1") {
            $output = $output + "$($NPI_Results.results.number),SUCCESS,$($NPI_RESULTS.results.basic.last_updated),$($NPI_RESULTS.results.basic.name),`"$($NPI_RESULTS.results.taxonomies.desc)`",$($NPI_RESULTS.results.basic.credential),$($NPI_RESULTS.results.basic.status)"
            foreach ($address in $NPI_Results.results.addresses) {
                $output = $output + ",$($address.address_purpose),`"$($address.address_1), $($address.address_2), $($address.city), $($address.state), $($address.postal_code), $($address.country_code)`",$($address.telephone_number)"
            }
        } else {
            $output = $output + "$($line),NONE"
        }
        $output = $output + "`n"
    }
}
# Save results
try {
    $output | Out-File -LiteralPath $OUTPUT_FILE
} catch {
    Write-Host "`n[!!ERROR!!] Unable to save results.csv. Please close the file if you have it open already and re-run.`n"
    exit 1
}
Write-Host "`n[STATUS] Complete! Check results in $($OUTPUT_File).`n"


问:
Is it possible to compose paths and evaluate the result in AWS Step Functions?
Is it possible to compose paths in AWS Step Functions? I'm attempting to do something like this:

State Input:

{
  "query": "genre",
  "movies": [
    {
      "genre": "crime",
      "title": "Reservoir Dogs",
      "year": 1992
    }
  ]
}
```
<p>Composing Paths in Parameters:</p>
<pre class="lang-json prettyprint-override"><code>{
  "value1.$": "$.query",
  "value2.$": "$.movies[0].{$.query}"
}
-- or --
{
  "value1.$": "$.query",
  "value2.$": "$.movies[0].{$.value1}"
}
</code>```

Expected Result:

{
  "value1": "genre",
  "value2": "crime"
}
```
<p>Actual Result:</p>
```No results for path: '$.movies[0].{$.query}' specified for the field 'value2.$'  in input JSON.

----

No results for path: '$.movies[0].{$.value1}' specified for the field 'value2.$'  in input JSON.
```

Body:
Is it possible to compose paths in AWS Step Functions? I'm attempting to do something like this:

State Input:

{
  "query": "genre",
  "movies": [
    {
      "genre": "crime",
      "title": "Reservoir Dogs",
      "year": 1992
    }
  ]
}

Composing Paths in Parameters:

{
  "value1.$": "$.query",
  "value2.$": "$.movies[0].{$.query}"
}
-- or --
{
  "value1.$": "$.query",
  "value2.$": "$.movies[0].{$.value1}"
}

Expected Result:

{
  "value1": "genre",
  "value2": "crime"
}

Actual Result:

No results for path: '$.movies[0].{$.query}' specified for the field 'value2.$'  in input JSON.

----

No results for path: '$.movies[0].{$.value1}' specified for the field 'value2.$'  in input JSON.


问:
JsonUnsupportedObjectError was thrown while handling a gesture - Flutter
I'm working on a datable that displays some users with their information and in which each row can change its 'role' and be removed from the site it's associated with by sending a JSON message to kafka into the DB. For this purpose, I added a dropdown button to change their roles and a 'remove' button to remove the user from the site.

But whenever I trigger the 'remove button' or change the role dropdown validation, I receive the following error:

```<code>EXCEPTION CAUGHT BY GESTURE
The following JsonUnsupportedObjectError was thrown while handling a gesture:
Converting object to an encodable object failed: Instance of 'User'

When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49
throw_
dart-sdk/lib/convert/json.dart 794:7
writeObject
dart-sdk/lib/convert/json.dart 875:7
writeMap
dart-sdk/lib/convert/json.dart 830:21
writeJsonValue
dart-sdk/lib/convert/json.dart 785:9
writeObject
dart-sdk/lib/convert/json.dart 983:16
printOn
dart-sdk/lib/convert/json.dart 968:5
stringify
dart-sdk/lib/convert/json.dart 345:30
convert
dart-sdk/lib/convert/json.dart 231:45
encode
dart-sdk/lib/convert/json.dart 114:10
jsonEncode
packages/frontend/data/socketDataStreamController.dart 343:33
editUserSite
packages/frontend/screens/pagesNavigator/sitesManagementPage/sitesUsers.dart
237:64  <fn>

</code>```

My user class is the following:

```<code>class User {
  final String userId;
  String firstName;
  String lastName;
  String email;
  final String company;
  String phoneNumber;
  final String userRole;
  final Uint8List imageBuffer;
  final bool admin;
  String? authToken;
  String country;
  String language;
  List<dynamic> notifications;
  String siteRole;

  User(
      {required this.userId,
      required this.firstName,
      required this.lastName,
      required this.email,
      required this.company,
      required this.phoneNumber,
      required this.imageBuffer,
      required this.userRole,
      required this.admin,
      required this.country,
      required this.language,
      required this.notifications,
      required this.siteRole
      });

  /// Generate new user object from json
  User.fromJSON(
    Map<String, dynamic> json,
  )   : userId = json["_id"] ?? "",
        firstName = json["firstName"] ?? "",
        lastName = json["lastName"] ?? "",
        email = json["email"] ?? "",
        company = json["company"] ?? "",
        phoneNumber = json["phoneNumber"] ?? "",
        userRole = json["userRole"] ?? "",
        imageBuffer = Uint8List(0),
        authToken = json["token"],
        admin = json["admin"] ?? false,
        country = json["country"] ?? "",
        language = json["language"] ?? "",
        notifications = json["notifications"] ?? [],
        siteRole = json["siteRole"] ?? "";

  @override
  String toString() {
    return "User: ${jsonEncode({
          "userId": userId,
          "name": "$firstName $lastName",
          "email": email,
          "company": company,
          "phoneNumber": phoneNumber,
          "userRole": userRole,
          "admin": admin,
          "country": country,
          "language": language,
          "siteRole": siteRole
        })}";
  }
}
</code>```

This is the Button inside the alert dialog that triggers the JSON

```<code>      ElevatedButton(
       child: Text('Yes, remove.'),
       style: ElevatedButton.styleFrom(
       backgroundColor: Colors.grey),
       onPressed: () {
       final userRoleChange = {
             "siteId": widget.site.id,
             "userId": user,
             "status": 0
              };
        globals.socketController.editUserSite(userRoleChange);
        Navigator.of(context).pop()
         },
       ),
</code>```

This is the main.js backend function that connects with kafka:

```<code>socket.on("editUserSite", async (message) => {
        // console.log('on editUserSite')
        let result = true;
        const userData = JSON.parse(message);
        // console.log(userData)

        var requestId = Date.now().toString() + "_backend"
        let dbRequest = topicsLib["userDB-read"]
        dbRequest.query_id = requestId,
        dbRequest.collection = "sites",
        dbRequest.object_id = [userData.siteId]
        dbRequest.requester = "backend"
        dbRequest.field = [
          "users"
        ]

        adminProducer.send( {
          topic: "userDB-read",
          messages: [{ value: JSON.stringify(dbRequest) }],
        });

        const dbUserResponse = await kafkaDbResponse(requestId, logger);

        if (typeof(dbUserResponse.data) == String) {
          logger.error("Error when fetching data" + dbUserResponse)
          throw new Error("Error when fetching data")
        }

        // console.log(dbUserResponse)
        usersList = []
        for (d of dbUserResponse.data[0].users) {
          usersList.push(d)
        }

        // console.log(usersList)
        objIndex = usersList.findIndex((obj => obj.userId == userData.userId));
        console.log(objIndex)
        //The users dont exist , we need to add a user
        if (objIndex  == -1) {
          usersList.push({
            userId:userData.userId,
            role:userData.role,
          })
        } else {
          //Update or Remove user
          if (userData.status == 0) {
            usersList.splice(objIndex, 1);
          } else {
            usersList[objIndex].role = userData.role
          }
        }

        console.log(usersList)
        let dbUpdatePayload = topicsLib["userDB-write"]
        const dbUpdateMessageId = hashCode(Date.now().toString());
        dbUpdatePayload.query_id = dbUpdateMessageId,
        dbUpdatePayload.collection = "sites",
        dbUpdatePayload.object_id = userData.siteId
        dbUpdatePayload.requester = "backend"
        dbUpdatePayload.append = false
        dbUpdatePayload.field = ["users"]
        dbUpdatePayload.data = [usersList]
        dbUpdatePayload.convert_to_object_id = true
        dbUpdatePayload.field_to_object_id = "userId"

        console.log(dbUpdatePayload)
        await adminProducer.send( {
          topic: "userDB-write",
          messages: [
            {
              value: JSON.stringify(dbUpdatePayload),
            },
          ],
        });
        //@ts-ignore
        await sleep(80);

        if (result) {
          response = {
            'status' : 200,
            'message' : 'Site updated',
          }
        } else {
          response = {
            'status' : 400,
            'message' : 'error',
          }
        }
        socket.emit("editUserSiteResponse", response)

      })
</code>```

And this is the socketdataStreamcontroller that consumes it on the frontend:

```<code> void editUserSite(userRoleChange) {
    if (!socket.connected) {
      return;
    }
    socket.emit("editUserSite", jsonEncode(userRoleChange));
  }
</code>```

How can I solve this issue?

Body:
I'm working on a datable that displays some users with their information and in which each row can change its 'role' and be removed from the site it's associated with by sending a JSON message to kafka into the DB. For this purpose, I added a dropdown button to change their roles and a 'remove' button to remove the user from the site.

But whenever I trigger the 'remove button' or change the role dropdown validation, I receive the following error:

EXCEPTION CAUGHT BY GESTURE
The following JsonUnsupportedObjectError was thrown while handling a gesture:
Converting object to an encodable object failed: Instance of 'User'

When the exception was thrown, this was the stack:
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49
throw_
dart-sdk/lib/convert/json.dart 794:7
writeObject
dart-sdk/lib/convert/json.dart 875:7
writeMap
dart-sdk/lib/convert/json.dart 830:21
writeJsonValue
dart-sdk/lib/convert/json.dart 785:9
writeObject
dart-sdk/lib/convert/json.dart 983:16
printOn
dart-sdk/lib/convert/json.dart 968:5
stringify
dart-sdk/lib/convert/json.dart 345:30
convert
dart-sdk/lib/convert/json.dart 231:45
encode
dart-sdk/lib/convert/json.dart 114:10
jsonEncode
packages/frontend/data/socketDataStreamController.dart 343:33
editUserSite
packages/frontend/screens/pagesNavigator/sitesManagementPage/sitesUsers.dart
237:64  <fn>

My user class is the following:

class User {
  final String userId;
  String firstName;
  String lastName;
  String email;
  final String company;
  String phoneNumber;
  final String userRole;
  final Uint8List imageBuffer;
  final bool admin;
  String? authToken;
  String country;
  String language;
  List<dynamic> notifications;
  String siteRole;

  User(
      {required this.userId,
      required this.firstName,
      required this.lastName,
      required this.email,
      required this.company,
      required this.phoneNumber,
      required this.imageBuffer,
      required this.userRole,
      required this.admin,
      required this.country,
      required this.language,
      required this.notifications,
      required this.siteRole
      });

  /// Generate new user object from json
  User.fromJSON(
    Map<String, dynamic> json,
  )   : userId = json["_id"] ?? "",
        firstName = json["firstName"] ?? "",
        lastName = json["lastName"] ?? "",
        email = json["email"] ?? "",
        company = json["company"] ?? "",
        phoneNumber = json["phoneNumber"] ?? "",
        userRole = json["userRole"] ?? "",
        imageBuffer = Uint8List(0),
        authToken = json["token"],
        admin = json["admin"] ?? false,
        country = json["country"] ?? "",
        language = json["language"] ?? "",
        notifications = json["notifications"] ?? [],
        siteRole = json["siteRole"] ?? "";

  @override
  String toString() {
    return "User: ${jsonEncode({
          "userId": userId,
          "name": "$firstName $lastName",
          "email": email,
          "company": company,
          "phoneNumber": phoneNumber,
          "userRole": userRole,
          "admin": admin,
          "country": country,
          "language": language,
          "siteRole": siteRole
        })}";
  }
}

This is the Button inside the alert dialog that triggers the JSON

      ElevatedButton(
       child: Text('Yes, remove.'),
       style: ElevatedButton.styleFrom(
       backgroundColor: Colors.grey),
       onPressed: () {
       final userRoleChange = {
             "siteId": widget.site.id,
             "userId": user,
             "status": 0
              };
        globals.socketController.editUserSite(userRoleChange);
        Navigator.of(context).pop()
         },
       ),

This is the main.js backend function that connects with kafka:

socket.on("editUserSite", async (message) => {
        // console.log('on editUserSite')
        let result = true;
        const userData = JSON.parse(message);
        // console.log(userData)

        var requestId = Date.now().toString() + "_backend"
        let dbRequest = topicsLib["userDB-read"]
        dbRequest.query_id = requestId,
        dbRequest.collection = "sites",
        dbRequest.object_id = [userData.siteId]
        dbRequest.requester = "backend"
        dbRequest.field = [
          "users"
        ]

        adminProducer.send( {
          topic: "userDB-read",
          messages: [{ value: JSON.stringify(dbRequest) }],
        });

        const dbUserResponse = await kafkaDbResponse(requestId, logger);

        if (typeof(dbUserResponse.data) == String) {
          logger.error("Error when fetching data" + dbUserResponse)
          throw new Error("Error when fetching data")
        }

        // console.log(dbUserResponse)
        usersList = []
        for (d of dbUserResponse.data[0].users) {
          usersList.push(d)
        }

        // console.log(usersList)
        objIndex = usersList.findIndex((obj => obj.userId == userData.userId));
        console.log(objIndex)
        //The users dont exist , we need to add a user
        if (objIndex  == -1) {
          usersList.push({
            userId:userData.userId,
            role:userData.role,
          })
        } else {
          //Update or Remove user
          if (userData.status == 0) {
            usersList.splice(objIndex, 1);
          } else {
            usersList[objIndex].role = userData.role
          }
        }

        console.log(usersList)
        let dbUpdatePayload = topicsLib["userDB-write"]
        const dbUpdateMessageId = hashCode(Date.now().toString());
        dbUpdatePayload.query_id = dbUpdateMessageId,
        dbUpdatePayload.collection = "sites",
        dbUpdatePayload.object_id = userData.siteId
        dbUpdatePayload.requester = "backend"
        dbUpdatePayload.append = false
        dbUpdatePayload.field = ["users"]
        dbUpdatePayload.data = [usersList]
        dbUpdatePayload.convert_to_object_id = true
        dbUpdatePayload.field_to_object_id = "userId"

        console.log(dbUpdatePayload)
        await adminProducer.send( {
          topic: "userDB-write",
          messages: [
            {
              value: JSON.stringify(dbUpdatePayload),
            },
          ],
        });
        //@ts-ignore
        await sleep(80);

        if (result) {
          response = {
            'status' : 200,
            'message' : 'Site updated',
          }
        } else {
          response = {
            'status' : 400,
            'message' : 'error',
          }
        }
        socket.emit("editUserSiteResponse", response)

      })

And this is the socketdataStreamcontroller that consumes it on the frontend:

 void editUserSite(userRoleChange) {
    if (!socket.connected) {
      return;
    }
    socket.emit("editUserSite", jsonEncode(userRoleChange));
  }

How can I solve this issue?


问:
How can i delete something from cloud firestore database?
i'm trying to delete a document in my firestore database

i'm using a listview to list some things of my data base, the items of this listview have a delete button, what i want is: when the user presses the delete button, this thing gets deleted from the list and from the firestore, there what i'm trying:

this is my entire activity to do this:

```<code>class RigBuilderActivity : AppCompatActivity() {

    lateinit var botaoAddPc: FloatingActionButton
    lateinit var pcName:EditText
    lateinit var infoButton:FloatingActionButton
    lateinit var pcListView: ListView

    companion object{
        const val TAG = "RigBuilderActivity"

    }

    var pc = arrayListOf<PC>()

    val pcAdapter = PcAdapter()

    val db = Firebase.firestore
    val userId = FirebaseAuth.getInstance().currentUser!!.uid

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rig_builder)
        botaoAddPc = findViewById(R.id.rig_builder_button_add_pc)
        pcName = findViewById(R.id.rig_builder_text_input)
        infoButton = findViewById(R.id.rig_builder_button_info)
        pcListView = findViewById(R.id.rig_builder_pc_list)

        botaoAddPc.setOnClickListener{

            var pc_text :String = pcName.text.toString()
            val computer = PC(UUID.randomUUID().toString(),pc_text)

            db.collection("users").document(userId).collection("PC").add(computer.toHashmapPC()).addOnSuccessListener { task->
                Log.d(TAG, "DocumentSnapshot added with ID: ${task.id}")
                Toast.makeText(this,"Pc added",Toast.LENGTH_SHORT).show()
            }.addOnFailureListener{ e->
                Log.w(TAG,"Error Adding PC",e)
                Toast.makeText(this,"Failed",Toast.LENGTH_SHORT).show()
            }
        }
        pcListView.adapter = pcAdapter

        db.collection("users").document(userId).collection("PC").addSnapshotListener{ value, e->

            if (e!=null){
                Log.w(TAG,"Listen failed.",e)
                return@addSnapshotListener
            }

            pc.clear()
            for (doc in value!!){
                val pc = PC.fromQueryDoc(doc)
                this.pc.add(pc)
            }

            pcAdapter.notifyDataSetChanged()
        }

    }

    fun getPcName():String{
        return pcName.toString()
    }

    inner class PcAdapter : BaseAdapter() {

        override fun getCount(): Int {
            return pc.size
        }

        override fun getItem(p0: Int): Any {
            return pc[p0]
        }

        override fun getItemId(p0: Int): Long {
            return 0
        }

        override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
            val rootView = layoutInflater.inflate(R.layout.pc_item_layout, p2,false )
            val textViewPcName = rootView.findViewById<TextView>(R.id.pc_name)
            val editButton = rootView.findViewById<ImageButton>(R.id.pc_edit_button)
            val deleteButton = rootView.findViewById<FloatingActionButton>(R.id.pc_delete_button)

            textViewPcName.text = pc[p0].counter.toString()

            deleteButton.setOnClickListener{

                val ref : DocumentReference = db.collection("users").document(userId).collection("PC").document(pc[p0].getPcId())

                ref.delete().addOnSuccessListener {
                    Log.d(TAG,"Pc deleted with success")
                    Toast.makeText(this@RigBuilderActivity,"Deleted with success",Toast.LENGTH_SHORT).show()
                }
                pcAdapter.notifyDataSetChanged()
            }

            editButton.setOnClickListener{

            }

            textViewPcName.text = pc[p0].name
            return rootView
        }
    }
}
</code>```

in case of needing, this is my PC class, i'm just using one of the constructors to test the list and make the delete works:

```<code>class PC {

    var id:String
    var name : String? = null
    var counter : Long? = null
    lateinit var cpu :CPU
    lateinit var gpu: GPU
    lateinit var motherBoard: MotherBoard

    /**
     * Construtor de teste
     */
    constructor(id:String, name:String?){
        this.id = id
        this.name = name
    }

    /**
     * Construtor ainda a implementar
     */
    constructor(id:String, name:String?, cpu: CPU,gpu: GPU,motherBoard: MotherBoard){
        this.id = id
        this.name = name
        this.cpu = cpu
        this.gpu = gpu
        this.motherBoard = motherBoard
    }

    fun toHashmapPC() : HashMap <String, Any?>{
        return hashMapOf(
            "id" to id,
            "name" to name
        )
    }

    fun getPcId():String{
        return id
    }

    companion object{
        fun fromQueryDoc(documentSnapshot: DocumentSnapshot):PC{
            return PC(
                documentSnapshot["id"] as String,
                documentSnapshot["name"] as String
            )
        }
    }
}
</code>```

Body:
i'm trying to delete a document in my firestore database

i'm using a listview to list some things of my data base, the items of this listview have a delete button, what i want is: when the user presses the delete button, this thing gets deleted from the list and from the firestore, there what i'm trying:

this is my entire activity to do this:

class RigBuilderActivity : AppCompatActivity() {

    lateinit var botaoAddPc: FloatingActionButton
    lateinit var pcName:EditText
    lateinit var infoButton:FloatingActionButton
    lateinit var pcListView: ListView

    companion object{
        const val TAG = "RigBuilderActivity"

    }

    var pc = arrayListOf<PC>()

    val pcAdapter = PcAdapter()

    val db = Firebase.firestore
    val userId = FirebaseAuth.getInstance().currentUser!!.uid

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rig_builder)
        botaoAddPc = findViewById(R.id.rig_builder_button_add_pc)
        pcName = findViewById(R.id.rig_builder_text_input)
        infoButton = findViewById(R.id.rig_builder_button_info)
        pcListView = findViewById(R.id.rig_builder_pc_list)

        botaoAddPc.setOnClickListener{

            var pc_text :String = pcName.text.toString()
            val computer = PC(UUID.randomUUID().toString(),pc_text)

            db.collection("users").document(userId).collection("PC").add(computer.toHashmapPC()).addOnSuccessListener { task->
                Log.d(TAG, "DocumentSnapshot added with ID: ${task.id}")
                Toast.makeText(this,"Pc added",Toast.LENGTH_SHORT).show()
            }.addOnFailureListener{ e->
                Log.w(TAG,"Error Adding PC",e)
                Toast.makeText(this,"Failed",Toast.LENGTH_SHORT).show()
            }
        }
        pcListView.adapter = pcAdapter

        db.collection("users").document(userId).collection("PC").addSnapshotListener{ value, e->

            if (e!=null){
                Log.w(TAG,"Listen failed.",e)
                return@addSnapshotListener
            }

            pc.clear()
            for (doc in value!!){
                val pc = PC.fromQueryDoc(doc)
                this.pc.add(pc)
            }

            pcAdapter.notifyDataSetChanged()
        }

    }

    fun getPcName():String{
        return pcName.toString()
    }

    inner class PcAdapter : BaseAdapter() {

        override fun getCount(): Int {
            return pc.size
        }

        override fun getItem(p0: Int): Any {
            return pc[p0]
        }

        override fun getItemId(p0: Int): Long {
            return 0
        }

        override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
            val rootView = layoutInflater.inflate(R.layout.pc_item_layout, p2,false )
            val textViewPcName = rootView.findViewById<TextView>(R.id.pc_name)
            val editButton = rootView.findViewById<ImageButton>(R.id.pc_edit_button)
            val deleteButton = rootView.findViewById<FloatingActionButton>(R.id.pc_delete_button)

            textViewPcName.text = pc[p0].counter.toString()

            deleteButton.setOnClickListener{

                val ref : DocumentReference = db.collection("users").document(userId).collection("PC").document(pc[p0].getPcId())

                ref.delete().addOnSuccessListener {
                    Log.d(TAG,"Pc deleted with success")
                    Toast.makeText(this@RigBuilderActivity,"Deleted with success",Toast.LENGTH_SHORT).show()
                }
                pcAdapter.notifyDataSetChanged()
            }

            editButton.setOnClickListener{

            }

            textViewPcName.text = pc[p0].name
            return rootView
        }
    }
}

in case of needing, this is my PC class, i'm just using one of the constructors to test the list and make the delete works:

class PC {

    var id:String
    var name : String? = null
    var counter : Long? = null
    lateinit var cpu :CPU
    lateinit var gpu: GPU
    lateinit var motherBoard: MotherBoard

    /**
     * Construtor de teste
     */
    constructor(id:String, name:String?){
        this.id = id
        this.name = name
    }

    /**
     * Construtor ainda a implementar
     */
    constructor(id:String, name:String?, cpu: CPU,gpu: GPU,motherBoard: MotherBoard){
        this.id = id
        this.name = name
        this.cpu = cpu
        this.gpu = gpu
        this.motherBoard = motherBoard
    }

    fun toHashmapPC() : HashMap <String, Any?>{
        return hashMapOf(
            "id" to id,
            "name" to name
        )
    }

    fun getPcId():String{
        return id
    }

    companion object{
        fun fromQueryDoc(documentSnapshot: DocumentSnapshot):PC{
            return PC(
                documentSnapshot["id"] as String,
                documentSnapshot["name"] as String
            )
        }
    }
}


问:
How to share components between mobile and web without a symbolic link?
Preferable one:

```<code>components/
platforms/
  web/
    index.tsx
  mobile/
    index.tsx
</code>```

This one works on mobile but throws Uncaught ReferenceError: React is not defined on web.

Working one:

```<code>web/
  index.tsx
  shared/ *
    components
mobile/
  index.tsx
  shared/ *
    components/

* : symbolic link
</code>```

This one works both on mobile and web but uses symbolic link.

Body:
Preferable one:

components/
platforms/
  web/
    index.tsx
  mobile/
    index.tsx

This one works on mobile but throws Uncaught ReferenceError: React is not defined on web.

Working one:

web/
  index.tsx
  shared/ *
    components
mobile/
  index.tsx
  shared/ *
    components/

* : symbolic link

This one works both on mobile and web but uses symbolic link.


问:
Why hash match join may be faster than join raw values in SQL?
I don't understand why transforming inputs by using hash function might be faster when joining tables than just compare values without hashing.

Using hash match join, SQL have to read all rows for join column and create corresponding values using hash function. Then it have to read all rows from a second table and again use hash function for each value. Using hash function is an additional step and SQL have to read all rows from first and second table, just like using nested loops.

Why hash match might be faster? Nested loops also have to read all rows from both tables, so why using hash function on join columns might perform better? It's an additional step, can't we just compare values without hashing?

I try to understand why it can be faster but every tutorial I have encountered doesn't really explain why hashing join values and then comparing them in bins may be faster than comparing "raw" values in bins.


问:
Error in `[.xgb.DMatrix`(x, 0, , drop = FALSE) : unused argument (drop = FALSE) using R
I was using this code:

```<code>xgb_model <- caret::train(
   x_train, y_train,
   trControl = xgb_trcontrol,
   tuneGrid = xgb_grid,
   method = "xgbTree",
   nthread = 1
)

</code>```

and get this error:

```<code>Error in `[.xgb.DMatrix`(x, 0, , drop = FALSE) :
  unused argument (drop = FALSE)
</code>```

Body:
I was using this code:

xgb_model <- caret::train(
   x_train, y_train,
   trControl = xgb_trcontrol,
   tuneGrid = xgb_grid,
   method = "xgbTree",
   nthread = 1
)

and get this error:

Error in `[.xgb.DMatrix`(x, 0, , drop = FALSE) :
  unused argument (drop = FALSE)


问:
Having trouble connecting Prestashop to DigitalOcean Managed Database
I encountered an issue with the Prestashop initial installation process. When I want to define DigitalOcean managed database as the primary database, I will get this error message:
"You must be granted the privilege to select data in the tables of database "prestashop". Ask your hosting provider to enable it.
Unknown table 'prestashop.ps_test'"

I granted all the permissions to the user, even the "doadmin" user, which has all the access levels get the same error message.

any suggestions would be highly appreciated.


问:
Java Locale LanguageRange priority list: how to list en-US-POSIX after en-US?
Java Locale LanguageRange: how to list en-US-POSIX after en-US?

```<code>    List<LanguageRange> ranges = LanguageRange.parse("en-US;q=1.0,en-US-POSIX;q=0.9");

    List<Locale> locales = Locale.filter(ranges,
            Arrays.asList(Locale.getAvailableLocales()));
</code>```

The result is en-US-POSIX, en-US.

The order expected is en-US, en-US-POSIX.

java 11.

Body:
Java Locale LanguageRange: how to list en-US-POSIX after en-US?

    List<LanguageRange> ranges = LanguageRange.parse("en-US;q=1.0,en-US-POSIX;q=0.9");

    List<Locale> locales = Locale.filter(ranges,
            Arrays.asList(Locale.getAvailableLocales()));

The result is en-US-POSIX, en-US.

The order expected is en-US, en-US-POSIX.

java 11.