问:
Why does this counter (class instance) work properly and doesn't re-initialize at every recursion occurrence? (Python 3.8)
I wanted to count the number of recursion occurrence my binary search would require to find the right item (100).
I implemented this Counter class, I thought that it wouldn't work but I gave it a try as an experiment.
I thought that I would re-set so to speak (or "overwrite") the previous instantiation, but it doesn't seem to be the case as the counter seem to work.

I have three questions here:

Is there a better way to implement a counter for this specific search case?

Why is the previous instantiation not overwritten at each recursion occurrence?

Am I using the right vocabulary when I say "recursion occurrence"?

```<code>from dataclasses import dataclass

@dataclass
class Counter:
    c = 0

def binary_search(container, item, left, right):

    count = Counter
    count.c +=1

    print("count: ", count.c)

    # first base case - search misses
    if right < left:
        return -1

    # generate the index of the middle item
    middle_index = (left + right) // 2

    # we have found the item
    if container[middle_index] == item:
        return middle_index

    # have to check whether the middle_item is smaller or greater
    # the item is in the left subèarray
    elif container[middle_index] > item:
        print('Checking items on the left. . .')
        # we can discard the right side of the array (items greater than the middle item)
        return binary_search(container, item, left, middle_index-1)

    elif container[middle_index] < item:
        print('Checking items on the right. . .')
        return binary_search(container, item, middle_index+1, right)

nums = [-5,-4,0,2,4,6,8,100,500]

print(binary_search(nums, 100,0 ,len(nums)-1))
</code>```

Result:

```<code>count:  1
Checking items on the right. . .
count:  2
Checking items on the right. . .
count:  3
7
</code>```

Thank you

答:
Regarding your question 2: You are not creating an instance of class Counter, but instead refer to the class itself:

```<code>count = Counter
count.c +=1
</code>```

This means, count.c is always the same variable.  If instead you write

```<code>count = Counter()
count.c +=1
</code>```

then count.c is always a 'fresh' variable.

Body:
I wanted to count the number of recursion occurrence my binary search would require to find the right item (100).
I implemented this Counter class, I thought that it wouldn't work but I gave it a try as an experiment.
I thought that I would re-set so to speak (or "overwrite") the previous instantiation, but it doesn't seem to be the case as the counter seem to work.

I have three questions here:

Is there a better way to implement a counter for this specific search case?

Why is the previous instantiation not overwritten at each recursion occurrence?

Am I using the right vocabulary when I say "recursion occurrence"?

from dataclasses import dataclass

@dataclass
class Counter:
    c = 0

def binary_search(container, item, left, right):

    count = Counter
    count.c +=1

    print("count: ", count.c)

    # first base case - search misses
    if right < left:
        return -1

    # generate the index of the middle item
    middle_index = (left + right) // 2

    # we have found the item
    if container[middle_index] == item:
        return middle_index

    # have to check whether the middle_item is smaller or greater
    # the item is in the left subèarray
    elif container[middle_index] > item:
        print('Checking items on the left. . .')
        # we can discard the right side of the array (items greater than the middle item)
        return binary_search(container, item, left, middle_index-1)

    elif container[middle_index] < item:
        print('Checking items on the right. . .')
        return binary_search(container, item, middle_index+1, right)

nums = [-5,-4,0,2,4,6,8,100,500]

print(binary_search(nums, 100,0 ,len(nums)-1))

Result:

count:  1
Checking items on the right. . .
count:  2
Checking items on the right. . .
count:  3
7

Thank you

Body:
Regarding your question 2: You are not creating an instance of class Counter, but instead refer to the class itself:

count = Counter
count.c +=1

This means, count.c is always the same variable.  If instead you write

count = Counter()
count.c +=1

then count.c is always a 'fresh' variable.


来源: stackexchange

问:
How do I use different date formats for serialization & deserialization?
I'm getting an object with the date field in the format 2022-02-11 which I'm mapping into an object as follows:

{ "dateTimeField": "2022-02-11" }
```
<pre class="lang-java prettyprint-override"><code>@Data
class MyPojo {
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date dateTimeField;
}
</code>```

Now I need to send this object as a json response, but I need it to be in a different format:

{ "dateTimeField": "2022-02-11 00:00:00" }

```
<p>If I change the <code>pattern</code> field, deserialization fails:</p>
<pre class="lang-java prettyprint-override"><code>@Data
class MyPojo {
    // com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2022-02-11": expected format "yyyy-MM-dd HH:mm:ss"
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date dateTimeField;
}
</code>```

How do I use different patterns for serialization & deserialization?

答:
This can be accomplished using separate annotations on the getter and setter of the field:

@Data
class MyPojo {

    private Date dateTimeField;

    // Used during serialization
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public Date getDateTimeField() {
        return dateTimeField;
    }

    // Used during deserialization
    @JsonFormat(pattern = "yyyy-MM-dd")
    public void setDateTimeField(Date dateTimeField) {
        this.dateTimeField = dateTimeField;
    }
}
```
<p>Alternatively, using Lombok's (experimental as of 11 Feb 2022) onX feature:</p>
<pre class="lang-java prettyprint-override"><code>@Data
class MyPojo {
    @Getter(onMethod_ = {@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")}) // Used during serialization
    @Setter(onMethod_ = {@JsonFormat(pattern = "yyyy-MM-dd")})          // Used during deserialization
    private Date dateTimeField;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm getting an object with the date field in the format 2022-02-11 which I'm mapping into an object as follows:

{ "dateTimeField": "2022-02-11" }

@Data
class MyPojo {
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date dateTimeField;
}

Now I need to send this object as a json response, but I need it to be in a different format:

{ "dateTimeField": "2022-02-11 00:00:00" }

If I change the pattern field, deserialization fails:

@Data
class MyPojo {
    // com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2022-02-11": expected format "yyyy-MM-dd HH:mm:ss"
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date dateTimeField;
}

How do I use different patterns for serialization & deserialization?

Body:
This can be accomplished using separate annotations on the getter and setter of the field:

@Data
class MyPojo {

    private Date dateTimeField;

    // Used during serialization
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public Date getDateTimeField() {
        return dateTimeField;
    }

    // Used during deserialization
    @JsonFormat(pattern = "yyyy-MM-dd")
    public void setDateTimeField(Date dateTimeField) {
        this.dateTimeField = dateTimeField;
    }
}

Alternatively, using Lombok's (experimental as of 11 Feb 2022) onX feature:

@Data
class MyPojo {
    @Getter(onMethod_ = {@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")}) // Used during serialization
    @Setter(onMethod_ = {@JsonFormat(pattern = "yyyy-MM-dd")})          // Used during deserialization
    private Date dateTimeField;
}


问:
What is "range" actually? Is it a function?
One of the preferred way to loop through arrays and slices is to use range like this

arr = []int{1, 2}

for index, item := range arr {
  continue
}
```

I know how range works, I've been using it multiple times. But I'm still not sure what it is behind the scene. Is it a function and a modification of range(arr)? The fact that it returns 2 variables make me think that way, but I need a confirmation.

What's the implementation behind it?

答: It's an iterator-pattern which the for-loop uses to get the next object from.</p>

Body:
One of the preferred way to loop through arrays and slices is to use range like this

arr = []int{1, 2}

for index, item := range arr {
  continue
}

I know how range works, I've been using it multiple times. But I'm still not sure what it is behind the scene. Is it a function and a modification of range(arr)? The fact that it returns 2 variables make me think that way, but I need a confirmation.

What's the implementation behind it?


问:
Silverstripe 4 show specific records in GridField
I created a module that will allow certain user groups to create a request in the CMS.Any logged in user can access the module.
When user visit 'RequestModeule' in in CMS section in GRID CMS FIELDS I want to show him the requests he only sent not another customer requests. The system displays the requirements of all users and he see all.

How do I set the CMS FIELDS results to be displayed for the currently logged in user.

This is a ecommerce site and some customers want to return the product, some want to replace the product, some want to complain about the quality. I want to allow customers to submit a request themselves. I started with a simple model, so I will expand it when I solve big problems.

Here is my Model.

```<code>class Request extends DataObject
{
    private static $db = [
        'FullName' => 'Varchar',
        'RequestText' => 'Text'
    ];

    private static $has_one = [
        'Photo' => Image::class
    ];

    public function canView($member = null)
    {
        return Permission::check('VIEW_REQUEST', 'any', $member);
    }

    public function canEdit($member = null)
    {
        return Permission::check('EDIT_REQUEST', 'any', $member);
    }

    public function canDelete($member = null)
    {
        return Permission::check('DELETE_REQUEST', 'any', $member);
    }

    public function canCreate($member = null, $context = [])
    {
        return Permission::check('CREATE_REQUEST', 'any', $member);
    }

    /**
     * @return \SilverStripe\Forms\FieldList
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();
        $fields->addFieldToTab('Root.Main', TextField::create('FullName'));
        $fields->addFieldToTab('Root.Main', TextField::create('RequestText'));
        $fields->addFieldToTab('Root.Photos', $img = UploadField::create('Photo', 'Main photo'));

        $img->setFolderName("products");
        $img->setAllowedExtensions(["png", "jpg", "jpeg", "gif", "webp"]);

        return $fields;
    }
}
</code>```

Request Controller

```<code>class Request_Controller extends ContentController implements PermissionProvider
{

    function providePermissions(){
        return array(
            "CREATE_REQUEST" => "Create REQUEST",
            "EDIT_REQUEST" => "Edit REQUEST",
            "VIEW_REQUEST" => "View REQUEST",
            "DELTE_REQUEST" => "Delete REQUEST",
        );
    }
</code>```

答:
First of all, I don't see anything about connecting your Request class with a Member. If you want to only show the things a member has created, you need to somehow store the Members ID or something.

The most obvious way to do this would be a private static $has_one = ['CreatedBy' => Member::class].

(and during creation you'll have to put the member ID into CreatedBy. For example you can do protected function onBeforeWrite() { parent::onBeforeWrite(); $this->CreatedByID = Security::getCurrentUser()->ID; })

As for the GridField:

There are 2 ways to control what is displayed in a GridField:

GridFields 3rd argument is any SS_List instance, so you can filter or customize that any way you want. For example you can use Request::get()->filter('CreatedByID' => 13) to only show the objects created by member ID 13.

You can use canView on each Request object. If it returns false, it will not be shown. So you can do public function canView($member = null) { return $member && $member->ID === $this->CreatedByID && Permission::check('VIEW_REQUEST', 'any', $member); }

Body:
I created a module that will allow certain user groups to create a request in the CMS.Any logged in user can access the module.
When user visit 'RequestModeule' in in CMS section in GRID CMS FIELDS I want to show him the requests he only sent not another customer requests. The system displays the requirements of all users and he see all.

How do I set the CMS FIELDS results to be displayed for the currently logged in user.

This is a ecommerce site and some customers want to return the product, some want to replace the product, some want to complain about the quality. I want to allow customers to submit a request themselves. I started with a simple model, so I will expand it when I solve big problems.

Here is my Model.

class Request extends DataObject
{
    private static $db = [
        'FullName' => 'Varchar',
        'RequestText' => 'Text'
    ];

    private static $has_one = [
        'Photo' => Image::class
    ];

    public function canView($member = null)
    {
        return Permission::check('VIEW_REQUEST', 'any', $member);
    }

    public function canEdit($member = null)
    {
        return Permission::check('EDIT_REQUEST', 'any', $member);
    }

    public function canDelete($member = null)
    {
        return Permission::check('DELETE_REQUEST', 'any', $member);
    }

    public function canCreate($member = null, $context = [])
    {
        return Permission::check('CREATE_REQUEST', 'any', $member);
    }

    /**
     * @return \SilverStripe\Forms\FieldList
     */
    public function getCMSFields()
    {
        $fields = parent::getCMSFields();
        $fields->addFieldToTab('Root.Main', TextField::create('FullName'));
        $fields->addFieldToTab('Root.Main', TextField::create('RequestText'));
        $fields->addFieldToTab('Root.Photos', $img = UploadField::create('Photo', 'Main photo'));

        $img->setFolderName("products");
        $img->setAllowedExtensions(["png", "jpg", "jpeg", "gif", "webp"]);

        return $fields;
    }
}

Request Controller

class Request_Controller extends ContentController implements PermissionProvider
{

    function providePermissions(){
        return array(
            "CREATE_REQUEST" => "Create REQUEST",
            "EDIT_REQUEST" => "Edit REQUEST",
            "VIEW_REQUEST" => "View REQUEST",
            "DELTE_REQUEST" => "Delete REQUEST",
        );
    }


问:
How do I list all of the applications installed on an Android mobile?

Possible Duplicate:

  How to get a list of installed android applications and pick one to run

I have a button. I gave it a click event. Now, I want to list the installed applications on my Android mobile. Is there any possible way to do this using intents? If anyone knows, please tell me.

答: Try using the PackageManager.</p>

ContentLicense: CC BY-SA 3.0

Body: Try using the PackageManager.


问:
Embed not being sent
```<code>import discord
from discord.ext import commands
import random
import praw

cl = commands.Bot(command_prefix = '!')
reddit = praw.Reddit(client_id = "",
                    client_secret = "",
                    username = "",
                    password = "",
                    user_agent = "")
@cl.event
async def on_ready():
  print("Bot is ready, get ready to do wutever u want with it")

@cl.command()
async def meme(ctx, amount=50, subr="memes", filter="top"):
 all_submission = []
 subreddit = reddit.subreddit("subr")
 subs = subreddit.filter(limit = amount)
 for submission in subs:
   all_submission.append(submission)
 random_sub = random.choice(all_submission)
 name = random_sub.title
 url = random_sub.url
 em = discord.embed(title = name)
 em.set_image = url
 await ctx.send(embed=em)
 print("embed sent")

cl.run("")
</code>```

when I was running this nothing showed up but when I debugged it and !meme in discord it was showing me this traceback error thing

```<code>It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
Ignoring exception in command meme:
Traceback (most recent call last):
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 20, in meme
    subs = subreddit.filter(limit = amount)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
    self._fetch()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 584, in _fetch
    data = self._fetch_data()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 581, in _fetch_data
    return self._reddit.request("GET", path, params)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/reddit.py", line 885, in request
    return self._core.request(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 330, in request
    return self._request_with_retries(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 228, in _request_with_retries
    response, saved_exception = self._make_request(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request
    response = self._rate_limiter.call(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
    kwargs["headers"] = set_header_callback()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 283, in _set_header_callback
    self._authorizer.refresh()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 425, in refresh
    self._request_token(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 158, in _request_token
    raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OAuthException: invalid_grant error processing request
</code>```

This is the error thing I was talking about and it is very weird like telling me to download async praw which I have never had a problem with and pls help it is needed

答:
This doesn't appear to be a discord.py issue, it appears to be related to the praw 0auth flow.

According to the traceback, there's an authentication issue in your praw credentials. Double, triple, and quadruple check your authentication credentials  and flow with the workflow and methodology in the docs

Title: Embed not being sent

Body:
import discord
from discord.ext import commands
import random
import praw

cl = commands.Bot(command_prefix = '!')
reddit = praw.Reddit(client_id = "",
                    client_secret = "",
                    username = "",
                    password = "",
                    user_agent = "")
@cl.event
async def on_ready():
  print("Bot is ready, get ready to do wutever u want with it")

@cl.command()
async def meme(ctx, amount=50, subr="memes", filter="top"):
 all_submission = []
 subreddit = reddit.subreddit("subr")
 subs = subreddit.filter(limit = amount)
 for submission in subs:
   all_submission.append(submission)
 random_sub = random.choice(all_submission)
 name = random_sub.title
 url = random_sub.url
 em = discord.embed(title = name)
 em.set_image = url
 await ctx.send(embed=em)
 print("embed sent")

cl.run("")

when I was running this nothing showed up but when I debugged it and !meme in discord it was showing me this traceback error thing

It appears that you are using PRAW in an asynchronous environment.
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
Ignoring exception in command meme:
Traceback (most recent call last):
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 20, in meme
    subs = subreddit.filter(limit = amount)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/base.py", line 34, in __getattr__
    self._fetch()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 584, in _fetch
    data = self._fetch_data()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/models/reddit/subreddit.py", line 581, in _fetch_data
    return self._reddit.request("GET", path, params)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/praw/reddit.py", line 885, in request
    return self._core.request(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 330, in request
    return self._request_with_retries(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 228, in _request_with_retries
    response, saved_exception = self._make_request(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 185, in _make_request
    response = self._rate_limiter.call(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/rate_limit.py", line 33, in call
    kwargs["headers"] = set_header_callback()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/sessions.py", line 283, in _set_header_callback
    self._authorizer.refresh()
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 425, in refresh
    self._request_token(
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/prawcore/auth.py", line 158, in _request_token
    raise OAuthException(
prawcore.exceptions.OAuthException: invalid_grant error processing request
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/runner/memes-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OAuthException: invalid_grant error processing request

This is the error thing I was talking about and it is very weird like telling me to download async praw which I have never had a problem with and pls help it is needed


问:
HTML: white space around elements, how to remove?
My webpage contains several divs. Some are set to width: 100%, so they fill the whole page width.
But at the top of the page there is a small whitespace before the first element shows up. Moreover, that same whitespace is visible left and right from elements spanning the whole page width.

I cannot figure out why. If I set:

```<code>html, body {
width: 100%;
}
</code>```

then the whitespace remains but the page is just stretched out to fit the image width of a div.

Can anyone help? It's probably pretty simple but I must be overlooking something.
Thank you.

EDIT: I must mention I'm using a parallax element. This uses a padding, so the image does fills the whole div and does not leave a black area on top. The HTML is:

```<code><div class="js-background-1 container">
</div>
</code>```

The CSS:

```<code>.container {
    padding-top: 200px;
}

.js-background-1 {
    background: transparent url(url/to/image) center 0 no-repeat;
}
</code>```

And the javascript:

```<code><script type="text/javascript">
var $window = $(window);
var velocity = 0.4;
function update(){
    var pos = $window.scrollTop();

    $('.container').each(function() {
        var $element = $(this);
        var height = $element.height();

        $(this).css('backgroundPosition', '50% ' + Math.round((height - pos) * velocity) + 'px');
    });
};

$window.bind('scroll', update);

</script>
</code>```

I used the tutorial from http://www.webdesign.org/how-to-create-a-parallax-scrolling-website.22336.html, so there is where it is from. I changed the HTML a bit for my website, but the rest is the same.

I saw the comment about the margin and padding set to 0, but that leads to my div to have a blank space if you don't scroll far enough.

答:
```<code>padding-bottom: 20px;
border: 1px solid red !important;
margin: 0;
padding: 0;
width: 100%;
</code>```

Body:
My webpage contains several divs. Some are set to width: 100%, so they fill the whole page width.
But at the top of the page there is a small whitespace before the first element shows up. Moreover, that same whitespace is visible left and right from elements spanning the whole page width.

I cannot figure out why. If I set:

html, body {
width: 100%;
}

then the whitespace remains but the page is just stretched out to fit the image width of a div.

Can anyone help? It's probably pretty simple but I must be overlooking something.
Thank you.

EDIT: I must mention I'm using a parallax element. This uses a padding, so the image does fills the whole div and does not leave a black area on top. The HTML is:

The CSS:

.container {
    padding-top: 200px;
}

.js-background-1 {
    background: transparent url(url/to/image) center 0 no-repeat;
}

And the javascript:

I used the tutorial from http://www.webdesign.org/how-to-create-a-parallax-scrolling-website.22336.html, so there is where it is from. I changed the HTML a bit for my website, but the rest is the same.

I saw the comment about the margin and padding set to 0, but that leads to my div to have a blank space if you don't scroll far enough.


问:
data frame slicing several problems
I don't understand slicing anymore!! I am doing strat_shuf_split.split and separate my data into training and test sets. I run this:

```<code>X_train = data1.loc[train_idx, cols]
y_train = data1.loc[train_idx, 'nClass']
X_test  = data1.loc[test_idx, cols]
y_test  = data1.loc[test_idx, 'nClass']
</code>```

and i get KeyError: 'Passing list-likes to .loc or [] with any missing labels is no longer supported.
I run it on a year old notebook and it runs fine. Why?
I try this:

```<code>X_train = X.loc[X.index.intersection(train_idx),:]
y_train = y.loc[y.index.intersection(train_idx),:]
X_test = X.loc[X.index.intersection(test_idx),:]
y_test = y.loc[y.index.intersection(test_idx),:]
</code>```

and I get error on y_train that there are too many indexers. Don't know what to do.

答:
You can try the following format:</p>
```<code>X_train = data1[cols].iloc[train_idx]
y_train = data1['nClass'].iloc[train_idx]
X_test  = data1[cols].iloc[test_idx]
y_test  = data1['nClass'].iloc[test_idx]
</code>```

Title: data frame slicing several problems

Body:
I don't understand slicing anymore!! I am doing strat_shuf_split.split and separate my data into training and test sets. I run this:

X_train = data1.loc[train_idx, cols]
y_train = data1.loc[train_idx, 'nClass']
X_test  = data1.loc[test_idx, cols]
y_test  = data1.loc[test_idx, 'nClass']

and i get KeyError: 'Passing list-likes to .loc or [] with any missing labels is no longer supported.
I run it on a year old notebook and it runs fine. Why?
I try this:

X_train = X.loc[X.index.intersection(train_idx),:]
y_train = y.loc[y.index.intersection(train_idx),:]
X_test = X.loc[X.index.intersection(test_idx),:]
y_test = y.loc[y.index.intersection(test_idx),:]

and I get error on y_train that there are too many indexers. Don't know what to do.

Body:
You can try the following format:

X_train = data1[cols].iloc[train_idx]
y_train = data1['nClass'].iloc[train_idx]
X_test  = data1[cols].iloc[test_idx]
y_test  = data1['nClass'].iloc[test_idx]


问:
Bootstrap 5 border-color doesn't work for responsive border-start/end/top/bottom
What I want to achieve:

For mobile: only border top/bottom,
For desktop: only border start/end, in border-dark color.

What I've tried:

added custom responsive borders to main.scss

```<code>// responsive borders

@each $breakpoint in map-keys($grid-breakpoints) {
    @include media-breakpoint-up($breakpoint) {
      $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

      .border#{$infix}-top {      border-top: $border-width solid $border-color !important; }
      .border#{$infix}-end {    border-right: $border-width solid $border-color !important; }
      .border#{$infix}-bottom {   border-bottom: $border-width solid $border-color !important; }
      .border#{$infix}-start {     border-left: $border-width solid $border-color !important; }

      .border#{$infix}-top-0 {    border-top: 0 !important; }
      .border#{$infix}-end-0 {  border-right: 0 !important; }
      .border#{$infix}-bottom-0 { border-bottom: 0 !important; }
      .border#{$infix}-start-0 {   border-left: 0 !important; }

      .border#{$infix}-x {
        border-left: $border-width solid $border-color !important;
        border-right: $border-width solid $border-color !important;
      }

      .border#{$infix}-y {
        border-top: $border-width solid $border-color !important;
        border-bottom: $border-width solid $border-color !important;
      }
    }
  }
</code>```

in html:

```<code><div class="col-sm-4 d-flex justify-content-center justify-content-sm-center border border-dark border-start-0 border-end-0 border-md-start border-md-end border-md-top-0 border-md-bottom-0 overflow-hidden"></div>
</code>```

The problem is borders start/end on desktop appears in default 1px solid #dee2e6 !important bootstrap color

答:
I think you need to specifically set border-{side}-width and border-style instead of the shorthand. Otherwise the color in the shorthand used by Bootstrap's .border: {1px solid #dee2e6 !important;} will override it.

```<code>   @include media-breakpoint-up($breakpoint) {
      .border#{$infix}-top { border-top-width: $border-width !important; border-style: solid !important; }
      .border#{$infix}-end { border-right-width: $border-width !important; border-style: solid !important; }
      .border#{$infix}-bottom { border-bottom-width: $border-width !important; border-style: solid !important; }
      .border#{$infix}-start { border-left-width: $border-width !important; border-style: solid !important; }

      .border#{$infix}-top-0 { border-top-width: 0 !important; }
      .border#{$infix}-end-0 { border-right-width: 0 !important; }
      .border#{$infix}-bottom-0 { border-bottom-width: 0 !important; }
      .border#{$infix}-start-0 { border-left-width: 0 !important; }
   }
</code>```

SASS demo

Body:
What I want to achieve:

For mobile: only border top/bottom,
For desktop: only border start/end, in border-dark color.

What I've tried:

added custom responsive borders to main.scss

// responsive borders

@each $breakpoint in map-keys($grid-breakpoints) {
    @include media-breakpoint-up($breakpoint) {
      $infix: breakpoint-infix($breakpoint, $grid-breakpoints);

      .border#{$infix}-top {      border-top: $border-width solid $border-color !important; }
      .border#{$infix}-end {    border-right: $border-width solid $border-color !important; }
      .border#{$infix}-bottom {   border-bottom: $border-width solid $border-color !important; }
      .border#{$infix}-start {     border-left: $border-width solid $border-color !important; }

      .border#{$infix}-top-0 {    border-top: 0 !important; }
      .border#{$infix}-end-0 {  border-right: 0 !important; }
      .border#{$infix}-bottom-0 { border-bottom: 0 !important; }
      .border#{$infix}-start-0 {   border-left: 0 !important; }

      .border#{$infix}-x {
        border-left: $border-width solid $border-color !important;
        border-right: $border-width solid $border-color !important;
      }

      .border#{$infix}-y {
        border-top: $border-width solid $border-color !important;
        border-bottom: $border-width solid $border-color !important;
      }
    }
  }

in html:

The problem is borders start/end on desktop appears in default 1px solid #dee2e6 !important bootstrap color

Body:
I think you need to specifically set border-{side}-width and border-style instead of the shorthand. Otherwise the color in the shorthand used by Bootstrap's .border: {1px solid #dee2e6 !important;} will override it.

   @include media-breakpoint-up($breakpoint) {
      .border#{$infix}-top { border-top-width: $border-width !important; border-style: solid !important; }
      .border#{$infix}-end { border-right-width: $border-width !important; border-style: solid !important; }
      .border#{$infix}-bottom { border-bottom-width: $border-width !important; border-style: solid !important; }
      .border#{$infix}-start { border-left-width: $border-width !important; border-style: solid !important; }

      .border#{$infix}-top-0 { border-top-width: 0 !important; }
      .border#{$infix}-end-0 { border-right-width: 0 !important; }
      .border#{$infix}-bottom-0 { border-bottom-width: 0 !important; }
      .border#{$infix}-start-0 { border-left-width: 0 !important; }
   }

SASS demo


问:
No converter found capable of converting from type org.bson.BsonUndefined
I have mongo driver 3.2.2, spring data mongodb 1.9.1.RELEASE.

Collection :

```<code>{
  "_id": "5728a1a5abdb9c352cda6432",
  "isDeleted": null,
  "name": undefined
},
{
  "_id": "5728a1a5abdb9c352cda6433",
  "isDeleted": null,
  "name": null
}
</code>```

When I try to fetch record with {"name":undefined} I get following exception.

```<code>org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type org.bson.BsonUndefined to type java.lang.String
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:313) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:176) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getPotentiallyConvertedSimpleRead(MappingMongoConverter.java:821) ~[spring-data-mongodb-1.7.1.RELEASE.jar:?]
</code>```

How to solve this? I have multiple types which needs to be converted from BsonUndefined like String, Date, PhoneNumber, etc...

答:
If undefined values are unwanted (i.e. were created due to some error) - you can unset them, by running following mongo script:

```<code>var TYPE_UNDEFINED = 6;
db.getCollection("my.lovely.collection").updateMany({ "name": {$type: TYPE_UNDEFINED}}, {
    $unset: {"name": 1}
});
</code>```

or set them to null - if that's preferred solution:

```<code>var TYPE_UNDEFINED = 6;
db.getCollection("my.lovely.collection").updateMany({ "name": {$type: TYPE_UNDEFINED}}, {
    $set: {"name": null}
});
</code>```

Body:
I have mongo driver 3.2.2, spring data mongodb 1.9.1.RELEASE.

Collection :

{
  "_id": "5728a1a5abdb9c352cda6432",
  "isDeleted": null,
  "name": undefined
},
{
  "_id": "5728a1a5abdb9c352cda6433",
  "isDeleted": null,
  "name": null
}

When I try to fetch record with {"name":undefined} I get following exception.

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type org.bson.BsonUndefined to type java.lang.String
    at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:313) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:195) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
    at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:176) ~[spring-core-4.1.7.RELEASE.jar:4.1.7.RELEASE]
    at org.springframework.data.mongodb.core.convert.MappingMongoConverter.getPotentiallyConvertedSimpleRead(MappingMongoConverter.java:821) ~[spring-data-mongodb-1.7.1.RELEASE.jar:?]

How to solve this? I have multiple types which needs to be converted from BsonUndefined like String, Date, PhoneNumber, etc...

Body:
If undefined values are unwanted (i.e. were created due to some error) - you can unset them, by running following mongo script:

var TYPE_UNDEFINED = 6;
db.getCollection("my.lovely.collection").updateMany({ "name": {$type: TYPE_UNDEFINED}}, {
    $unset: {"name": 1}
});

or set them to null - if that's preferred solution:

var TYPE_UNDEFINED = 6;
db.getCollection("my.lovely.collection").updateMany({ "name": {$type: TYPE_UNDEFINED}}, {
    $set: {"name": null}
});


问:
How do I find all the rows that share column value 2 based on column value 1?
I have a dataframe that looks like this

```<code>Movie          Actor      Year
Ocean's Eleven Brad Pitt  2001
Ocean's Eleven George Clooney 2001
Ocean's Eleven Matt Damon 2001
Pulp Fiction   Samuel L. Jackson 1994
Pulp Fiction   John Travolta 1994
</code>```

etcc...

It basically is a long list of movies with the main actors in that movie
Now my question: how can I find all the movies that share atleast one actor?

For example:

Ocean's Eleven and Ocean's Twelve both share Brad Pitt and George Clooney

Ocean's Eleven and Fury they both have Brad Pitt

Ocean's Eleven and Pulp Fiction do not share any main actors so it should not be found

I know I can use the intersect function to find overlapping elements in vectors/lists however I'm not sure how to do this for all unique movies in my dataframe! I thought of writing a for loop but I figured that there is probably an easier method.

答:
split Movie by Actor then subset for lengths > 1.

```<code>split(dat$Movie, dat$Actor) |> {\(.) .[lengths(.) > 1]}()
# $`Brad Pitt`
# [1] "Ocean's Eleven" "Fury"
</code>```

Data:

```<code>dat <- structure(list(Movie = c("Ocean's Eleven", "Ocean's Eleven",
"Ocean's Eleven", "Fury", "Fury", "Pulp Fiction", "Pulp Fiction"
), Actor = c("Brad Pitt", "George Clooney", "Matt Damon", "Brad Pitt",
"Someone Else", "Samuel L. Jackson", "John Travolta"), Year = c(2001L,
2001L, 2001L, 2222L, 2222L, 1994L, 1994L)), row.names = c(NA,
-7L), class = "data.frame")
</code>```

Body:
I have a dataframe that looks like this

Movie          Actor      Year
Ocean's Eleven Brad Pitt  2001
Ocean's Eleven George Clooney 2001
Ocean's Eleven Matt Damon 2001
Pulp Fiction   Samuel L. Jackson 1994
Pulp Fiction   John Travolta 1994

etcc...

It basically is a long list of movies with the main actors in that movie
Now my question: how can I find all the movies that share atleast one actor?

For example:

Ocean's Eleven and Ocean's Twelve both share Brad Pitt and George Clooney

Ocean's Eleven and Fury they both have Brad Pitt

Ocean's Eleven and Pulp Fiction do not share any main actors so it should not be found

I know I can use the intersect function to find overlapping elements in vectors/lists however I'm not sure how to do this for all unique movies in my dataframe! I thought of writing a for loop but I figured that there is probably an easier method.

Body:
split Movie by Actor then subset for lengths > 1.

split(dat$Movie, dat$Actor) |> {\(.) .[lengths(.) > 1]}()
# $`Brad Pitt`
# [1] "Ocean's Eleven" "Fury"

Data:

dat <- structure(list(Movie = c("Ocean's Eleven", "Ocean's Eleven",
"Ocean's Eleven", "Fury", "Fury", "Pulp Fiction", "Pulp Fiction"
), Actor = c("Brad Pitt", "George Clooney", "Matt Damon", "Brad Pitt",
"Someone Else", "Samuel L. Jackson", "John Travolta"), Year = c(2001L,
2001L, 2001L, 2222L, 2222L, 1994L, 1994L)), row.names = c(NA,
-7L), class = "data.frame")


问:
Kafka-connect to PostgreSQL - org.apache.kafka.connect.errors.DataException: Failed to deserialize topic to Avro

Setup

I've installed latest (7.0.1) version of Confluent platform in standalone mode on Ubuntu virtual machine.

Python producer for Avro format

Using this sample Avro producer to generate stream from data to Kafka topic (pmu214).

Producer seems to work ok. I'll give full code on request.
Producer output:

```<code>Raw data: {"pmu_id": 2, "time": 1644577001.22, "measurements": [{"stream_id": 2, "stat": "ok", "phasors": [[27.22379, 0.0], [24.672079638784002, -2.075237618663568], [25.11940552135938, 2.10660756475536], [3248.794237867336, -0.06468446412011757], [3068.6629010042793, -2.152472189017548], [2990.0809353594427, 2.031751749658583], [0.0, 0.0], [3101.9477751890026, -0.06193618455080409]], "analog": [], "digital": [0], "frequency": 50.022, "rocof": 0}]}
PMU record b'e5c1e5a8-3e44-465d-98c4-93f896ec1b14' successfully produced to pmu214 [0] at offset 38256
</code>```

KSQL

In ksqld it seems that record reached ksqldb ok:

```<code>rowtime: 2022/02/11 09:48:05.431 Z, key: [26151234-d3dd-4b7c-9222-2867@3486128305426751843/-], value: \x00\x00\x00\x00\x01\x04\xAA\xC3\xB1\xA0\x0C\x04\x04ok\xC2p\xD9A\x0F`\x
9F>.b\xC6A\xB9\xC8\xE2\xBF\xC5%\xC8A\x13v\x1A@\x8FVKE\xF9\xF8u>\xC5\xC5?E\xEA\xBA\xEC\xBF\xE0\xFA:E\xD5~\x15@\x00\x00\x00\x00\x00\x00\x00\x00\x84\x07BEs\xD1w>\x04[]\x020b\x0
2, partition: 0
Index 0 out of bounds for length 0
Topic printing ceased
</code>```

Kafka-connect

Here is command used to connect to PostgreSQL:

```<code>bin/connect-standalone etc/kafka/connect-standalone.properties etc/schema-registry/connect-avro-standalone.properties
</code>```

Here is content of connect-avro-standalone.properties:

```<code>bootstrap.servers=localhost:9092
name=sinkIRIpostgre
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector
connection.url=jdbc:postgresql://localhost:5432/mydb
topics=pmu214

connection.user=mydbuser
connection.password=mypass
auto.create=true
auto.evolve=true
insert.mode=insert
pk.mode=record_key
pk.fields=MESSAGE_KEY

key.converter=io.confluent.connect.avro.AvroConverter
key.converter.schema.registry.url=http://localhost:8081
value.converter=io.confluent.connect.avro.AvroConverter
value.converter.schema.registry.url=http://localhost:8081

internal.key.converter=org.apache.kafka.connect.json.JsonConverter
internal.value.converter=org.apache.kafka.connect.json.JsonConverter
internal.key.converter.schemas.enable=false
internal.value.converter.schemas.enable=false

offset.storage.file.filename=/tmp/connect.offsets
</code>```

I didn't change anything in connect-standalone.properties except plugins I've installed.

```<code>plugin.path=/home/proton/kafkaConnectors/confluentinc-kafka-connect-jdbc-10.3.2,/home/proton/kafkaConverters/confluentinc-kafka-connect-json-schema-converter-7.0.1,/home/proton/kafkaConverters/confluentinc-kafka-connect-avro-converter-7.0.1/
</code>```

ERROR received

ERROR [sinkIRIpostgre|task-0] WorkerSinkTask{id=sinkIRIpostgre-0}
Error converting message key in topic 'pmu214' partition 0 at offset 0
and timestamp 1644560570372: Failed to deserialize data for topic
pmu214 to Avro:  (org.apache.kafka.connect.runtime.WorkerSinkTask:552)
org.apache.kafka.connect.errors.DataException: Failed to deserialize
data for topic pmu214 to Avro:    at
io.confluent.connect.avro.AvroConverter.toConnectData(AvroConverter.java:124)
at
org.apache.kafka.connect.storage.Converter.toConnectData(Converter.java:87)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.convertKey(WorkerSinkTask.java:550)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.lambda$convertAndTransformRecord$3(WorkerSinkTask.java:513)
at
org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndRetry(RetryWithToleranceOperator.java:156)
at
org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:190)
at
org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execute(RetryWithToleranceOperator.java:132)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.convertAndTransformRecord(WorkerSinkTask.java:513)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.convertMessages(WorkerSinkTask.java:493)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:332)

答:
If you literally ran the Python sample code, then the key is not Avro, so a failure on the key.converter would be expected, as shown

Error converting message key

Body:
Setup

I've installed latest (7.0.1) version of Confluent platform in standalone mode on Ubuntu virtual machine.

Python producer for Avro format

Using this sample Avro producer to generate stream from data to Kafka topic (pmu214).

Producer seems to work ok. I'll give full code on request.
Producer output:

Raw data: {"pmu_id": 2, "time": 1644577001.22, "measurements": [{"stream_id": 2, "stat": "ok", "phasors": [[27.22379, 0.0], [24.672079638784002, -2.075237618663568], [25.11940552135938, 2.10660756475536], [3248.794237867336, -0.06468446412011757], [3068.6629010042793, -2.152472189017548], [2990.0809353594427, 2.031751749658583], [0.0, 0.0], [3101.9477751890026, -0.06193618455080409]], "analog": [], "digital": [0], "frequency": 50.022, "rocof": 0}]}
PMU record b'e5c1e5a8-3e44-465d-98c4-93f896ec1b14' successfully produced to pmu214 [0] at offset 38256

KSQL

In ksqld it seems that record reached ksqldb ok:

rowtime: 2022/02/11 09:48:05.431 Z, key: [26151234-d3dd-4b7c-9222-2867@3486128305426751843/-], value: \x00\x00\x00\x00\x01\x04\xAA\xC3\xB1\xA0\x0C\x04\x04ok\xC2p\xD9A\x0F`\x
9F>.b\xC6A\xB9\xC8\xE2\xBF\xC5%\xC8A\x13v\x1A@\x8FVKE\xF9\xF8u>\xC5\xC5?E\xEA\xBA\xEC\xBF\xE0\xFA:E\xD5~\x15@\x00\x00\x00\x00\x00\x00\x00\x00\x84\x07BEs\xD1w>\x04[]\x020b\x0
2, partition: 0
Index 0 out of bounds for length 0
Topic printing ceased

Kafka-connect

Here is command used to connect to PostgreSQL:

bin/connect-standalone etc/kafka/connect-standalone.properties etc/schema-registry/connect-avro-standalone.properties

Here is content of connect-avro-standalone.properties:

bootstrap.servers=localhost:9092
name=sinkIRIpostgre
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector
connection.url=jdbc:postgresql://localhost:5432/mydb
topics=pmu214

connection.user=mydbuser
connection.password=mypass
auto.create=true
auto.evolve=true
insert.mode=insert
pk.mode=record_key
pk.fields=MESSAGE_KEY

key.converter=io.confluent.connect.avro.AvroConverter
key.converter.schema.registry.url=http://localhost:8081
value.converter=io.confluent.connect.avro.AvroConverter
value.converter.schema.registry.url=http://localhost:8081

internal.key.converter=org.apache.kafka.connect.json.JsonConverter
internal.value.converter=org.apache.kafka.connect.json.JsonConverter
internal.key.converter.schemas.enable=false
internal.value.converter.schemas.enable=false

offset.storage.file.filename=/tmp/connect.offsets

I didn't change anything in connect-standalone.properties except plugins I've installed.

plugin.path=/home/proton/kafkaConnectors/confluentinc-kafka-connect-jdbc-10.3.2,/home/proton/kafkaConverters/confluentinc-kafka-connect-json-schema-converter-7.0.1,/home/proton/kafkaConverters/confluentinc-kafka-connect-avro-converter-7.0.1/

ERROR received

ERROR [sinkIRIpostgre|task-0] WorkerSinkTask{id=sinkIRIpostgre-0}
Error converting message key in topic 'pmu214' partition 0 at offset 0
and timestamp 1644560570372: Failed to deserialize data for topic
pmu214 to Avro:  (org.apache.kafka.connect.runtime.WorkerSinkTask:552)
org.apache.kafka.connect.errors.DataException: Failed to deserialize
data for topic pmu214 to Avro:    at
io.confluent.connect.avro.AvroConverter.toConnectData(AvroConverter.java:124)
at
org.apache.kafka.connect.storage.Converter.toConnectData(Converter.java:87)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.convertKey(WorkerSinkTask.java:550)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.lambda$convertAndTransformRecord$3(WorkerSinkTask.java:513)
at
org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndRetry(RetryWithToleranceOperator.java:156)
at
org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execAndHandleError(RetryWithToleranceOperator.java:190)
at
org.apache.kafka.connect.runtime.errors.RetryWithToleranceOperator.execute(RetryWithToleranceOperator.java:132)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.convertAndTransformRecord(WorkerSinkTask.java:513)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.convertMessages(WorkerSinkTask.java:493)
at
org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:332)


问:
Is it possible to count the number of shared characters in two cells / strings?
I have a large number of strings in a pair of columns in a spreadsheet. I'd like to write a formula to tell me whether "enough" initial characters of one cell are also initial characters of the other cell. Basically, I'm looking for something that can say "these two strings start with the same N characters" and then I get to choose what N I think means "enough" so I can flag the row using magic text, conditional-formatting or whatever.

Since the "choose the N" and magic text/conditional-formatting are well understood, I only need to figure out the "count shared characters" part so I'll focus on that.

For example:

Column A
Column B
Formula Output

Foo
Bar
0

Foo
Food
3

Foo
Fud
1

Bar
Bark
3

Bar
baz
2

Bar
abar
0

What formula could be used to produce Column C from Columns A and B?

I can easily write a script/program outside of a spreadsheet to do this kind of thing, or maybe even a sufficiently complex SQL query if I load the data into a database first. But I'd like to deal with this at the spreadsheet level because (a) the data is already in a spreadsheet) and (b) this formula will be used by non-programmers once I get it working.

答:
Unfortunately, as far I know, there is no quick way to achieve this. Please see the codes below for each cell:

```<code>=COUNTIF(B1,"*f*")+COUNTIF(B1,"*o*")+COUNTIF(B1,"*o*")
=COUNTIF(B2,"*f*")+COUNTIF(B2,"*o*")+COUNTIF(B2,"*o*")
=COUNTIF(B3,"*f*")+COUNTIF(B3,"*o*")+COUNTIF(B3,"*o*")
=COUNTIF(B4,"*b*")+COUNTIF(B4,"*a*")+COUNTIF(B4,"*r*")
=COUNTIF(B5,"*b*")+COUNTIF(B5,"*a*")+COUNTIF(B5,"*r*")
=COUNTIF(B6,"*b*")+COUNTIF(B6,"*a*")+COUNTIF(B6,"*r*")
</code>```

Explanation:

=COUNTIF counts how many times something appears

B1, counts how many times it appears in cell B1

*f* counts how many times the letter "f" appears, even if it preceded or succeeded by other text

Body:
Unfortunately, as far I know, there is no quick way to achieve this. Please see the codes below for each cell:

=COUNTIF(B1,"*f*")+COUNTIF(B1,"*o*")+COUNTIF(B1,"*o*")
=COUNTIF(B2,"*f*")+COUNTIF(B2,"*o*")+COUNTIF(B2,"*o*")
=COUNTIF(B3,"*f*")+COUNTIF(B3,"*o*")+COUNTIF(B3,"*o*")
=COUNTIF(B4,"*b*")+COUNTIF(B4,"*a*")+COUNTIF(B4,"*r*")
=COUNTIF(B5,"*b*")+COUNTIF(B5,"*a*")+COUNTIF(B5,"*r*")
=COUNTIF(B6,"*b*")+COUNTIF(B6,"*a*")+COUNTIF(B6,"*r*")

Explanation:

=COUNTIF counts how many times something appears

B1, counts how many times it appears in cell B1

*f* counts how many times the letter "f" appears, even if it preceded or succeeded by other text


问:
How to remove the border of last child in list items using after
In my application I have some font icons in i tag within the list items and after the each icons I have placed some border line .

But my requirement is to remove the border of last element in list items.

.component.html

```<code><div class="list-container">
<ul>
   <li *ngFor="let icon of iconsArr">
    <span class="icons" [style.font-weight]="icon.active ? 'bold' : 'normal'" ></span><i (click)="onIconClick(icon)" class="smiley-icon "   [ngClass]="icon.class"
    [style.color]="icon.active === true ? '#FF0000' : '#ffffff'" >

 </i>
   </li>
 </ul>
      </div>

</code>```

.component.css

```<code>.list-container{
  li{
    display: inline;
  }
.icons{
    font-size: 2.9em;
    display:inline-block;
    margin: 0px;
    text-shadow: -1.3px 0 #000, 0 1.3px #000, 1.3px 0 #000, 0 -1.3px #000;
    color: white;
    margin-right: -8.9px;
    //z-index:1000;
}
 .icons::after{
    content: "";
    display: inline-block;
    width: 0.8em;
    border-top: 5px solid #e8e8e8;
    top: 50%;
    z-index: -10;
    margin-bottom: 15px;
    margin-left: -8px;
}

</code>```

If I write

```<code>
.icons:last-of-type:after{
content:"";
border:none;
}
</code>```

It is not working, I want to remove the border for last icon from the list of icons

答:
It is the li element not the span that is the last child that you want to target.

So use:

```<code>.list-container ul li:last-child span.icons::after {
  border: none;
}
</code>```

Body:
In my application I have some font icons in i tag within the list items and after the each icons I have placed some border line .

But my requirement is to remove the border of last element in list items.

.component.html

.component.css

.list-container{
  li{
    display: inline;
  }
.icons{
    font-size: 2.9em;
    display:inline-block;
    margin: 0px;
    text-shadow: -1.3px 0 #000, 0 1.3px #000, 1.3px 0 #000, 0 -1.3px #000;
    color: white;
    margin-right: -8.9px;
    //z-index:1000;
}
 .icons::after{
    content: "";
    display: inline-block;
    width: 0.8em;
    border-top: 5px solid #e8e8e8;
    top: 50%;
    z-index: -10;
    margin-bottom: 15px;
    margin-left: -8px;
}

If I write

.icons:last-of-type:after{
content:"";
border:none;
}

It is not working, I want to remove the border for last icon from the list of icons

Body:
It is the li element not the span that is the last child that you want to target.

So use:

.list-container ul li:last-child span.icons::after {
  border: none;
}


问:
PyTorch Lightning Transfer Learning with Stacked LSTM
I have trained a stacked LSTM on PyTorch Lightning with the following layers:

```<code>def __init__(self, n_features, hidden_size, batch_size, num_layers, dropout, learning_rate):
    super(LSTMClassifier, self).__init__()
    ...

    # Architecture Baseline
    self.lstm = nn.LSTM(input_size=n_features,
                        hidden_size=hidden_size,
                        num_layers=num_layers,
                        dropout=dropout,
                        batch_first=True)
    self.relu = nn.ReLU()
    self.fc = nn.Linear(hidden_size, 2)
    self.sigmoid = nn.Sigmoid()
</code>```

and architecture:

```<code>def forward(self, x):
    # reshape to pass each element of sequence through lstm, and not all together
    # LSTM needs a 3D tensor
    x = x.view(len(x), 1, -1)

    out, _ = self.lstm(x)
    out = self.relu(out)
    out = self.fc(out)
    out = self.sigmoid(out)
    # reshape back to be compatible with the true values' shape
    out = out.reshape(self.batch_size, -1)

    return out
</code>```

Now, I want to use this pre-trained model for transfer learning according to the PyTorch Lightning tutorial:

```<code>import torchvision.models as models

class ImagenetTransferLearning(LightningModule):
    def __init__(self):
        super().__init__()

        # init a pretrained resnet
        backbone = # loading the pretrained model from file
        num_filters = backbone.fc.in_features
        layers = list(backbone.children())[:-3]
        self.feature_extractor = nn.Sequential(*layers)

        # use the pretrained model for binary classification
        num_target_classes = 2
        self.classifier = nn.Linear(num_filters, num_target_classes)

    def forward(self, x):
        self.feature_extractor.eval()
        with torch.no_grad():
            representations = self.feature_extractor(x).flatten(1)
        x = self.classifier(representations)
        ...
</code>```

However, LSTM layers cannot be entered into an nn.Sequential() as per this question. So, what sort of module can I use as feature_extractor instead of nn.Sequential()?

答:
Ultimately, based on the linked question, I changed the feature_extractor definition as below (assuming you know the layers you want to freeze):

```<code>self.feature_extractor = nn.Sequential(self.layers[0], GetLSTMOutput(), self.layers[1])
</code>```

Hopefully, this helps someone as I've been baffled for a while.

Body:
I have trained a stacked LSTM on PyTorch Lightning with the following layers:

def __init__(self, n_features, hidden_size, batch_size, num_layers, dropout, learning_rate):
    super(LSTMClassifier, self).__init__()
    ...

    # Architecture Baseline
    self.lstm = nn.LSTM(input_size=n_features,
                        hidden_size=hidden_size,
                        num_layers=num_layers,
                        dropout=dropout,
                        batch_first=True)
    self.relu = nn.ReLU()
    self.fc = nn.Linear(hidden_size, 2)
    self.sigmoid = nn.Sigmoid()

and architecture:

def forward(self, x):
    # reshape to pass each element of sequence through lstm, and not all together
    # LSTM needs a 3D tensor
    x = x.view(len(x), 1, -1)

    out, _ = self.lstm(x)
    out = self.relu(out)
    out = self.fc(out)
    out = self.sigmoid(out)
    # reshape back to be compatible with the true values' shape
    out = out.reshape(self.batch_size, -1)

    return out

Now, I want to use this pre-trained model for transfer learning according to the PyTorch Lightning tutorial:

import torchvision.models as models

class ImagenetTransferLearning(LightningModule):
    def __init__(self):
        super().__init__()

        # init a pretrained resnet
        backbone = # loading the pretrained model from file
        num_filters = backbone.fc.in_features
        layers = list(backbone.children())[:-3]
        self.feature_extractor = nn.Sequential(*layers)

        # use the pretrained model for binary classification
        num_target_classes = 2
        self.classifier = nn.Linear(num_filters, num_target_classes)

    def forward(self, x):
        self.feature_extractor.eval()
        with torch.no_grad():
            representations = self.feature_extractor(x).flatten(1)
        x = self.classifier(representations)
        ...

However, LSTM layers cannot be entered into an nn.Sequential() as per this question. So, what sort of module can I use as feature_extractor instead of nn.Sequential()?

Body:
Ultimately, based on the linked question, I changed the feature_extractor definition as below (assuming you know the layers you want to freeze):

self.feature_extractor = nn.Sequential(self.layers[0], GetLSTMOutput(), self.layers[1])

Hopefully, this helps someone as I've been baffled for a while.


问:
Select random rows from duplicate IDS
I'm dealing with a dataset where I have students ratings of teachers. Some students rated the same teacher more than once.
What I would like to do with the data is to subset it with the following criteria:

1) Keep any unique student Ids and ratings

2) In cases where students rated a teacher twice keep only 1 rating, but to select which rating to keep randomly.

3) If possible I'd like to be able to run the code in a munging script at the top of every analysis file and ensure that the dataset created is exaclty the same for each analysis (set seed?).

```<code># data
student.id <- c(1,1,2,3,3,4,5,6,7,7,7,8,9)
teacher.id <- c(1,1,1,1,1,2,2,2,2,2,2,2,2)
rating <- c(100,99,89,100,99,87,24,52,100,99,89,79,12)
df <- data.frame(student.id,teacher.id,rating)
</code>```

Thanks for any guidance for how to move forward.

答:
This can now be done much faster using data.table. Your question is equivalent to sampling rows from within groups, see

Sample random rows within each group in a data.table

Title: Select random rows from duplicate IDS

Body:
I'm dealing with a dataset where I have students ratings of teachers. Some students rated the same teacher more than once.
What I would like to do with the data is to subset it with the following criteria:

1) Keep any unique student Ids and ratings

2) In cases where students rated a teacher twice keep only 1 rating, but to select which rating to keep randomly.

3) If possible I'd like to be able to run the code in a munging script at the top of every analysis file and ensure that the dataset created is exaclty the same for each analysis (set seed?).

# data
student.id <- c(1,1,2,3,3,4,5,6,7,7,7,8,9)
teacher.id <- c(1,1,1,1,1,2,2,2,2,2,2,2,2)
rating <- c(100,99,89,100,99,87,24,52,100,99,89,79,12)
df <- data.frame(student.id,teacher.id,rating)

Thanks for any guidance for how to move forward.


问:
How can I stop Eclipse from asking to install Subversive Connectors
I'm using Eclipse Helios v3.6 and every time I start up I get the following dialog.  Yet I do not use subversion.  Does anyone know how to make this stop?

答:
I had the same issue. To fix it I went into my Eclipse plug-ins directory and searched for anything with "svn", "subversion", or "subclipse" in the filename. I removed the following JAR's and relaunched Eclipse. So far so good.</p>

```<code>01/19/2011  09:37 AM             8,262 com.smartbear.collaborator.subclipse_6.0.6016.jar
01/19/2011  09:37 AM            19,556 com.smartbear.collaborator.subversive_6.0.6016.jar
01/19/2011  09:37 AM            10,539 com.smartbear.collaborator.ui.subclipse_6.0.6016.jar
01/19/2011  09:37 AM            11,093 com.smartbear.collaborator.ui.subversive_6.0.6016.jar
05/04/2011  11:03 AM           943,141 org.eclipse.team.svn.core_0.7.9.I20110207-1700.jar
05/04/2011  11:04 AM         2,490,582 org.eclipse.team.svn.ui_0.7.9.I20110207-1700.jar
05/04/2011  11:44 AM            82,086 org.tigris.subversion.clientadapter_1.6.12.jar
05/04/2011  11:44 AM           297,927 org.tigris.subversion.subclipse.core_1.6.17.jar
05/04/2011  11:44 AM         1,928,100 org.tigris.subversion.subclipse.ui_1.6.17.jar
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I had the same issue. To fix it I went into my Eclipse plug-ins directory and searched for anything with "svn", "subversion", or "subclipse" in the filename. I removed the following JAR's and relaunched Eclipse. So far so good.

01/19/2011  09:37 AM             8,262 com.smartbear.collaborator.subclipse_6.0.6016.jar
01/19/2011  09:37 AM            19,556 com.smartbear.collaborator.subversive_6.0.6016.jar
01/19/2011  09:37 AM            10,539 com.smartbear.collaborator.ui.subclipse_6.0.6016.jar
01/19/2011  09:37 AM            11,093 com.smartbear.collaborator.ui.subversive_6.0.6016.jar
05/04/2011  11:03 AM           943,141 org.eclipse.team.svn.core_0.7.9.I20110207-1700.jar
05/04/2011  11:04 AM         2,490,582 org.eclipse.team.svn.ui_0.7.9.I20110207-1700.jar
05/04/2011  11:44 AM            82,086 org.tigris.subversion.clientadapter_1.6.12.jar
05/04/2011  11:44 AM           297,927 org.tigris.subversion.subclipse.core_1.6.17.jar
05/04/2011  11:44 AM         1,928,100 org.tigris.subversion.subclipse.ui_1.6.17.jar


问:
in maya, set custom attributes of an expression node by variables
I want to drive the ouput values of custom attributes of a expression node by variables inside this same expression node.

答: Expressions do not work like this. You cannot assing a value to an attribute this way. The direct assingment only works if you set an value of a connected destination. If you want to set an attribute, you have to use setAttr().


问:
How do I loop a menu driven program that uses a switch case?
I need to ask the user in this way "Do you want to do it again?" and the user will choose Y or N whether they want to compute another set of numbers and go through the program all over again.</p>
```<code>#include <iostream>

using namespace std;

int main()
{
    float x, y;
    float Sum, Difference, Product, Quotient;
    char choice;

    cout << "Enter x and y: ";
    cin >> x >> y;
    cout << "MENU" << endl;
    cout << "A: Addition " << endl;
    cout << "B: Subtraction" << endl;
    cout << "C: Multiplication " << endl;
    cout << "D: Division " << endl;
    cout << "E: Exit " << endl;
    cout << "Enter your choice :";
    cin >> choice;
        switch (choice)
        {
        case 'A':
            Sum = x+y;
            cout << x << "+" << y << "=" << Sum <<endl;
            break;
        case 'B':
            Difference = x-y;
            cout << x << "-" << y << "=" << Difference <<endl;
            break;
        case 'C':
            Product = x*y;
            cout << x << "*" << y << "=" << Product <<endl;
            break;
        case 'D':
            Quotient = x/y;
            cout << x << "/" << y << "=" <<  Quotient <<endl;
            break;
        case 'E':
            break;
        default:
            cout << "Invalid input" << endl;
        }
    return 0;
}

</code>```

答:
It's actually pretty simple. You can use loops as such:

```<code>    #include <iostream>

    using namespace std;

    void showChoices();
    int main()
    {
        while (true) // This is a while loop
        {
            system("cls"); // Clear the screen. If you don't want to clear the screen you can remove this line

            float x, y;
            float Sum, Difference, Product, Quotient;
            char choice;

            cout << "Enter x and y: ";
            cin >> x >> y;

            showChoices();
            cin >> choice;
            switch (choice)
            {
            case 'A':
                Sum = x + y;
                cout << x << "+" << y << "=" << Sum << endl;
                break;
            case 'B':
                Difference = x - y;
                cout << x << "-" << y << "=" << Difference << endl;
                break;
            case 'C':
                Product = x - y;
                cout << x << "*" << y << "=" << Product << endl;
                break;
            case 'D':
                Quotient = x - y;
                cout << x << "/" << y << "=" << Quotient << endl;
                break;
            case 'E':
                return 0; // Instead of break, use return here
            default:
                cout << "Invalid input" << endl;
            }
        }
    }

    void showChoices()
    {
        cout << "MENU" << endl;
        cout << "A: Addition " << endl;
        cout << "B: Subtraction" << endl;
        cout << "C: Multiplication " << endl;
        cout << "D: Division " << endl;
        cout << "E: Exit " << endl;
        cout << "Enter your choice :";
    }
</code>```

Also consider removing the line:

```<code>using namespace std
</code>```

...because it's not considered as a good practice.

Also consider refactoring your code by moving the code inside the loop to a separate function, which returns a boolean something like this:

```<code>    #include <iostream>

    using namespace std;

    void showChoices();
    bool askUser();
    int main()
    {
        while (askUser()) { /* Loop */ }
    }

    void showChoices()
    {
        cout << "MENU" << endl;
        cout << "A: Addition " << endl;
        cout << "B: Subtraction" << endl;
        cout << "C: Multiplication " << endl;
        cout << "D: Division " << endl;
        cout << "E: Exit " << endl;
        cout << "Enter your choice :";
    }

    bool askUser()
    {
        system("cls"); // Clear the screen. Can be removed if you don't want to do so.

        float x, y;
        float Sum, Difference, Product, Quotient;
        char choice;

        cout << "Enter x and y: ";
        cin >> x >> y;

        showChoices();
        cin >> choice;
        switch (choice)
        {
        case 'A':
            Sum = x + y;
            cout << x << "+" << y << "=" << Sum << endl;
            break;
        case 'B':
            Difference = x - y;
            cout << x << "-" << y << "=" << Difference << endl;
            break;
        case 'C':
            Product = x - y;
            cout << x << "*" << y << "=" << Product << endl;
            break;
        case 'D':
            Quotient = x - y;
            cout << x << "/" << y << "=" << Quotient << endl;
            break;
        case 'E':
            return false;
        default:
            cout << "Invalid input" << endl;
        }

        return true;
    }
</code>```

I hope it was useful :).

Body:
I need to ask the user in this way "Do you want to do it again?" and the user will choose Y or N whether they want to compute another set of numbers and go through the program all over again.

#include <iostream>

using namespace std;

int main()
{
    float x, y;
    float Sum, Difference, Product, Quotient;
    char choice;

    cout << "Enter x and y: ";
    cin >> x >> y;
    cout << "MENU" << endl;
    cout << "A: Addition " << endl;
    cout << "B: Subtraction" << endl;
    cout << "C: Multiplication " << endl;
    cout << "D: Division " << endl;
    cout << "E: Exit " << endl;
    cout << "Enter your choice :";
    cin >> choice;
        switch (choice)
        {
        case 'A':
            Sum = x+y;
            cout << x << "+" << y << "=" << Sum <<endl;
            break;
        case 'B':
            Difference = x-y;
            cout << x << "-" << y << "=" << Difference <<endl;
            break;
        case 'C':
            Product = x*y;
            cout << x << "*" << y << "=" << Product <<endl;
            break;
        case 'D':
            Quotient = x/y;
            cout << x << "/" << y << "=" <<  Quotient <<endl;
            break;
        case 'E':
            break;
        default:
            cout << "Invalid input" << endl;
        }
    return 0;
}

Body:
It's actually pretty simple. You can use loops as such:

    #include <iostream>

    using namespace std;

    void showChoices();
    int main()
    {
        while (true) // This is a while loop
        {
            system("cls"); // Clear the screen. If you don't want to clear the screen you can remove this line

            float x, y;
            float Sum, Difference, Product, Quotient;
            char choice;

            cout << "Enter x and y: ";
            cin >> x >> y;

            showChoices();
            cin >> choice;
            switch (choice)
            {
            case 'A':
                Sum = x + y;
                cout << x << "+" << y << "=" << Sum << endl;
                break;
            case 'B':
                Difference = x - y;
                cout << x << "-" << y << "=" << Difference << endl;
                break;
            case 'C':
                Product = x - y;
                cout << x << "*" << y << "=" << Product << endl;
                break;
            case 'D':
                Quotient = x - y;
                cout << x << "/" << y << "=" << Quotient << endl;
                break;
            case 'E':
                return 0; // Instead of break, use return here
            default:
                cout << "Invalid input" << endl;
            }
        }
    }

    void showChoices()
    {
        cout << "MENU" << endl;
        cout << "A: Addition " << endl;
        cout << "B: Subtraction" << endl;
        cout << "C: Multiplication " << endl;
        cout << "D: Division " << endl;
        cout << "E: Exit " << endl;
        cout << "Enter your choice :";
    }

Also consider removing the line:

using namespace std

...because it's not considered as a good practice.

Also consider refactoring your code by moving the code inside the loop to a separate function, which returns a boolean something like this:

    #include <iostream>

    using namespace std;

    void showChoices();
    bool askUser();
    int main()
    {
        while (askUser()) { /* Loop */ }
    }

    void showChoices()
    {
        cout << "MENU" << endl;
        cout << "A: Addition " << endl;
        cout << "B: Subtraction" << endl;
        cout << "C: Multiplication " << endl;
        cout << "D: Division " << endl;
        cout << "E: Exit " << endl;
        cout << "Enter your choice :";
    }

    bool askUser()
    {
        system("cls"); // Clear the screen. Can be removed if you don't want to do so.

        float x, y;
        float Sum, Difference, Product, Quotient;
        char choice;

        cout << "Enter x and y: ";
        cin >> x >> y;

        showChoices();
        cin >> choice;
        switch (choice)
        {
        case 'A':
            Sum = x + y;
            cout << x << "+" << y << "=" << Sum << endl;
            break;
        case 'B':
            Difference = x - y;
            cout << x << "-" << y << "=" << Difference << endl;
            break;
        case 'C':
            Product = x - y;
            cout << x << "*" << y << "=" << Product << endl;
            break;
        case 'D':
            Quotient = x - y;
            cout << x << "/" << y << "=" << Quotient << endl;
            break;
        case 'E':
            return false;
        default:
            cout << "Invalid input" << endl;
        }

        return true;
    }

I hope it was useful :).


问:
Google Apps Script Save copy to read only
How do you save a copy of the current Sheets file to a read-only copy? We have scripts that set values that once confirmed save to a new Sheets file. This new file needs to be set as ReadOnly as a part of the script.</p>

答:
You can use the DriveApp Permission enum, .setSharing, and related methods to do this.

Assuming you have a reference to the File object represented by the new Sheets file, this function will change all sharing so that the file is "View only" for anyone who previously had edit permission.

```<code>/**
 * Change sharing permissions on a file or folder.
 * @param {File or Folder object} asset
 */
function makeViewOnly(asset)
{
  // General sharing permissions: change VIEW to NONE if you only want specific people to view the file
  asset.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW);
  asset.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  // These only apply if the file is on a Workspace domain.
  asset.setSharing(DriveApp.Access.DOMAIN, DriveApp.Permission.VIEW);
  asset.setSharing(DriveApp.Access.DOMAIN_WITH_LINK, DriveApp.Permission.VIEW);

  // Change all edit permissions to view permissions
  users = asset.getEditors();
  user.forEach(function (user) {
    asset.removeEditor(user)
    asset.addViewer(user)
  });
}
</code>```

If you have a reference to the Spreadsheet object for the newly created Sheets file instead of the File object, you can get the File object via

```<code>var asset = DriveApp.getFileById(spreadsheet.getId())
</code>```

Body:
You can use the DriveApp Permission enum, .setSharing, and related methods to do this.

Assuming you have a reference to the File object represented by the new Sheets file, this function will change all sharing so that the file is "View only" for anyone who previously had edit permission.

/**
 * Change sharing permissions on a file or folder.
 * @param {File or Folder object} asset
 */
function makeViewOnly(asset)
{
  // General sharing permissions: change VIEW to NONE if you only want specific people to view the file
  asset.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW);
  asset.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  // These only apply if the file is on a Workspace domain.
  asset.setSharing(DriveApp.Access.DOMAIN, DriveApp.Permission.VIEW);
  asset.setSharing(DriveApp.Access.DOMAIN_WITH_LINK, DriveApp.Permission.VIEW);

  // Change all edit permissions to view permissions
  users = asset.getEditors();
  user.forEach(function (user) {
    asset.removeEditor(user)
    asset.addViewer(user)
  });
}

If you have a reference to the Spreadsheet object for the newly created Sheets file instead of the File object, you can get the File object via

var asset = DriveApp.getFileById(spreadsheet.getId())


问:
How can I optionally pass one or two semicolon separated params in a GET request and retrieve the data that pertains to it/them?
In Postman, whenever I pass key isbns and values 0307951529;9780307951526 while doing dd($queryArray);.  I get the correct output:

```<code>^ array:2 [
  "isbn10" => "0307951529"
  "isbn13" => "9780307951526"
]
</code>```

However, on the isbns key, when I try to pass one value in Postman instead of two - I get an error that says: array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements.  This is because I'm being reliant on array_combine($keysArray, $valuesArray); to do this but I feel like it's not a good approach.

What's a good way to do this so that optionally, one or two semicolon separated values can be accepted so an error won't get thrown?

Note: dd(urldecode($request->fullUrl())); displays the url correctly (provided this detail in case more information is needed).

```<code>    $isbn = $request->get('isbns');
    $keysArray = ['isbn10', 'isbn13'];
    $valuesArray = explode(';', $isbn);
    $queryArray = array_combine($keysArray, $valuesArray);

    $queryParams = [
        'api-key' => $apiKey,
        'author' => $author,
        'title' => $title,
        'isbns' => [(object) $queryArray]
    ];

    dd($queryParams);
    // dd(urldecode($request->fullUrl()));
</code>```

答:
Assuming you just want to know what to do if only one param is passed in isbn then you can do this

```<code>$isbn = '234234;777777';
$keysArray = ['isbn10', 'isbn13'];
$valuesArray = explode(';', $isbn);

foreach($valuesArray as $i=>$val){
    $queryArray[$keysArray[$i]] = $val;
}
print_r($queryArray);
</code>```

RESULT

```<code>Array
(
    [isbn10] => 234234
    [isbn13] => 777777
)
</code>```

Now if you only pass one param

```<code>$isbn = '234234';
$keysArray = ['isbn10', 'isbn13'];
$valuesArray = explode(';', $isbn);

foreach($valuesArray as $i=>$val){
    $queryArray[$keysArray[$i]] = $val;
}
print_r($queryArray);
</code>```

RESULT

```<code>Array
(
    [isbn10] => 234234
)
</code>```

But this does leave a lot of potential for problems as mentioned in the comments, like is it correct that the single param should be placed in isbn10 and also what happens of there are 3 parameter passed like `123;456;789'

Body:
In Postman, whenever I pass key isbns and values 0307951529;9780307951526 while doing dd($queryArray);.  I get the correct output:

^ array:2 [
  "isbn10" => "0307951529"
  "isbn13" => "9780307951526"
]

However, on the isbns key, when I try to pass one value in Postman instead of two - I get an error that says: array_combine(): Argument #1 ($keys) and argument #2 ($values) must have the same number of elements.  This is because I'm being reliant on array_combine($keysArray, $valuesArray); to do this but I feel like it's not a good approach.

What's a good way to do this so that optionally, one or two semicolon separated values can be accepted so an error won't get thrown?

Note: dd(urldecode($request->fullUrl())); displays the url correctly (provided this detail in case more information is needed).

    $isbn = $request->get('isbns');
    $keysArray = ['isbn10', 'isbn13'];
    $valuesArray = explode(';', $isbn);
    $queryArray = array_combine($keysArray, $valuesArray);

    $queryParams = [
        'api-key' => $apiKey,
        'author' => $author,
        'title' => $title,
        'isbns' => [(object) $queryArray]
    ];

    dd($queryParams);
    // dd(urldecode($request->fullUrl()));

Body:
Assuming you just want to know what to do if only one param is passed in isbn then you can do this

$isbn = '234234;777777';
$keysArray = ['isbn10', 'isbn13'];
$valuesArray = explode(';', $isbn);

foreach($valuesArray as $i=>$val){
    $queryArray[$keysArray[$i]] = $val;
}
print_r($queryArray);

RESULT

Array
(
    [isbn10] => 234234
    [isbn13] => 777777
)

Now if you only pass one param

$isbn = '234234';
$keysArray = ['isbn10', 'isbn13'];
$valuesArray = explode(';', $isbn);

foreach($valuesArray as $i=>$val){
    $queryArray[$keysArray[$i]] = $val;
}
print_r($queryArray);

RESULT

Array
(
    [isbn10] => 234234
)

But this does leave a lot of potential for problems as mentioned in the comments, like is it correct that the single param should be placed in isbn10 and also what happens of there are 3 parameter passed like `123;456;789'


问:
How do I list all of the applications installed on an Android mobile?

Possible Duplicate:

  How to get a list of installed android applications and pick one to run

I have a button. I gave it a click event. Now, I want to list the installed applications on my Android mobile. Is there any possible way to do this using intents? If anyone knows, please tell me.

答: Use PackageManager class's getInstalledApplications() method and take a look at this post.


问:
How to understand VIM configuration noremap <leader>M mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
I find many results on internet using this confiuration to remove ^M. I can understand the substitute command :%s/<C-V><cr>//ge<cr>. But I cannot figure out why mmHmt and 'tzt'm is necessary.

```<code>noremap <leader>M mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
</code>```

答:
```<code>mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
^^................................ create mark m
  ^............................... move the cursor to the top of the window
   ^^............................. create mark t
                          ^^...... move the cursor to mark t
                            ^^.... position the current line at the top of the window
                              ^^.. move the cursor to mark m
</code>```

Creating those marks and jumping back to them after the substitution seems to be an attempt at keeping the cursor in place.

Hints:

The mapping is a normal mode mapping so the commands in the RHS are assumed to be normal command by default.

mmHmt is thus a sequence of normal mode commands, and so is 'tzt'm.

Doing :help m explains mm and mt. It also explains 't and 'm indirectly.

You are left with H: :help H, and zt: :help zt.

See :help m, :help H, :help ', :help zt.

Learning Vim is really easy. It not only allows one to understand random snippets found on the internet but, more importantly, to not need those in the first place.

See :help user-manual.

Body:
I find many results on internet using this confiuration to remove ^M. I can understand the substitute command :%s/<C-V><cr>//ge<cr>. But I cannot figure out why mmHmt and 'tzt'm is necessary.

noremap <leader>M mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm

Body:
mmHmt:%s/<C-V><cr>//ge<cr>'tzt'm
^^................................ create mark m
  ^............................... move the cursor to the top of the window
   ^^............................. create mark t
                          ^^...... move the cursor to mark t
                            ^^.... position the current line at the top of the window
                              ^^.. move the cursor to mark m

Creating those marks and jumping back to them after the substitution seems to be an attempt at keeping the cursor in place.

Hints:

The mapping is a normal mode mapping so the commands in the RHS are assumed to be normal command by default.

mmHmt is thus a sequence of normal mode commands, and so is 'tzt'm.

Doing :help m explains mm and mt. It also explains 't and 'm indirectly.

You are left with H: :help H, and zt: :help zt.

See :help m, :help H, :help ', :help zt.

Learning Vim is really easy. It not only allows one to understand random snippets found on the internet but, more importantly, to not need those in the first place.

See :help user-manual.


问:
How to pass a parameter to a usercontrol in a repeater
I have a usercontroll which accepts some parameter and I need to insert this usercontrol in repeater and pass a parameter from List<> to each one, I'm doing it like this:

```<code><asp:Repeater ID="winnersRepeater" runat="server">
  <ItemTemplate>
    <uc:myControl ID="myControl" NodeId="<%# DataBinder.Eval(Container.DataItem,"Id")%>" runat="server" />
  </ItemTemplate>
</asp:Repeater>
</code>```

I do binding in PageLoad:

```<code>List<Winner> winners = new List<Winner>();
//...
winnersRepeater.DataSource = winners;
winnersRepeater.DataBind();
</code>```

It doesn't work, I'm getting Error creating usercontrol... The server tag is not well formed.

How can I do it? thanks

答: The trick here is with quotes - you are using double quotes both to open and close the NodeId property here, and to enclose the string in the expression. You should use single quotes in one place, and double in the other.</p>

Body:
I have a usercontroll which accepts some parameter and I need to insert this usercontrol in repeater and pass a parameter from List<> to each one, I'm doing it like this:

<asp:Repeater ID="winnersRepeater" runat="server">
  <ItemTemplate>
    <uc:myControl ID="myControl" NodeId="<%# DataBinder.Eval(Container.DataItem,"Id")%>" runat="server" />
  </ItemTemplate>
</asp:Repeater>

I do binding in PageLoad:

List<Winner> winners = new List<Winner>();
//...
winnersRepeater.DataSource = winners;
winnersRepeater.DataBind();

It doesn't work, I'm getting Error creating usercontrol... The server tag is not well formed.

How can I do it? thanks


问:
How to click on element which contains a credit card number that changes each time with Selenium Python
I have a problem to find element on credit card payment form, which contains a number that changes each time, so please help me to find the way to do it.

This is the element:

```<code><input id="adyen-checkout-encryptedCardNumber-1644589302666" data-fieldtype="encryptedCardNumber" type="text" inputmode="numeric" maxlength="24" autocomplete="cc-number" placeholder="1234 5678 9012 3456" aria-label="Champ du numéro de carte" aria-invalid="true" aria-required="true" aria-describedby="adyen-checkout-encryptedCardNumber-1644589302666-ariaError" class="js-iframe-input input-field" data-type="gsf" style="display: block;">
</code>```

答:
Various locator strategies you can use (as per the DOM provided in the query):

All are xpaths

```<code>//input[@data-fieldtype='encryptedCardNumber']

//input[@type='text']

//input[@inputmode='numeric']

//input[@aria-label='Champ du numéro de carte']
</code>```

Body:
I have a problem to find element on credit card payment form, which contains a number that changes each time, so please help me to find the way to do it.

This is the element:

<input id="adyen-checkout-encryptedCardNumber-1644589302666" data-fieldtype="encryptedCardNumber" type="text" inputmode="numeric" maxlength="24" autocomplete="cc-number" placeholder="1234 5678 9012 3456" aria-label="Champ du numéro de carte" aria-invalid="true" aria-required="true" aria-describedby="adyen-checkout-encryptedCardNumber-1644589302666-ariaError" class="js-iframe-input input-field" data-type="gsf" style="display: block;">

Body:
Various locator strategies you can use (as per the DOM provided in the query):

All are xpaths

//input[@data-fieldtype='encryptedCardNumber']

//input[@type='text']

//input[@inputmode='numeric']

//input[@aria-label='Champ du numéro de carte']


问:
Active Storage File Not Found error when trying to use ImageProcessing
I keep getting

```<code>ActiveStorage::FileNotFoundError (ActiveStorage::FileNotFoundError):
app/models/service.rb:24:in `process_images'
</code>```

When trying to load an image into ImageProcessing::MiniMagick using
ImageProcessing::MiniMagick.source(self.image.download)

I have also tried

ImageProcessing::MiniMagick.source(self.image)
ImageProcessing::MiniMagick.source(self.image.attachment)
ImageProcessing::MiniMagick.source(self.image.attachment.download)
ImageProcessing::MiniMagick.source(self.image.blob)

ImageProcessing doesn't like those as its looking for a url so I tried using a url as well like this
url = Rails.application.routes.url_helpers.rails_blob_path(self.image, only_path: true) and passing that in instead of self.image
When I do that I get the error

```<code>failed with error:
convert: unable to open image `rails/active_storage/blobs/foo...`
</code>```

Can someone please steer me in the right direction.

here is the relevant part of my Model as it looks now.

```<code>class Service < ApplicationRecord
  has_one_attached :image, dependent: :destroy
  has_one_attached :featured_image, dependent: :destroy

  after_create :process_images
  after_save :process_images

  private
  def process_images
    url = Rails.application.routes.url_helpers.rails_blob_path(self.image, only_path: true)
    pipeline1 = ImageProcessing::MiniMagick.source(url)
    #can't continue until I load an image
  end
end
</code>```

I have also called the method from the controller. I made the model method not private and called it and it solved the nil attachment issue. The following but then I get this error.
ArgumentError (string contains null byte): flagged at this line.
pipeline1.resize_to_limit(400,400).convert("jpg").call

All I'm trying to do is resize images when the instance is created or updated and then save the processed image as the main attachment.

答:
The issue is probably not related to MiniMagick, but to ActiveStorage. Avoid attaching attachments inside transactions and all will run smooth. This applies to migrations, seeds or callbacks.

What I finally did to avoid my logic being wrapped inside a transaction is to run the logic inside a thread:

Thread.new do
  # your logic here
end.join
```

Body:
I keep getting

ActiveStorage::FileNotFoundError (ActiveStorage::FileNotFoundError):
app/models/service.rb:24:in `process_images'

When trying to load an image into ImageProcessing::MiniMagick using
ImageProcessing::MiniMagick.source(self.image.download)

I have also tried

ImageProcessing::MiniMagick.source(self.image)
ImageProcessing::MiniMagick.source(self.image.attachment)
ImageProcessing::MiniMagick.source(self.image.attachment.download)
ImageProcessing::MiniMagick.source(self.image.blob)

ImageProcessing doesn't like those as its looking for a url so I tried using a url as well like this
url = Rails.application.routes.url_helpers.rails_blob_path(self.image, only_path: true) and passing that in instead of self.image
When I do that I get the error

failed with error:
convert: unable to open image `rails/active_storage/blobs/foo...`

Can someone please steer me in the right direction.

here is the relevant part of my Model as it looks now.

class Service < ApplicationRecord
  has_one_attached :image, dependent: :destroy
  has_one_attached :featured_image, dependent: :destroy

  after_create :process_images
  after_save :process_images

  private
  def process_images
    url = Rails.application.routes.url_helpers.rails_blob_path(self.image, only_path: true)
    pipeline1 = ImageProcessing::MiniMagick.source(url)
    #can't continue until I load an image
  end
end

I have also called the method from the controller. I made the model method not private and called it and it solved the nil attachment issue. The following but then I get this error.
ArgumentError (string contains null byte): flagged at this line.
pipeline1.resize_to_limit(400,400).convert("jpg").call

All I'm trying to do is resize images when the instance is created or updated and then save the processed image as the main attachment.


问:
jquery - Updating and clearing textarea not working when content edited
Can someone please support with the code snippet. There are li items. The button "update" updates the textarea content with defined text (data-text). The text area has 2 buttons that copy and clear the textarea content. What doesn't work is when the text in the textarea is edited: Neither do the "update" buttons work nor the clear button. The "copy" button still works. What needs to be changed in the code?

jQuery(function ($) {

        $('.area_update').click(function () {
            var my_var = $(this).data('text');
            $('#area').html(my_var);
            document.querySelector("textarea").select();
            document.execCommand('copy');
        });

    });

 jQuery(function ($) {

        $('#clear_area').click(function () {
            $('#area').empty();
        });
    });

  document.querySelector("#copy-btn").onclick = function () {
        document.querySelector("textarea").select();
        document.execCommand('copy');
    };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>aaa<input type="button" class="area_update" data-text="zzz" value="update" /></li>
    <li>bbb<input type="button" class="area_update" data-text="yyy" value="update" /></li>
    <li>ccc<input type="button" class="area_update" data-text="xxx" value="update" /></li>
</ul>

<textarea id='area' name='editor'>test</textarea>
<button id="copy-btn">Copy</button>
<button id="clear_area">Clear</button></code>```

答:
To change the content of the textarea you should use .val() instead of .html(). Try this

jQuery(function ($) {
    $('.area_update').click(function () {
        var my_var = $(this).data('text');
        $('#area').val(my_var);
        document.querySelector("textarea").select();
        document.execCommand('copy');
    });
});

jQuery(function ($) {
    $('#clear_area').click(function () {
        $('#area').val('');
    });
});

document.querySelector("#copy-btn").onclick = function () {
    document.querySelector("textarea").select();
    document.execCommand('copy');
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>aaa<input type="button" class="area_update" data-text="zzz" value="update" /></li>
    <li>bbb<input type="button" class="area_update" data-text="yyy" value="update" /></li>
    <li>ccc<input type="button" class="area_update" data-text="xxx" value="update" /></li>
</ul>

<textarea id='area' name='editor'>test</textarea>
<button id="copy-btn">Copy</button>
<button id="clear_area">Clear</button></code>```

Body:
Can someone please support with the code snippet. There are li items. The button "update" updates the textarea content with defined text (data-text). The text area has 2 buttons that copy and clear the textarea content. What doesn't work is when the text in the textarea is edited: Neither do the "update" buttons work nor the clear button. The "copy" button still works. What needs to be changed in the code?

jQuery(function ($) {

        $('.area_update').click(function () {
            var my_var = $(this).data('text');
            $('#area').html(my_var);
            document.querySelector("textarea").select();
            document.execCommand('copy');
        });

    });

 jQuery(function ($) {

        $('#clear_area').click(function () {
            $('#area').empty();
        });
    });

  document.querySelector("#copy-btn").onclick = function () {
        document.querySelector("textarea").select();
        document.execCommand('copy');
    };

aaa<input type="button" class="area_update" data-text="zzz" value="update" />

bbb<input type="button" class="area_update" data-text="yyy" value="update" />

ccc<input type="button" class="area_update" data-text="xxx" value="update" />

<textarea id='area' name='editor'>test</textarea>
<button id="copy-btn">Copy</button>
<button id="clear_area">Clear</button>

Body:
To change the content of the textarea you should use .val() instead of .html(). Try this

jQuery(function ($) {
    $('.area_update').click(function () {
        var my_var = $(this).data('text');
        $('#area').val(my_var);
        document.querySelector("textarea").select();
        document.execCommand('copy');
    });
});

jQuery(function ($) {
    $('#clear_area').click(function () {
        $('#area').val('');
    });
});

document.querySelector("#copy-btn").onclick = function () {
    document.querySelector("textarea").select();
    document.execCommand('copy');
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li>aaa<input type="button" class="area_update" data-text="zzz" value="update" /></li>
    <li>bbb<input type="button" class="area_update" data-text="yyy" value="update" /></li>
    <li>ccc<input type="button" class="area_update" data-text="xxx" value="update" /></li>
</ul>

<textarea id='area' name='editor'>test</textarea>
<button id="copy-btn">Copy</button>
<button id="clear_area">Clear</button>