问:
Failing to add controls to a page dynamically
I'm adding a User Control for each record pulled up in a data reader, here's the basic loop:

```<code>while (dr.Read())
{
     ImageSelect imgSel = new ImageSelect(dr["Name"].ToString());
     myPanel.Controls.Add(imgSel);
}
</code>```

The problem is that there are no controls added to the page, I check the html output and there is my panel, with nothing in it.

I even stepped through the code in the debugger, and verified that myPanel.Controls gets a control added on each loop, with the count being 6, no errors, but then they dont show up on the page.

I've run the above code in the Page_Init and Page_Load events, both with the same result.

EDIT:
Ok so I've switched to using LoadControl("....ascx") to get my control instance, which is now working.  But originally I was also passing in data via the controls constructor.. Is this still possible or do I just need to set them via get/sets?

EDIT 2:
Thanks to Freddy for pointing out that the LoadControl has an overload where you CAN pass in constructor params, see accepted answer.

EDIT 3:
After trying this method both with and without the constructor.  I have found its better to just use setters for any properties I want the control to have versus trying to use the passed in object array for my constructor.

答:
To add UserControls you must call the LoadControl method passing in the path to the .ascx file.  You can not create them by just instantiating the object the .ascx file inherits from.

A UserControl consists of both the markup and the class in the code behind.  The markup contains a link to the class behind, but the class behind does not know where the markup lives and therefore can not be created on it's own.

OwnerDisplayName: Neil N

ContentLicense: CC BY-SA 2.5

Body:
I'm adding a User Control for each record pulled up in a data reader, here's the basic loop:

while (dr.Read())
{
     ImageSelect imgSel = new ImageSelect(dr["Name"].ToString());
     myPanel.Controls.Add(imgSel);
}

The problem is that there are no controls added to the page, I check the html output and there is my panel, with nothing in it.

I even stepped through the code in the debugger, and verified that myPanel.Controls gets a control added on each loop, with the count being 6, no errors, but then they dont show up on the page.

I've run the above code in the Page_Init and Page_Load events, both with the same result.

EDIT:
Ok so I've switched to using LoadControl("....ascx") to get my control instance, which is now working.  But originally I was also passing in data via the controls constructor.. Is this still possible or do I just need to set them via get/sets?

EDIT 2:
Thanks to Freddy for pointing out that the LoadControl has an overload where you CAN pass in constructor params, see accepted answer.

EDIT 3:
After trying this method both with and without the constructor.  I have found its better to just use setters for any properties I want the control to have versus trying to use the passed in object array for my constructor.

LastEditorDisplayName: Freddy Rios

OwnerDisplayName: Daniel


来源: stackexchange

问:
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data in React js
I have spent many hours to solve that error or also see othersites to solve that but no solution found so I need help for solve that error

Screenshort here - https://i.stack.imgur.com/XbBJ5.jpg

I use https://www.twilio.com/blog/video-chat-react-hooks for create video app becuase of that       above error I have not enter into the room

Here is the code below.

```<code>import React, { useState, useCallback } from "react";
import Lobby from "./Lobby";
import Room from "./Room";
const VideoChat = () => {
  const [username, setUsername] = useState("");
  const [roomName, setRoomName] = useState("");
  const [token, setToken] = useState(null);

  const handleUsernameChange = useCallback((event) => {
    setUsername(event.target.value);
  }, []);

  const handleRoomNameChange = useCallback((event) => {
    setRoomName(event.target.value);
  }, []);

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = fetch("/video/token", {
      method: "POST",
      body: JSON.stringify({
        identity: username,
        room: roomName,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());
    setToken(data.token);
  };
  const handleLogout = useCallback((event) => {
    setToken(null);
  }, []);

  let render;
  if (token) {
    render = (
      <Room roomName={roomName} token={token} handleLogout={handleLogout} />
    );
  } else {
    render = (
      <Lobby
        username={username}
        roomName={roomName}
        handleUsernameChange={handleUsernameChange}
        handleRoomNameChange={handleRoomNameChange}
        handleSubmit={handleSubmit}
      />
    );
  }

  return render;
};

export default VideoChat;
</code>```

答:
Twilio developer evangelist here.

As epascarello pointed out, when you make the request to get the token you are receiving a 404 response.

When you run this application, you need to start both the client side application and the server. To do this you should run

```<code>npm run dev
</code>```

When you run npm start it will only run the React application, the server application won't run and you will get 404 responses when making requests to it. This is all based on my blog post on creating a React application with a proxy to an Express server in which you can see the details of how this is set up.

ContentLicense: CC BY-SA 4.0

Body:
I have spent many hours to solve that error or also see othersites to solve that but no solution found so I need help for solve that error

Screenshort here - https://i.stack.imgur.com/XbBJ5.jpg

I use https://www.twilio.com/blog/video-chat-react-hooks for create video app becuase of that       above error I have not enter into the room

Here is the code below.

import React, { useState, useCallback } from "react";
import Lobby from "./Lobby";
import Room from "./Room";
const VideoChat = () => {
  const [username, setUsername] = useState("");
  const [roomName, setRoomName] = useState("");
  const [token, setToken] = useState(null);

  const handleUsernameChange = useCallback((event) => {
    setUsername(event.target.value);
  }, []);

  const handleRoomNameChange = useCallback((event) => {
    setRoomName(event.target.value);
  }, []);

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = fetch("/video/token", {
      method: "POST",
      body: JSON.stringify({
        identity: username,
        room: roomName,
      }),
      headers: {
        "Content-Type": "application/json",
      },
    }).then((res) => res.json());
    setToken(data.token);
  };
  const handleLogout = useCallback((event) => {
    setToken(null);
  }, []);

  let render;
  if (token) {
    render = (
      <Room roomName={roomName} token={token} handleLogout={handleLogout} />
    );
  } else {
    render = (
      <Lobby
        username={username}
        roomName={roomName}
        handleUsernameChange={handleUsernameChange}
        handleRoomNameChange={handleRoomNameChange}
        handleSubmit={handleSubmit}
      />
    );
  }

  return render;
};

export default VideoChat;

Body:
Twilio developer evangelist here.

As epascarello pointed out, when you make the request to get the token you are receiving a 404 response.

When you run this application, you need to start both the client side application and the server. To do this you should run

npm run dev

When you run npm start it will only run the React application, the server application won't run and you will get 404 responses when making requests to it. This is all based on my blog post on creating a React application with a proxy to an Express server in which you can see the details of how this is set up.


问:
How to change background color depending on the day of the week using PHP
I need to change the background color of the header box according to the day of the week. For example if the day is Monday or Wednesday the background of the header should be pink, otherwise it should be blue. I found something like this online but it doesn't work. Also I'm not sure where to put the if statement, in the head or the body part? I put this code in the head part and it didn't work.

$t = date("l");
if ($t == 'Monday' || $t == 'Wednesday') {
    echo "";
} else {
    echo "";
}
```

Anything I found online was with javascript and I don't know js (I'm very new to coding) so I'm not sure If I should learn and use it or try something else.
Thanks for the help in advance.

答:
Check and return the color value, then use it in the body.

```<code><?php

$day = date("l");
$color = ($day == "Monday" || $day == "Wednesday") ? 'pink' : 'blue';

?>

<body style="background-color: <?= $color ?>;">

</body>
</code>```

Body:
I need to change the background color of the header box according to the day of the week. For example if the day is Monday or Wednesday the background of the header should be pink, otherwise it should be blue. I found something like this online but it doesn't work. Also I'm not sure where to put the if statement, in the head or the body part? I put this code in the head part and it didn't work.

$t = date("l");
if ($t == 'Monday' || $t == 'Wednesday') {
    echo "";
} else {
    echo "";
}

Anything I found online was with javascript and I don't know js (I'm very new to coding) so I'm not sure If I should learn and use it or try something else.
Thanks for the help in advance.

Body:
Check and return the color value, then use it in the body.

<?php

$day = date("l");
$color = ($day == "Monday" || $day == "Wednesday") ? 'pink' : 'blue';

?>

<body style="background-color: <?= $color ?>;">

</body>


问:
How can I return an optional instead of throwing an exception?
I have a method that can possibly throw an error. This exception is out of my control, as it is an IO exception, not a exception I am throwing. Instead of adding a throws statement to my method or fitting it in a try and catch block, would I be able to return an optional via this method?

Summary: I have a method to return a value T, except to get to that value, I have to add a try/catch block or throws statement to my method. Can I return an Optional of type T instead of throwing this error?

答:
"Instead of adding a throws statement to my method or fitting it in a try and catch block"

Well, those are your two options.  Either you can

Catch the exception yourself and return an empty Optional. This is not a good idea as it hides the exception, OR

You can let the exception propagate.

I suppose a third option is to wrap the exception in an unchecked exception, but that just makes your interface murkier.

If you really want to defer error handling to the caller and not throw, the ideal solution is to implement a composite object to return, containing both the error status and the return value if there is one.


问:
MPI import works with sbatch but fails with srun
I'm facing a strange problem when trying to use MPI on a cluster, which uses Slurm as a job scheduler. On both cases, I'm trying to run this simple python program:

```<code>from mpi4py import MPI
print('TEST')
</code>```

Creating a batch script (where I export the suitable virtual environment and run this python program) and using it with sbatch works great.

However, using srun in the terminal to run the same program (inside the same virtual environment) produces the following error:

```<code>*** An error occurred in MPI_Init_thread
*** on a NULL communicator
*** MPI_ERRORS_ARE_FATAL (processes in this communicator will now abort,
***    and potentially your MPI job)
[w7:564843] Local abort before MPI_INIT completed successfully, but am not able to aggregate error messages, and not able to guarantee that all other processes were killed!
srun: error: w7: task 0: Exited with exit code 1
</code>```

If I don't import MPI, the python script is executed correctly both with srun and sbatch.

Slurm version is: 19.05.5

OpenMPI version is: 4.0.3

What is the difference between srun and sbatch that makes the former fail and the later work when using MPI? What should I change to make this code run correctly using srun?

答:
Running the job with srun and with pmix support ( srun --mpi=pmix_v3 a.out ) seems to completely solve the issue. For more information about using slurm with pmix support: https://slurm.schedmd.com/mpi_guide.html

I was unaware that our OpenMPI was built without pmi2 support, so this explains why it didn't work with pmi2

Body:
I'm facing a strange problem when trying to use MPI on a cluster, which uses Slurm as a job scheduler. On both cases, I'm trying to run this simple python program:

from mpi4py import MPI
print('TEST')

Creating a batch script (where I export the suitable virtual environment and run this python program) and using it with sbatch works great.

However, using srun in the terminal to run the same program (inside the same virtual environment) produces the following error:

*** An error occurred in MPI_Init_thread
*** on a NULL communicator
*** MPI_ERRORS_ARE_FATAL (processes in this communicator will now abort,
***    and potentially your MPI job)
[w7:564843] Local abort before MPI_INIT completed successfully, but am not able to aggregate error messages, and not able to guarantee that all other processes were killed!
srun: error: w7: task 0: Exited with exit code 1

If I don't import MPI, the python script is executed correctly both with srun and sbatch.

Slurm version is: 19.05.5

OpenMPI version is: 4.0.3

What is the difference between srun and sbatch that makes the former fail and the later work when using MPI? What should I change to make this code run correctly using srun?


问:
How to handle Docker login to Gitlab container registry with multiple concurrent jobs?
We use Gitlab CI/CD, building and deploying with runners on locally hosted machines and using the Gitlab container registry to store our Docker images. We log in to the Gitlab registry like so:

default:
  before_script:
    - "docker login -u \"${CI_REGISTRY_USER}\" -p \"${CI_REGISTRY_PASSWORD}\" \"${CI_REGISTRY}\""
```

This works fine with the runners in our deployment environments, which each only run a single job concurrently. However, our build machine is supposed to run multiple build jobs concurrently. The problem is, the ${CI_REGISTRY_PASSWORD} provided by Gitlab for each job is different and, it seems, valid only for that job. Thus, when we have multiple jobs running at once, their calls to docker login overwrite each other, causing other jobs to fail with authentication required errors.

Currently, we're working around the problem by performing a new docker login command before every docker push or docker pull to minimize the chance that another job will perform a login command of its own in between, but there's got to be a better way.

What is the recommended solution for managing Docker registry logins with concurrent jobs?

答:
This sort of thing is best handled using a Deploy Token, it's exactly what it was intended for. This allows you to set a user, so you can tell the CI server was the one who pushed the container, and also set expiration for security reasons:

https://docs.gitlab.com/ee/user/project/deploy_tokens/

Body:
We use Gitlab CI/CD, building and deploying with runners on locally hosted machines and using the Gitlab container registry to store our Docker images. We log in to the Gitlab registry like so:

default:
  before_script:
    - "docker login -u \"${CI_REGISTRY_USER}\" -p \"${CI_REGISTRY_PASSWORD}\" \"${CI_REGISTRY}\""

This works fine with the runners in our deployment environments, which each only run a single job concurrently. However, our build machine is supposed to run multiple build jobs concurrently. The problem is, the ${CI_REGISTRY_PASSWORD} provided by Gitlab for each job is different and, it seems, valid only for that job. Thus, when we have multiple jobs running at once, their calls to docker login overwrite each other, causing other jobs to fail with authentication required errors.

Currently, we're working around the problem by performing a new docker login command before every docker push or docker pull to minimize the chance that another job will perform a login command of its own in between, but there's got to be a better way.

What is the recommended solution for managing Docker registry logins with concurrent jobs?


问:
mongodb aggregation pipeline solution for getting record from 2 collections based on the value from an array in one collection
I have two mongoDb collections, one contains data about cards and the other contains data about a field of cards and called list.
structure of firstCollection :

```<code>{
    "cardType":"card",
    "xyz":"XYZ",
    "fields":[
        {"abc":"abc", "xyz":"XYZ", "inputMethod" : "Entry", "xyz":"xyz"},
        {"abc":"abc", "xyz":"XYZ", "inputMethod" : "List", "xyz":"xyz", "ListId":"1234"}
        // ListId will only be present incase of inputMethod=List
    ]
}
</code>```

Structure of secondCollection:

```<code>{ "abc":"abc", "xyz":"xyz, "itemId": "1234" }
</code>```

Now what I want is
all the firstCollection where cardType = "card", complete card object
and
all the items from secondCollection where itemId in (select ListId from firstCollection where fields.inputmethod = "List").

Need to write MongoDB pipeline for this situation. I am quite new to mongo, it can be done using an aggregation pipeline with $loopup but I can write the pipeline.
the result I want :

```<code>{
    firstCollection:{complete collection },
    secondCollection:[
        array of matching records from second collection where
        secondelement.itemId in(records from array of firstcollection
        where fields.inputmethod = "List" )
    ]
}
</code>```

答:
```<code>db.first.aggregate([
  {
    $match: {}
  },
  {
    $project: {
      firstCollection: "$$ROOT"
    }
  },
  {
    $lookup: {
      "from": "second",
      "localField": "firstCollection.fields.ListId",
      "foreignField": "itemId",
      "as": "secondCollection"
    }
  }
])
</code>```

mongoplayground

Body:
I have two mongoDb collections, one contains data about cards and the other contains data about a field of cards and called list.
structure of firstCollection :

{
    "cardType":"card",
    "xyz":"XYZ",
    "fields":[
        {"abc":"abc", "xyz":"XYZ", "inputMethod" : "Entry", "xyz":"xyz"},
        {"abc":"abc", "xyz":"XYZ", "inputMethod" : "List", "xyz":"xyz", "ListId":"1234"}
        // ListId will only be present incase of inputMethod=List
    ]
}

Structure of secondCollection:

{ "abc":"abc", "xyz":"xyz, "itemId": "1234" }

Now what I want is
all the firstCollection where cardType = "card", complete card object
and
all the items from secondCollection where itemId in (select ListId from firstCollection where fields.inputmethod = "List").

Need to write MongoDB pipeline for this situation. I am quite new to mongo, it can be done using an aggregation pipeline with $loopup but I can write the pipeline.
the result I want :

{
    firstCollection:{complete collection },
    secondCollection:[
        array of matching records from second collection where
        secondelement.itemId in(records from array of firstcollection
        where fields.inputmethod = "List" )
    ]
}

Body:
db.first.aggregate([
  {
    $match: {}
  },
  {
    $project: {
      firstCollection: "$$ROOT"
    }
  },
  {
    $lookup: {
      "from": "second",
      "localField": "firstCollection.fields.ListId",
      "foreignField": "itemId",
      "as": "secondCollection"
    }
  }
])

mongoplayground


问:
time complexities of algorithms
What are the time complexities of these two algorithms? I got 3n/2 + 6 for the first one, and 3logn + 6 for the second and I'm not sure if I'm doing them right.

```<code>int i  = 0 ;
double evenSum = 0.0 ;
while ( i < n) {
    evenSum = evenSum + data[i] ;
    i += 2;
}
StdOut.println(evenSum);
</code>```

and the second is similar it just multiples by  2

```<code>int i = 0 ;
double evenSum = 0.0 ;
while ( i < n) {
    evenSum = evenSum + data[i] ;
    i *= 2;
}
StdOut.println(evenSum);
</code>```

and I got 3n/2 + 6 and 3log n + 6

答: Time complexity for the first one is O(n). The second one is infinite loop. for (i = 0) * 2 => 0 and won't exit loop. In case i = 1, then its time complexity is O(log(n)).</p>

Title: time complexities of algorithms

Body:
What are the time complexities of these two algorithms? I got 3n/2 + 6 for the first one, and 3logn + 6 for the second and I'm not sure if I'm doing them right.

int i  = 0 ;
double evenSum = 0.0 ;
while ( i < n) {
    evenSum = evenSum + data[i] ;
    i += 2;
}
StdOut.println(evenSum);

and the second is similar it just multiples by  2

int i = 0 ;
double evenSum = 0.0 ;
while ( i < n) {
    evenSum = evenSum + data[i] ;
    i *= 2;
}
StdOut.println(evenSum);

and I got 3n/2 + 6 and 3log n + 6


问:
How to use Scrapy to parse PDFs?
I would like to download all PDFs found on a site, e.g. https://www.stadt-koeln.de/politik-und-verwaltung/bekanntmachungen/amtsblatt/index.html. I also tried to use rules but I think it's not neccessary here.

This is my approach:

```<code>import scrapy
from scrapy.linkextractors import IGNORED_EXTENSIONS
CUSTOM_IGNORED_EXTENSIONS = IGNORED_EXTENSIONS.copy()
CUSTOM_IGNORED_EXTENSIONS.remove('pdf')

class PDFParser(scrapy.Spider):
    name = 'stadt_koeln_amtsblatt'

    # URL of the pdf file
    start_urls = ['https://www.stadt-koeln.de/politik-und-verwaltung/bekanntmachungen/amtsblatt/index.html']

    rules = (
        Rule(LinkExtractor(allow=r'.*\.pdf', deny_extensions=CUSTOM_IGNORED_EXTENSIONS), callback='parse', follow=True),
    )

    def parse(self, response):
        # selector of pdf file.
        for pdf in response.xpath("//a[contains(@href, 'pdf')]"):
            yield scrapy.Request(
                url=response.urljoin(pdf),
                callback=self.save_pdf
            )

    def save_pdf(self, response):
        path = response.url.split('/')[-1]
        self.logger.info('Saving PDF %s', path)
        with open(path, 'wb') as f:
            f.write(response.body)
</code>```

It seems there are two problems. The first one when extracting all the pdf links with xpath:

```<code>TypeError: Cannot mix str and non-str arguments
</code>```

and the second problem is about handling the pdf file itself. I just want to store it locally in a specific folder or similar. It would be really great if someone has a working example for this kind of site.

答:
To download files you need to use the FilesPipeline. This requires that you enable it in ITEM_PIPELINES and then provide a field named file_urls in your yielded item. In the example below, I have created an extenstion of the FilesPipeline in order to retain the filename of the pdf as provided on the website. The files will be saved in a folder named downloaded_files in the current directory

Read more about the filespipeline from the docs

import scrapy
from scrapy.pipelines.files import FilesPipeline

class PdfPipeline(FilesPipeline):
    # to save with the name of the pdf from the website instead of hash
    def file_path(self, request, response=None, info=None):
        file_name = request.url.split('/')[-1]
        return file_name

class StadtKoelnAmtsblattSpider(scrapy.Spider):
    name = 'stadt_koeln_amtsblatt'
    start_urls = ['https://www.stadt-koeln.de/politik-und-verwaltung/bekanntmachungen/amtsblatt/index.html']

    custom_settings = {
        "ITEM_PIPELINES": {
            PdfPipeline: 100
        },
        "FILES_STORE": "downloaded_files"
    }

    def parse(self, response):
        links = response.xpath("//a[@class='download pdf pdf']/@href").getall()
        links = [response.urljoin(link) for link in links] # to make them absolute urls

        yield {
            "file_urls": links
        }
```

Title: How to use Scrapy to parse PDFs?

Body:
I would like to download all PDFs found on a site, e.g. https://www.stadt-koeln.de/politik-und-verwaltung/bekanntmachungen/amtsblatt/index.html. I also tried to use rules but I think it's not neccessary here.

This is my approach:

import scrapy
from scrapy.linkextractors import IGNORED_EXTENSIONS
CUSTOM_IGNORED_EXTENSIONS = IGNORED_EXTENSIONS.copy()
CUSTOM_IGNORED_EXTENSIONS.remove('pdf')

class PDFParser(scrapy.Spider):
    name = 'stadt_koeln_amtsblatt'

    # URL of the pdf file
    start_urls = ['https://www.stadt-koeln.de/politik-und-verwaltung/bekanntmachungen/amtsblatt/index.html']

    rules = (
        Rule(LinkExtractor(allow=r'.*\.pdf', deny_extensions=CUSTOM_IGNORED_EXTENSIONS), callback='parse', follow=True),
    )

    def parse(self, response):
        # selector of pdf file.
        for pdf in response.xpath("//a[contains(@href, 'pdf')]"):
            yield scrapy.Request(
                url=response.urljoin(pdf),
                callback=self.save_pdf
            )

    def save_pdf(self, response):
        path = response.url.split('/')[-1]
        self.logger.info('Saving PDF %s', path)
        with open(path, 'wb') as f:
            f.write(response.body)

It seems there are two problems. The first one when extracting all the pdf links with xpath:

TypeError: Cannot mix str and non-str arguments

and the second problem is about handling the pdf file itself. I just want to store it locally in a specific folder or similar. It would be really great if someone has a working example for this kind of site.


问:
Finding the number of subsets with sum equal to k
Can anyone explain me the dynamic algorithm, that finds number of subsets with sum equal to k.
I searched in Google, but cant find any simple explanation! Sorry for my English!
Here is the code:</p>

```<code>int numbers[MAX];

int GetmNumberOfSubsets()
    {
        int dp[MAX];
        dp[0] = 1;
        int currentSum = 0;
        for (int i = 0; i < numbers.length; i++)
        {
            currentSum += numbers[i];
            for (int j = min(sum, currentSum); j >= numbers[i]; j--)
                dp[j] += dp[j - numbers[i]];
        }

        return dp[sum];
    }
</code>```

答:
here is a solution using recursion ...
considering two cases
i) Including first element of an array.
ii) without first array element.</p>
```<code>`

def subSetsSumK(arr, v, k) :

    if (k == 0) :
        for value in v :
            print(value, end=" ")
        print()
        return

    if (len(arr)== 0):
        return
    si=0
    v1 = [] + v

    v1.append(arr[si])

    subSetsSumK(arr[1:], v1, k - arr[si])
    subSetsSumK(arr[1:], v, k)

def subSetsSumK(arr, k):

    v = []
    subSetsSumK(arr,v, k)

# Driver code

arr = [ 2,1,3,2 ]
k_sum = 4
subSetsSumK(arr,k)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can anyone explain me the dynamic algorithm, that finds number of subsets with sum equal to k.
I searched in Google, but cant find any simple explanation! Sorry for my English!
Here is the code:

int numbers[MAX];

int GetmNumberOfSubsets()
    {
        int dp[MAX];
        dp[0] = 1;
        int currentSum = 0;
        for (int i = 0; i < numbers.length; i++)
        {
            currentSum += numbers[i];
            for (int j = min(sum, currentSum); j >= numbers[i]; j--)
                dp[j] += dp[j - numbers[i]];
        }

        return dp[sum];
    }

Body:
here is a solution using recursion ...
considering two cases
i) Including first element of an array.
ii) without first array element.

`

def subSetsSumK(arr, v, k) :

    if (k == 0) :
        for value in v :
            print(value, end=" ")
        print()
        return

    if (len(arr)== 0):
        return
    si=0
    v1 = [] + v

    v1.append(arr[si])

    subSetsSumK(arr[1:], v1, k - arr[si])
    subSetsSumK(arr[1:], v, k)

def subSetsSumK(arr, k):

    v = []
    subSetsSumK(arr,v, k)

# Driver code

arr = [ 2,1,3,2 ]
k_sum = 4
subSetsSumK(arr,k)


问:
join same table with multiple columns and get the latest record with user data
i have two tables named users and message, I want to join both tables and get the last message from each user's conversation with user name.

I want last message by timestamp between two users whether it is from_id or to_id, and similarly, want last message from every user from which I had any conversation.

messages table having columns from_id, to_id, messages.

Below is my code.

```<code>$chats = DB::table('users')
    ->leftJoin('messages', function($query)
    {
        $query->on('users.id', '=', 'messages.to_id')
        ->whereRaw('messages.id IN (select MAX(messages.id) from messages join users on users.id = messages.to_id  group by users.id)');
    })
    ->select('users.id as user_id', 'users.name', DB::raw('CONCAT("https://www.interwebs.co.in/puzzle/attach/", users.avatar) AS image') , 'users.mobile', 'messages.id', 'messages.from_id', 'messages.to_id', 'messages.body as message', 'messages.attachment', 'messages.seen as seen_count', 'messages.created_at')
    ->where('messages.from_id', $request->user_id)
    ->get();

</code>```

My messages table is

```<code>| from_id  | to_id     | message  | created_at          |
| ---------| --------- | ---------| ------------------  |
| 1        | 2         | abc      | 2022-02-04 10:55:34 |
| 2        | 1         | cdef     | 2022-02-05 10:56:34 |
| 1        | 3         | defg     | 2022-02-06 10:57:34 |
| 1        | 3         | hijk     | 2022-02-07 10:58:34 |
| 1        | 2         | lmop     | 2022-02-08 10:59:34 |

</code>```

I have tried this but it is giving me the last message of each conversation of current logged in user and not others.

答:
I got the expected output with the below code.
I know there is some improvement in my code, but it is functional for now.</p>
```<code>$user_id = $request->user_id;
$user_name = DB::table('users')->where('id', $user_id)->value('name');

$chats =DB::table('messages')
                    ->leftJoin('users as u1', 'messages.from_id', '=', 'u1.id')
                    ->leftJoin('users as u2', 'messages.to_id', '=', 'u2.id')
                    ->select('u1.id as user_id', 'u1.name', 'u2.name as name2', 'messages.id','messages.from_id',
                    'messages.to_id', 'messages.body as message', 'messages.attachment', 'messages.created_at')
                    ->where('messages.from_id', $user_id)
                    ->orWhere('messages.to_id', $user_id)
                    ->latest()
                    ->get();

foreach($chats as $chat)
        {
            $chat->user_id = $chat->from_id == $user_id ? $chat->to_id : $chat->from_id;
            $chat->name = $chat->name == $user_name ? $chat->name2 : $chat->name;
        }
        $chats = $chats->unique('user_id');

</code>```

Body:
i have two tables named users and message, I want to join both tables and get the last message from each user's conversation with user name.

I want last message by timestamp between two users whether it is from_id or to_id, and similarly, want last message from every user from which I had any conversation.

messages table having columns from_id, to_id, messages.

Below is my code.

$chats = DB::table('users')
    ->leftJoin('messages', function($query)
    {
        $query->on('users.id', '=', 'messages.to_id')
        ->whereRaw('messages.id IN (select MAX(messages.id) from messages join users on users.id = messages.to_id  group by users.id)');
    })
    ->select('users.id as user_id', 'users.name', DB::raw('CONCAT("https://www.interwebs.co.in/puzzle/attach/", users.avatar) AS image') , 'users.mobile', 'messages.id', 'messages.from_id', 'messages.to_id', 'messages.body as message', 'messages.attachment', 'messages.seen as seen_count', 'messages.created_at')
    ->where('messages.from_id', $request->user_id)
    ->get();

My messages table is

| from_id  | to_id     | message  | created_at          |
| ---------| --------- | ---------| ------------------  |
| 1        | 2         | abc      | 2022-02-04 10:55:34 |
| 2        | 1         | cdef     | 2022-02-05 10:56:34 |
| 1        | 3         | defg     | 2022-02-06 10:57:34 |
| 1        | 3         | hijk     | 2022-02-07 10:58:34 |
| 1        | 2         | lmop     | 2022-02-08 10:59:34 |

I have tried this but it is giving me the last message of each conversation of current logged in user and not others.

Body:
I got the expected output with the below code.
I know there is some improvement in my code, but it is functional for now.

$user_id = $request->user_id;
$user_name = DB::table('users')->where('id', $user_id)->value('name');

$chats =DB::table('messages')
                    ->leftJoin('users as u1', 'messages.from_id', '=', 'u1.id')
                    ->leftJoin('users as u2', 'messages.to_id', '=', 'u2.id')
                    ->select('u1.id as user_id', 'u1.name', 'u2.name as name2', 'messages.id','messages.from_id',
                    'messages.to_id', 'messages.body as message', 'messages.attachment', 'messages.created_at')
                    ->where('messages.from_id', $user_id)
                    ->orWhere('messages.to_id', $user_id)
                    ->latest()
                    ->get();

foreach($chats as $chat)
        {
            $chat->user_id = $chat->from_id == $user_id ? $chat->to_id : $chat->from_id;
            $chat->name = $chat->name == $user_name ? $chat->name2 : $chat->name;
        }
        $chats = $chats->unique('user_id');


问:
VBA inconsistency in find method when working on dates
I've been trying to find a date in a range, but for some reason the find method just doesnt work sometimes.

The dates in the range are formatted as such, each in two merged cells and in format "mmm-yy", in Spanish.
They are a mix of just values and formulas, they're values up until april 21 (they all are the first of the month), and from may-21 onwards they all use =EOMONTH with the previous cell.
This is a problem from a larger code (I don't generate the dates, I just want to find one), but the specific part that I'm interested is this:

```<code> Sub tset()

    Dim cell As Range
    Set cell = Selection.Find("ene-22", _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            MatchCase:=False)
    cell.Select
 end sub
</code>```

I know is not the best practices to use selection, but I'm just using it to try to figure out why is this not working.
Now, the problem is this works sometimes, and sometimes it doesn't, it's not consistent at all: in the year 2021 ene (january),  abr (april), ago (august), set (september), dic (december) and january again, from this year are all dates that DO NOT work, but all of the rest work just fine and as intended. This doesn't make any sense since it's not like only the formulated ones don't work.
To see if the code was at fault, I used the same code to find dates in a column of non merged cells with the same format and both values and formulas, and it worked.
I tried to replicate the range of dates (the merged ones) in a new workbook and it shows the exact same inconsistencies. I used find manually and it is able to find every single date.
More over, I tried recording a macro to do this, since I was able to use find manually and it was successfully recorded, but when I tried to run the recorded macro it doesn't work (
Object variable or With block variable not set, which is the error I'm always getting in these dates). So far I'm out of ideas, I would really appreciate all the help, thank you.

答:
Find a Date in a Row

I've written a function to find the date since the Find method gave me grief.

The key features are that you need to use the day, too, i.e. 1-ene-22, and that it uses Application.Match with CLng and CDate which works even if the cells are merged.

If there is a match, the function will return a reference to the cell (range). If not, it will return Nothing so, in your procedure, you need to test for Nothing the same way you should do it when using the Find method.

Option Explicit

Sub FindDateInRowTEST()

    Const wsName As String = "Sheet1"
    Const FirstDateCellAddress As String = "A1"
    Const DateString As String = "1-ene-22"

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)

    Dim dCell As Range
    Set dCell = FindDateInRow(ws.Range(FirstDateCellAddress), DateString)

    If Not dCell Is Nothing Then
        MsgBox "Found the date in cell '" & dCell.Address(0, 0) & "'.", _
            vbInformation
    Else
        MsgBox "Could not find the date.", vbCritical
    End If

End Sub

Function FindDateInRow( _
    ByVal FirstCell As Range, _
    ByVal DateString As String) _
As Range
    Const ProcName As String = "FindDateInRow"
    On Error GoTo ClearError

    Dim rrg As Range
    With FirstCell.Cells(1)
        Dim lCol As Long
        With .Worksheet.UsedRange
            lCol = .Columns(.Columns.Count).Column
        End With
        If lCol < .Column Then Exit Function ' too few columns
        Set rrg = .Resize(, lCol - .Column + 1)
    End With

    Dim cIndex As Variant
    cIndex = Application.Match(CLng(CDate(DateString)), rrg, 0)
    If IsError(cIndex) Then Exit Function ' date not found

    Set FindDateInRow = rrg.Cells(cIndex)

ProcExit:
    Exit Function
ClearError:
    Debug.Print "'" & ProcName & "' Run-time error '" _
        & Err.Number & "':" & vbLf & "    " & Err.Description
    Resume ProcExit
End Function
```

Body:
I've been trying to find a date in a range, but for some reason the find method just doesnt work sometimes.

The dates in the range are formatted as such, each in two merged cells and in format "mmm-yy", in Spanish.
They are a mix of just values and formulas, they're values up until april 21 (they all are the first of the month), and from may-21 onwards they all use =EOMONTH with the previous cell.
This is a problem from a larger code (I don't generate the dates, I just want to find one), but the specific part that I'm interested is this:

 Sub tset()

    Dim cell As Range
    Set cell = Selection.Find("ene-22", _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            MatchCase:=False)
    cell.Select
 end sub

I know is not the best practices to use selection, but I'm just using it to try to figure out why is this not working.
Now, the problem is this works sometimes, and sometimes it doesn't, it's not consistent at all: in the year 2021 ene (january),  abr (april), ago (august), set (september), dic (december) and january again, from this year are all dates that DO NOT work, but all of the rest work just fine and as intended. This doesn't make any sense since it's not like only the formulated ones don't work.
To see if the code was at fault, I used the same code to find dates in a column of non merged cells with the same format and both values and formulas, and it worked.
I tried to replicate the range of dates (the merged ones) in a new workbook and it shows the exact same inconsistencies. I used find manually and it is able to find every single date.
More over, I tried recording a macro to do this, since I was able to use find manually and it was successfully recorded, but when I tried to run the recorded macro it doesn't work (
Object variable or With block variable not set, which is the error I'm always getting in these dates). So far I'm out of ideas, I would really appreciate all the help, thank you.


问:
typescript compiler api - How to detect if property type is enum or object
I have to know each property declaration node, if is enum or another object.

so i get the type reference :

```<code> const typeReferance = (arrayType as any).typeName
</code>```

But i don't have any idea how to detect if is enum, or object.

Models:

```<code>enum Color { Red, Green, Blue }
class SomeObject {
    string: string;
}
class Model {
    color:Color;
}
</code>```

The visitor:

```<code>if (node.kind === ts.SyntaxKind.PropertyDeclaration) {
  ???
}
</code>```

答:
I have tried the "kind" attribute with success eg</p>
```<code>`   function visit(node: ts.Node) {
        if (!domain) {
            return;
        }

        if (node.kind === ts.SyntaxKind.ClassDeclaration) {
            //  console.log("Interface ignore");
            domain.isClass = true;
        }
        if (node.kind === ts.SyntaxKind.EnumDeclaration) {
            //  console.log("Interface ignore");
            domain.isEnum = true;
        }

        if (node.kind === ts.SyntaxKind.InterfaceDeclaration) {
            //  console.log("Interface ignore");
            domain.isInterface = true;
            return;
        }
        if (node.kind === ts.SyntaxKind.ImportDeclaration) {
            //console.log("Import Ignore");
            //output = null;
            return;
        }
        if (node.kind === ts.SyntaxKind.DefaultKeyword) {
            //console.log("DEFAULT");
            return;
        }
        if (node.kind === ts.SyntaxKind.ExportKeyword) {
            exportStatementFound = true;
            //console.log("EXPORT");
            return;
        }

        if (ts.isClassDeclaration(node) && node.name) {
           //do something
        }
  }`
</code>```

Body:
I have to know each property declaration node, if is enum or another object.

so i get the type reference :

 const typeReferance = (arrayType as any).typeName

But i don't have any idea how to detect if is enum, or object.

Models:

enum Color { Red, Green, Blue }
class SomeObject {
    string: string;
}
class Model {
    color:Color;
}

The visitor:

if (node.kind === ts.SyntaxKind.PropertyDeclaration) {
  ???
}

Body:
I have tried the "kind" attribute with success eg

`   function visit(node: ts.Node) {
        if (!domain) {
            return;
        }

        if (node.kind === ts.SyntaxKind.ClassDeclaration) {
            //  console.log("Interface ignore");
            domain.isClass = true;
        }
        if (node.kind === ts.SyntaxKind.EnumDeclaration) {
            //  console.log("Interface ignore");
            domain.isEnum = true;
        }

        if (node.kind === ts.SyntaxKind.InterfaceDeclaration) {
            //  console.log("Interface ignore");
            domain.isInterface = true;
            return;
        }
        if (node.kind === ts.SyntaxKind.ImportDeclaration) {
            //console.log("Import Ignore");
            //output = null;
            return;
        }
        if (node.kind === ts.SyntaxKind.DefaultKeyword) {
            //console.log("DEFAULT");
            return;
        }
        if (node.kind === ts.SyntaxKind.ExportKeyword) {
            exportStatementFound = true;
            //console.log("EXPORT");
            return;
        }

        if (ts.isClassDeclaration(node) && node.name) {
           //do something
        }
  }`


问:
Question when I inport .ova file into google cloud to create an instance of VM
When I try to import .ova file, there is following error.

The problem is:

```<code>[import-ovf] 2020/08/19 13:02:35 step "import-boot-disk" run error: step "wait-for-signal" run error: WaitForInstancesSignal FailureMatch found for "inst-importer-import-ovf-import-boot-disk-3qlqg": "ImportFailed: Failed to resize disk. The Compute Engine default service account needs the role: roles/compute.storageAdmin'"
ERROR
ERROR: build step 0 "gcr.io/compute-image-tools/gce_ovf_import:release" failed: step exited with non-zero status: 1
ERROR: (gcloud.compute.instances.import) build 0683583e-5157-4d13-972b-b5e3f5f75f2b completed with status "FAILURE"
"
The command I am using to implement is: gcloud compute instances import eve --os=ubuntu-1604 --source-uri=gs://evenamespace/EVE.ova --zone=northamerica-northeast1-a --custom-memory=25GB --custom-cpu=4.
</code>```

I already add an role in Compute Engine default service account, that is Compute Storage Admin like the picture

答:
Using this command without the / at the end of the ova file name I got it to work:

```<code>$ gcloud beta compute machine-images import <my-machine-image> --source-uri=gs://my-virtual-appliances-bucket/my-va-file.ova --os=ubuntu-1804
</code>```

Let me know if this helps anyone trying to attempt this, check out this link as well.

Body:
When I try to import .ova file, there is following error.

The problem is:

[import-ovf] 2020/08/19 13:02:35 step "import-boot-disk" run error: step "wait-for-signal" run error: WaitForInstancesSignal FailureMatch found for "inst-importer-import-ovf-import-boot-disk-3qlqg": "ImportFailed: Failed to resize disk. The Compute Engine default service account needs the role: roles/compute.storageAdmin'"
ERROR
ERROR: build step 0 "gcr.io/compute-image-tools/gce_ovf_import:release" failed: step exited with non-zero status: 1
ERROR: (gcloud.compute.instances.import) build 0683583e-5157-4d13-972b-b5e3f5f75f2b completed with status "FAILURE"
"
The command I am using to implement is: gcloud compute instances import eve --os=ubuntu-1604 --source-uri=gs://evenamespace/EVE.ova --zone=northamerica-northeast1-a --custom-memory=25GB --custom-cpu=4.

I already add an role in Compute Engine default service account, that is Compute Storage Admin like the picture

Body:
Using this command without the / at the end of the ova file name I got it to work:

$ gcloud beta compute machine-images import <my-machine-image> --source-uri=gs://my-virtual-appliances-bucket/my-va-file.ova --os=ubuntu-1804

Let me know if this helps anyone trying to attempt this, check out this link as well.


问:
Is there a way to automatically add a code in a newly created worksheet?
I want see if there is a way to track changes in a newly created tab only. Below are two sets of code that I've come up with in my research. For reference, "Overview" is where I put all the inputs that the newly created tab will have and "Variance Template" is the template I copy for the newly created tab. Now, when I create a new tab using the macro, I also need the tracking code to be copied within that new tab. Does anyone know if this is possible?

Create a new tab code:

```<code>Sub AddNewTab()

'Assign Overview tab to be read as "ws"
Dim ws As Worksheet
Set ws = Worksheets("Overview")

'Assign newly created tab as "newWs" and rename it to cell D6 in Overview tab
Dim newWs As Worksheet
Set newWs = Sheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
newWs.Name = ws.Range("D6").Value

'Copy data from other, already created, comparison tab into new tab
Worksheets("Variance Template").Range("A1:A59").EntireRow.Copy
newWs.Range("A1").PasteSpecial
Worksheets("Variance Template").Range("A1:BJ59").Copy
newWs.Range("A1").PasteSpecial xlPasteColumnWidths

'Copy comparison name/month/year, last closed month/year, and service type
ws.Range("D6").Copy
newWs.Range("F2").PasteSpecial Paste:=xlPasteValues
ws.Range("Q8").Copy
newWs.Range("L2").PasteSpecial Paste:=xlPasteValues
ws.Range("Q12").Copy
newWs.Range("P2").PasteSpecial Paste:=xlPasteValues

'Hide gridlines in newly created tab
newWs.Activate
ActiveWindow.DisplayGridlines = False

'First disables any freezed panes, then freezes panes to row 9 & column 7
ActiveWindow.FreezePanes = False
Cells(9, 7).Select
ActiveWindow.FreezePanes = True

'Disables "ignore errors" notices
Application.ErrorCheckingOptions.BackgroundChecking = False

'Change zoom to 80%
ActiveWindow.Zoom = 80

'Change tab color to green
ActiveSheet.Tab.Color = RGB(146, 208, 80)

End Sub
</code>```

Tracking Code:

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:BJ200")) Is Nothing Then
        Application.EnableEvents = False
        With newWs
            .Range("F3").Value = "Last Updated: " & Environ("username") & " " & Format(Now, "MM/dd/yyyy h:mm:ss_ AM/PM")
        End With
    End If
    Application.EnableEvents = True
End Sub
</code>```

I need this code to copy over every time I create a new tab using the first set of code. I'm relatively new to VBA so let me know if you need any other type of information.

Thank you.

答:
This worked for me:

Sub AddNewTab()

    Dim ws As Worksheet, wb As Workbook
    Dim newWs As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Overview")

    ' Variance Template is a hidden sheet (first tab position)
    '    zoom, freeze panes etc are already set up on this sheet
    wb.Worksheets("Variance Template").Copy after:=wb.Worksheets(wb.Worksheets.Count)

    Set newWs = wb.Worksheets(wb.Worksheets.Count) 'get the copy
    With newWs
        .Visible = True
        .Name = ws.Range("D6").Value
        .Tab.Color = RGB(146, 208, 80)
        .Range("F2").Value = ws.Range("D6").Value
        .Range("L2").Value = ws.Range("Q8").Value
        .Range("P2").Value = ws.Range("Q12").Value
        .Activate
    End With
    Application.ErrorCheckingOptions.BackgroundChecking = False

End Sub
```

Body:
I want see if there is a way to track changes in a newly created tab only. Below are two sets of code that I've come up with in my research. For reference, "Overview" is where I put all the inputs that the newly created tab will have and "Variance Template" is the template I copy for the newly created tab. Now, when I create a new tab using the macro, I also need the tracking code to be copied within that new tab. Does anyone know if this is possible?

Create a new tab code:

Sub AddNewTab()

'Assign Overview tab to be read as "ws"
Dim ws As Worksheet
Set ws = Worksheets("Overview")

'Assign newly created tab as "newWs" and rename it to cell D6 in Overview tab
Dim newWs As Worksheet
Set newWs = Sheets.Add(After:=ActiveWorkbook.Worksheets(ActiveWorkbook.Worksheets.Count))
newWs.Name = ws.Range("D6").Value

'Copy data from other, already created, comparison tab into new tab
Worksheets("Variance Template").Range("A1:A59").EntireRow.Copy
newWs.Range("A1").PasteSpecial
Worksheets("Variance Template").Range("A1:BJ59").Copy
newWs.Range("A1").PasteSpecial xlPasteColumnWidths

'Copy comparison name/month/year, last closed month/year, and service type
ws.Range("D6").Copy
newWs.Range("F2").PasteSpecial Paste:=xlPasteValues
ws.Range("Q8").Copy
newWs.Range("L2").PasteSpecial Paste:=xlPasteValues
ws.Range("Q12").Copy
newWs.Range("P2").PasteSpecial Paste:=xlPasteValues

'Hide gridlines in newly created tab
newWs.Activate
ActiveWindow.DisplayGridlines = False

'First disables any freezed panes, then freezes panes to row 9 & column 7
ActiveWindow.FreezePanes = False
Cells(9, 7).Select
ActiveWindow.FreezePanes = True

'Disables "ignore errors" notices
Application.ErrorCheckingOptions.BackgroundChecking = False

'Change zoom to 80%
ActiveWindow.Zoom = 80

'Change tab color to green
ActiveSheet.Tab.Color = RGB(146, 208, 80)

End Sub

Tracking Code:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:BJ200")) Is Nothing Then
        Application.EnableEvents = False
        With newWs
            .Range("F3").Value = "Last Updated: " & Environ("username") & " " & Format(Now, "MM/dd/yyyy h:mm:ss_ AM/PM")
        End With
    End If
    Application.EnableEvents = True
End Sub

I need this code to copy over every time I create a new tab using the first set of code. I'm relatively new to VBA so let me know if you need any other type of information.

Thank you.


问:
Remove specific states on WooCommerce checkout BUT only in the shipping form
I have this code which remove some States from the Billing and Shipping form in the checkout page. It works fine.

I need to remove the State but JUST in the "shipping form". Then the removed 'states' should be shown in the 'billing form'

I guess I need to use another hook than 'woocommerce_states'. But no sure which one.

function remove_my_states ($states) {
   unset ($states ['ES'] ['TF']);// tenerife
   unset ($states ['ES'] ['GC']);// gran canaria
   unset ($states ['ES'] ['CE']);// ceuta
   unset ($states ['ES'] ['ML']); // melilla
   unset ($states ['ES'] ['PM']); // baleares
   return $states;
   }

add_filter ('woocommerce_states', 'remove_my_states');
```

答:
Your question is not that obvious because with the current hook you are using you cannot distinguish between the fields. What you can do as a workaround is use the woocommerce_form_field_$args['type'] filter hook.

The callback function uses $field which contains all HTML from
 to the closing
 HTML tag, so we have the ability to rewrite the entire output of this through our function.

So you get:

function filter_woocommerce_form_field_state( $field, $key, $args, $value ) {
    // Checkout page only
    if ( ! is_checkout() ) return $field;

    // Only for shipping
    if ( $key == 'shipping_state' ) {
        // Replace all occurrences of the search string with the replacement string
        $field = str_replace( '<option value="CE" >Ceuta</option>', '', $field );
        $field = str_replace( '<option value="ML" >Melilla</option>', '', $field );
        $field = str_replace( '<option value="PM" >Baleares</option>', '', $field );
        // Etc..
    }

    // Do something
    return $field;
}
add_filter( 'woocommerce_form_field_state', 'filter_woocommerce_form_field_state', 10, 4 );
```

Might come in handy: /woocommerce/i18n/states.php

More info: How should I change the woocommerce_form_field HTML Structure?

Body:
Your question is not that obvious because with the current hook you are using you cannot distinguish between the fields. What you can do as a workaround is use the woocommerce_form_field_$args['type'] filter hook.

The callback function uses $field which contains all HTML from <p> to the closing </p> HTML tag, so we have the ability to rewrite the entire output of this through our function.

So you get:

function filter_woocommerce_form_field_state( $field, $key, $args, $value ) {
    // Checkout page only
    if ( ! is_checkout() ) return $field;

    // Only for shipping
    if ( $key == 'shipping_state' ) {
        // Replace all occurrences of the search string with the replacement string
        $field = str_replace( '<option value="CE" >Ceuta</option>', '', $field );
        $field = str_replace( '<option value="ML" >Melilla</option>', '', $field );
        $field = str_replace( '<option value="PM" >Baleares</option>', '', $field );
        // Etc..
    }

    // Do something
    return $field;
}
add_filter( 'woocommerce_form_field_state', 'filter_woocommerce_form_field_state', 10, 4 );

Might come in handy: /woocommerce/i18n/states.php

More info: How should I change the woocommerce_form_field HTML Structure?


问:
Creating column dynamically by checking conditions in python pandas
I have a dataset like below:

Which needs to be checked against the below master dataset:

Here, the condition is to check the associated value for the Group and its value from the dataset with the master dataset and pick the S2SFlag column value from the master dataset and create an S2SFlag column in the dataset. The original dataset is returned by querying the database using AWS Lambda.

Also, if post-checking if there is a 'No' value for any of the Group attributes then the Flag for that particular group would be 'No'. The expected output is as below:

As it can be seen that for the first record in the expected output, S2SFlag for each of the group attributes is Yes so the S2SFlag for the first record is 'Yes' and in the second case it is No because one of the values of Age has No as its S2SFlag.

Attempt so far:

```<code>df1 = pd.read_csv('/home/siddhesh/Documents/data.csv')

df2 = pd.read_csv('/home/siddhesh/Documents/data1.csv')  # Assuming it as query results

age = df2['Age']
Channel = df2['Channel']
Status = df2['Status']

df3 = df1[(df1['Attributes'] = str(age))]

if (age == df3.iloc[0]):
    getS2s = df1['S2SFlag']
    if (getS2s == 'No'):
        df1['S2SFlag'] = 'No'
</code>```

It gives me the below error:

```<code>Traceback (most recent call last):
  File "/home/siddhesh/Downloads/pyspark/src/sample/test.py", line 16, in <module>
    if (age == df3.iloc[0]):
  File "/home/siddhesh/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 931, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "/home/siddhesh/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 1566, in _getitem_axis
    self._validate_integer(key, axis)
  File "/home/siddhesh/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 1500, in _validate_integer
    raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds
</code>```

答:
We can first create mappings for each group:

```<code>mapping_Age = df1[df1['Group'] == 'Age'].set_index('Attributes')['S2SFlag'] == 'Yes'
</code>```

In the above line, we filter to keep only Age rows and use their attributes values as the key of this mapping, but instead of using the S2SFlag as the value of this mapping, I changed them from Yes to True and from No to False as it's more program-friendly to process boolean values. We will change them back to Yes/No later. Note that we need to make sure the same Attributes value does not appear twice in any mapping. Otherwise it will report errors in later step. Similarly

```<code>mapping_Channel = df1[df1['Group'] == 'Channel'].set_index('Attributes')['S2SFlag'] == 'Yes'

mapping_Status = df1[df1['Group'] == 'Status'].set_index('Attributes')['S2SFlag'] == 'Yes'
</code>```

We can then apply the mappings to our data like the following

```<code>mapped_Age = df2['Age'].astype(str).map(mapping_Age)
mapped_Channel = df2['Channel'].map(mapping_Channel)
mapped_Status = df2['Status'].map(mapping_Status)
</code>```

Note that if map cannot find a mapping from (e.g.) mapping_Age for a particular value in df2['Age'], it will return a np.nan instead of a True/False, you need to define how to handle this case by appending .fillna(True) or .fillna(False) at the end of each of them.

Lastly, your final S2SFlag is Yes (or True) only if all are Yess, so

```<code>df2['S2SFlag'] = (mapped_Age & mapped_Status & mapped_Channel).map({True: 'Yes', False: 'No'})
</code>```

Body:
I have a dataset like below:

Which needs to be checked against the below master dataset:

Here, the condition is to check the associated value for the Group and its value from the dataset with the master dataset and pick the S2SFlag column value from the master dataset and create an S2SFlag column in the dataset. The original dataset is returned by querying the database using AWS Lambda.

Also, if post-checking if there is a 'No' value for any of the Group attributes then the Flag for that particular group would be 'No'. The expected output is as below:

As it can be seen that for the first record in the expected output, S2SFlag for each of the group attributes is Yes so the S2SFlag for the first record is 'Yes' and in the second case it is No because one of the values of Age has No as its S2SFlag.

Attempt so far:

df1 = pd.read_csv('/home/siddhesh/Documents/data.csv')

df2 = pd.read_csv('/home/siddhesh/Documents/data1.csv')  # Assuming it as query results

age = df2['Age']
Channel = df2['Channel']
Status = df2['Status']

df3 = df1[(df1['Attributes'] = str(age))]

if (age == df3.iloc[0]):
    getS2s = df1['S2SFlag']
    if (getS2s == 'No'):
        df1['S2SFlag'] = 'No'

It gives me the below error:

Traceback (most recent call last):
  File "/home/siddhesh/Downloads/pyspark/src/sample/test.py", line 16, in <module>
    if (age == df3.iloc[0]):
  File "/home/siddhesh/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 931, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "/home/siddhesh/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 1566, in _getitem_axis
    self._validate_integer(key, axis)
  File "/home/siddhesh/.local/lib/python3.8/site-packages/pandas/core/indexing.py", line 1500, in _validate_integer
    raise IndexError("single positional indexer is out-of-bounds")
IndexError: single positional indexer is out-of-bounds

Body:
We can first create mappings for each group:

mapping_Age = df1[df1['Group'] == 'Age'].set_index('Attributes')['S2SFlag'] == 'Yes'

In the above line, we filter to keep only Age rows and use their attributes values as the key of this mapping, but instead of using the S2SFlag as the value of this mapping, I changed them from Yes to True and from No to False as it's more program-friendly to process boolean values. We will change them back to Yes/No later. Note that we need to make sure the same Attributes value does not appear twice in any mapping. Otherwise it will report errors in later step. Similarly

mapping_Channel = df1[df1['Group'] == 'Channel'].set_index('Attributes')['S2SFlag'] == 'Yes'

mapping_Status = df1[df1['Group'] == 'Status'].set_index('Attributes')['S2SFlag'] == 'Yes'

We can then apply the mappings to our data like the following

mapped_Age = df2['Age'].astype(str).map(mapping_Age)
mapped_Channel = df2['Channel'].map(mapping_Channel)
mapped_Status = df2['Status'].map(mapping_Status)

Note that if map cannot find a mapping from (e.g.) mapping_Age for a particular value in df2['Age'], it will return a np.nan instead of a True/False, you need to define how to handle this case by appending .fillna(True) or .fillna(False) at the end of each of them.

Lastly, your final S2SFlag is Yes (or True) only if all are Yess, so

df2['S2SFlag'] = (mapped_Age & mapped_Status & mapped_Channel).map({True: 'Yes', False: 'No'})


问:
Using guid in sqlite select where guid is stored in the sqlite db as binaries
I have a table Employee in the SQLite database. Whose primary key is "ID" of GUID type. I try to find the record with id = guid 'a8828ddf-ef22-4d36-935a-1c66ae86ebb3' with the following query with no luck:

```<code>SELECT * FROM Employee
WHERE Employee.Id = 'a8828ddf-ef22-4d36-935a-1c66ae86ebb3'
</code>```

Can anyone tell me how should I write the query?

Thanks,

答:
Sqlite can also be configured to store GUIDs as text. This is done in the connection string.

Data Source=c:\mydb.db;Version=3;BinaryGUID=False;

See https://www.connectionstrings.com/sqlite/

Body:
I have a table Employee in the SQLite database. Whose primary key is "ID" of GUID type. I try to find the record with id = guid 'a8828ddf-ef22-4d36-935a-1c66ae86ebb3' with the following query with no luck:

SELECT * FROM Employee
WHERE Employee.Id = 'a8828ddf-ef22-4d36-935a-1c66ae86ebb3'

Can anyone tell me how should I write the query?

Thanks,


问:
Is it guaranteed that only one callback is executed when the wait condition is true?
This is regarding the statement WAIT FOR ASYNCHRONOUS TASKS and the corresponding part of the documentation:

If the result of log_exp is false and there is an asynchronous function call with callback routine, the program waits until a callback routine of a previous function (called asynchronously) has been executed and then checks the logical expression again:

Let's say I spawn 4 tasks, each reducing availability attribute by one, reaching 0. In the callback, they increase the availability attribute by one.

Now when I reach WAIT FOR ASYNCHRONOUS TASKS UNTIL availability > 0 UP TO 6000 SECONDS. the program waits until the counter is increased by a callback.

Question: When the logical expression is checked again, is it guaranteed that the order is

callback->check->callback->check?

Or could it be that availability is e.g. already 3, since it did

callback->callback->callback->check?

答:
It works as per documentation.

WAIT ->  CALLBACK -> CHECK , WAIT -> CALLBACK -> CHECK,

until wait condition is true or no more outstanding Callbacks are open.

It is important that the Callback form/method has finished before the check is performed as that routine is responsible for changing the variable/s in the WAIT UNTIL Condition.

An extract from the docu.

If the result of log_exp is false and there is an asynchronous
function call with callback routine, the program waits until a
callback routine of a previous function (called asynchronously) has
been executed and then checks the logical expression again:

If you are concerned about 2 callbacks occurring concurrently,
the callbacks are handled by the kernel  sequentially.
There is no guarantee of order, just that the call backs are processed sequentially.  Note the waiting program is only executed in 1 Work process at a time. From my tests, it is always the same Work process.


问:
Pass variables to Function()
I wish to use the Function javascript feature instead of "eval", for implementing the ability to use comparison operators inside a filtering input field.

```<code>function test(){
 let x = 5, y = 10, operator = '>';
 return Function("return x" + operator + "y")(x, y);
}

console.log(test());
</code>```

The code above throws an error, x, y appear undefined in the Function.

So how can I pass external variables to Function?

答:
Each parameter referenced in the function body should be a leading argument to the function, in string format.

function test(){
 let x = 5, y = 10;
 return Function('x', 'y', "return x>y")(x, y);
}

console.log(test());```

Title: Pass variables to Function()

Body:
I wish to use the Function javascript feature instead of "eval", for implementing the ability to use comparison operators inside a filtering input field.

function test(){
 let x = 5, y = 10, operator = '>';
 return Function("return x" + operator + "y")(x, y);
}

console.log(test());

The code above throws an error, x, y appear undefined in the Function.

So how can I pass external variables to Function?


问:
How to return string/int from dbcontext
I want to get role_code from db.roles based on role_id and then return role_code as the result.

I have tried this

public static string GetRoleCode (int role_id)
{
    string result = "";
    using (var db =new DbContext())
    {
        result = db.roles
            .Where(r => r.Id == role_id)
            .Select(r => new
            {

            }).FirstOrDefault();
    }
    return result;
}
```

What's missing from my code?

答:
Since your result is a string, you can't return with anonymous type in .Select().

You should just return the role code as:

.Select(r => r.Code) // Assume this field you need to return
```
<pre class="lang-cs prettyprint-override"><code>result = db.roles
    .Where(r => r.Id == role_id)
    .Select(r => r.Code)
    .FirstOrDefault();
</code>```

Or

If you use C# 6 or above, you can use Null conditional operator as below:

result = db.roles
    .FirstOrDefault(r => r.Role_Id == role_id)?
    .Code;
```

Title: How to return string/int from dbcontext

Body:
I want to get role_code from db.roles based on role_id and then return role_code as the result.

I have tried this

public static string GetRoleCode (int role_id)
{
    string result = "";
    using (var db =new DbContext())
    {
        result = db.roles
            .Where(r => r.Id == role_id)
            .Select(r => new
            {

            }).FirstOrDefault();
    }
    return result;
}

What's missing from my code?

Body:
Since your result is a string, you can't return with anonymous type in .Select().

You should just return the role code as:

.Select(r => r.Code) // Assume this field you need to return

result = db.roles
    .Where(r => r.Id == role_id)
    .Select(r => r.Code)
    .FirstOrDefault();

Or

If you use C# 6 or above, you can use Null conditional operator as below:

result = db.roles
    .FirstOrDefault(r => r.Role_Id == role_id)?
    .Code;