问:
npm install errors with Error: ENOENT, chmod
I am trying to globally install an npm module I just published. Every time I try to install, either from npm or the folder, I get this error.

```<code>npm ERR! Error: ENOENT, chmod '/usr/local/lib/node_modules/takeapeek/lib/cmd.js'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Linux 3.8.0-19-generic
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "takeapeek"
npm ERR! cwd /home/giodamlio
npm ERR! node -v v0.10.6
npm ERR! npm -v 1.3.6
npm ERR! path /usr/local/lib/node_modules/takeapeek/lib/cmd.js
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/giodamlio/npm-debug.log
npm ERR! not ok code 0
</code>```

I am using sudo and I have triple checked everything in the package everything should work. I did some searching around, and saw a couple of similer cases none of which have been resolved. Here is what I tried.

Upgrade npm (sudo npm install -g npm)

Clear the global npm cache (sudo npm cache clear)

Clear the user npm cache (npm cache clear)

I noticed that the error had to do with the file I am linking to the path, specifically when npm tried to do a chmod. That shouldn't be a problem, my lib/cli.js has normal permissions, and npm has superuser permissions during this install.

After digging through the npm docs I found an option that would stop npm from making the bin links(--no-bin-links), when I tried the install with it, it worked fine.

So what's the deal? Is this some weird fringe case bug that has no solution yet?

Edit: For reference, here is the module I uploaded

答: Solve the problem simply because the modification to the file is locked, or you have locked the permissions on the partition through a specific protection program, and evidence of that is to create the project in another file or another place on the hard drive</p>

Body:
I am trying to globally install an npm module I just published. Every time I try to install, either from npm or the folder, I get this error.

npm ERR! Error: ENOENT, chmod '/usr/local/lib/node_modules/takeapeek/lib/cmd.js'
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <npm-@googlegroups.com>

npm ERR! System Linux 3.8.0-19-generic
npm ERR! command "node" "/usr/local/bin/npm" "install" "-g" "takeapeek"
npm ERR! cwd /home/giodamlio
npm ERR! node -v v0.10.6
npm ERR! npm -v 1.3.6
npm ERR! path /usr/local/lib/node_modules/takeapeek/lib/cmd.js
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/giodamlio/npm-debug.log
npm ERR! not ok code 0

I am using sudo and I have triple checked everything in the package everything should work. I did some searching around, and saw a couple of similer cases none of which have been resolved. Here is what I tried.

Upgrade npm (sudo npm install -g npm)

Clear the global npm cache (sudo npm cache clear)

Clear the user npm cache (npm cache clear)

I noticed that the error had to do with the file I am linking to the path, specifically when npm tried to do a chmod. That shouldn't be a problem, my lib/cli.js has normal permissions, and npm has superuser permissions during this install.

After digging through the npm docs I found an option that would stop npm from making the bin links(--no-bin-links), when I tried the install with it, it worked fine.

So what's the deal? Is this some weird fringe case bug that has no solution yet?

Edit: For reference, here is the module I uploaded


来源: stackexchange

问:
How to add a row to a dataframe modifying only some columns
In order to prepare the data for plotting I need to add a new row to the data:

I have this dataframe:

```<code>df <- data.frame(
  test_id = c(1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1),
  region = c("A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2)
)

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2
</code>```

I would like to add a row to this dataframe so the desired output should be:

```<code>  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75
</code>```

As you can see: column 1 and column 2 are the same value, column 3 changed to 'mean' and column 4 is the mean of row1-4.

I have tried to use add_row from tibble package which gives an error:

```<code>library(dpylr)
library(tibble)

df %>%
  mutate(mean1 = mean(test_value)) %>%
  add_row(test_id = test_id[1], test_nr=test_nr[1],region="mean", test_value=mean(test_value))

Error in eval_tidy(xs[[j]], mask) : object 'test_id' not found
</code>```

答:
Coming in with a base R approach, you can build off of an existing row and then rbind to row bind two objects.

```<code># save a new vector from any row you like
row_to_add <- df[1,]

# alter the values want one at a time
row_to_add$region <- "mean"
row_to_add$test_value <- mean(df$test_value)

# OR alter them at once if you prefer...
row_to_add[,c("region","test_value")] <- c("mean",mean(df$test_value))

# finally use rbind to add to the bottom of the data.frame
rbind(df,row_to_add)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In order to prepare the data for plotting I need to add a new row to the data:

I have this dataframe:

df <- data.frame(
  test_id = c(1, 1, 1, 1),
  test_nr = c(1, 1, 1, 1),
  region = c("A", "B", "C", "D"),
  test_value = c(3, 1, 1, 2)
)

  test_id test_nr region test_value
1       1       1      A          3
2       1       1      B          1
3       1       1      C          1
4       1       1      D          2

I would like to add a row to this dataframe so the desired output should be:

  test_id test_nr region test_value
1       1       1      A       3.00
2       1       1      B       1.00
3       1       1      C       1.00
4       1       1      D       2.00
5       1       1   mean       1.75

As you can see: column 1 and column 2 are the same value, column 3 changed to 'mean' and column 4 is the mean of row1-4.

I have tried to use add_row from tibble package which gives an error:

library(dpylr)
library(tibble)

df %>%
  mutate(mean1 = mean(test_value)) %>%
  add_row(test_id = test_id[1], test_nr=test_nr[1],region="mean", test_value=mean(test_value))

Error in eval_tidy(xs[[j]], mask) : object 'test_id' not found

Body:
Coming in with a base R approach, you can build off of an existing row and then rbind to row bind two objects.

# save a new vector from any row you like
row_to_add <- df[1,]

# alter the values want one at a time
row_to_add$region <- "mean"
row_to_add$test_value <- mean(df$test_value)

# OR alter them at once if you prefer...
row_to_add[,c("region","test_value")] <- c("mean",mean(df$test_value))

# finally use rbind to add to the bottom of the data.frame
rbind(df,row_to_add)


问:
repeater-type control for asp.net mvc 3
is there any sort of control for .net mvc 3 (some html helper method perhaps) that works like an asp:repeater?

I've done some googling and only found some home grown solutions.

Here's what I need:
My users will have a drop down list of numbers, depending what they select (1-8), I need to repeat a set of code below to offer them the same list of input fields (between 1 and 8 times).

what would be the best way to accomplish this with mvc 3 and jquery?

答:
You should use jquery templates for this

I copy-pasted some code from a project I'm currently working on, but I think you get the picture how you can solve your problem with jquery templates.

You can put the templates in a partialview. For example:

```<code><input type="hidden" id="productId" value="${ProductId}"/>
<div class="formElement">
    <label>@Globalization.Workorders.Domainname</label>
    <input type="text" id="domainname" name="domainname" />
</div>
<div class="formElement">
    <label>@Globalization.Workorders.StartDate</label>
    <input type="text" id="startDate" value=""/>
</div>
<input type="submit" id="addHostingProduct" value="@Globalization.Workorders.Add"/>
<input type="button" id="addHostingProductCancel" value="@Globalization.Workorders.Cancel"/>
</code>```

The template takes a json object or an array of json objects to render. The ${...} are replaced with values from the json.

I usually put the partialviews/templates in the view like this:

```<code><script id="AddHostingProductTemplate" type="text/x-jquery-tmpl">
    @Html.Partial("Templates/AddHostingProduct")
</script>
</code>```

When you're page first loads, you can do something like this, to set the initial values:

```<code><script type="text/javascript">
    $(document).ready(function() {
        @foreach (var workOrderLine in Model.WorkOrderLines)
        {
            <text>
                  $('#AddHostingProductTemplate').tmpl(@workOrderLine.ToJson()).appendTo("#products")
            </text>
        }

     });
</script>
</code>```

The ToJson method is a method I put on the viewmodel, it just serializes the viewmodel into a json string.

When a user clicks a button or changes the dropdown, it's easy to use the template in your client side code to render the extra templates. Just use:

```<code>$('#AddHostingProductTemplate').tmpl({ someValue: '1', someOtherValue : ' test' }).appendTo("#products")
</code>```

Hope this helps

ContentLicense: CC BY-SA 3.0

Title: repeater-type control for asp.net mvc 3

Body:
You should use jquery templates for this

I copy-pasted some code from a project I'm currently working on, but I think you get the picture how you can solve your problem with jquery templates.

You can put the templates in a partialview. For example:

<input type="hidden" id="productId" value="${ProductId}"/>
<div class="formElement">
    <label>@Globalization.Workorders.Domainname</label>
    <input type="text" id="domainname" name="domainname" />
</div>
<div class="formElement">
    <label>@Globalization.Workorders.StartDate</label>
    <input type="text" id="startDate" value=""/>
</div>
<input type="submit" id="addHostingProduct" value="@Globalization.Workorders.Add"/>
<input type="button" id="addHostingProductCancel" value="@Globalization.Workorders.Cancel"/>

The template takes a json object or an array of json objects to render. The ${...} are replaced with values from the json.

I usually put the partialviews/templates in the view like this:

<script id="AddHostingProductTemplate" type="text/x-jquery-tmpl">
    @Html.Partial("Templates/AddHostingProduct")
</script>

When you're page first loads, you can do something like this, to set the initial values:

<script type="text/javascript">
    $(document).ready(function() {
        @foreach (var workOrderLine in Model.WorkOrderLines)
        {
            <text>
                  $('#AddHostingProductTemplate').tmpl(@workOrderLine.ToJson()).appendTo("#products")
            </text>
        }

     });
</script>

The ToJson method is a method I put on the viewmodel, it just serializes the viewmodel into a json string.

When a user clicks a button or changes the dropdown, it's easy to use the template in your client side code to render the extra templates. Just use:

$('#AddHostingProductTemplate').tmpl({ someValue: '1', someOtherValue : ' test' }).appendTo("#products")

Hope this helps


问:
npm install throwing error in node-sass
```<code>node-sass@2.1.1 install /home/user/Documents/project/node_modules/node-sass
> node scripts/install.js

WARN invalid config loglevel="notice"
Can not download file from https://raw.githubusercontent.com/sass/node-sass-binaries/v2.1.1/linux-x64-node-8.2/binding.node

> node-sass@2.1.1 postinstall /home/user/Documents/project/node_modules/node-sass
> node scripts/build.js

module.js:487
    throw err;
    ^

Error: Cannot find module '/home/user/Documents/project/node_modules/node-sass/node_modules/pangyp/bin/node-gyp'
    at Function.Module._resolveFilename (module.js:485:15)
    at Function.Module._load (module.js:437:25)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3
Build failed
added 2186 packages in 42.166s
</code>```

I tried so far:

npm rebuild

npm rebuild node-sass

npm uninstall -g node-sass

rm -rf node_module

答:
Remove 'node-sass' dependency from your package.json

run npm install

run npm i sass

run npm start

You're ready to go! :)

Title: npm install throwing error in node-sass

Body:
node-sass@2.1.1 install /home/user/Documents/project/node_modules/node-sass
> node scripts/install.js

WARN invalid config loglevel="notice"
Can not download file from https://raw.githubusercontent.com/sass/node-sass-binaries/v2.1.1/linux-x64-node-8.2/binding.node

> node-sass@2.1.1 postinstall /home/user/Documents/project/node_modules/node-sass
> node scripts/build.js

module.js:487
    throw err;
    ^

Error: Cannot find module '/home/user/Documents/project/node_modules/node-sass/node_modules/pangyp/bin/node-gyp'
    at Function.Module._resolveFilename (module.js:485:15)
    at Function.Module._load (module.js:437:25)
    at Function.Module.runMain (module.js:605:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3
Build failed
added 2186 packages in 42.166s

I tried so far:

npm rebuild

npm rebuild node-sass

npm uninstall -g node-sass

rm -rf node_module


问:
Error while trying to create react app using npm
I'm trying to creating react app using create-react-app command but I get this error message:

```<code>npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! errno ERR_SOCKET_TIMEOUT
npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/dotenv-expand: Socket timeout
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\IMAD\AppData\Local\npm-cache\_logs\2022-02-12T18_27_46_293Z-debug-0.log
</code>```

I tried to clean cache:

```<code>npm cache clean -f
</code>```

I also tried restarting the computer and reinstall nodejs and npm, but nothing was fixed.

Can anyone know what is the issue? and how can I solve it?

答:
You should use npx command (not npm) like that as in official documentation :  https://reactjs.org/docs/create-a-new-react-app.html</p>
```<code>npx create-react-app my-app
</code>```

Body:
I'm trying to creating react app using create-react-app command but I get this error message:

npm ERR! code ERR_SOCKET_TIMEOUT
npm ERR! errno ERR_SOCKET_TIMEOUT
npm ERR! network Invalid response body while trying to fetch https://registry.npmjs.org/dotenv-expand: Socket timeout
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\IMAD\AppData\Local\npm-cache\_logs\2022-02-12T18_27_46_293Z-debug-0.log

I tried to clean cache:

npm cache clean -f

I also tried restarting the computer and reinstall nodejs and npm, but nothing was fixed.

Can anyone know what is the issue? and how can I solve it?

Body:
You should use npx command (not npm) like that as in official documentation :  https://reactjs.org/docs/create-a-new-react-app.html

npx create-react-app my-app


问:
Counting all descendants in a family tree (python dictionary)
I'm kind of beating my head against a wall here and I'm hoping that someone on stackoverflow can help me.
Let's say I have a python dictionary that looks like:

```<code>{
    'Son1': 'Father',
    'Son2': 'Father',
    'Father': 'Grandfather',
    'Grandfather': 'Great Grandfather',
    'Uncle': 'Grandfather',
    'Cousin': 'Uncle',
}
</code>```

Right, so each key is a person and the corresponding value is that person's parent. All I want to do at the moment is find out how many total descendants a given person has.
I've got a pretty simple function that finds and returns a list of a given person's immediate children.

```<code>def get_kids(person, dictionary):
    kids = []
    for key in dictionary:
        if dictionary[key] == person:
            kids.append(key)
    return kids
</code>```

Which works fine. From there, I keep thinking that all I need to do is write a recursive function that's something like:

```<code>def descendants(person, dictionary, count):
    kids = get_kids(person, dictionary)
    count = count + len(kids)
    for kid in kids:
         descendants(kid, dictionary, count)
    return count
</code>```

But this doesn't work. I think because the 'count' variable resets at the end of a 'line' of descendants, instead of being a running total. e.g. If I run:

```<code>descendants('Grandfather', familydictionary, 0)
</code>```

I get back a value of 2 (instead of the hoped-for 5). Presumably, the count reaches 4 when the function is exploring the 'Father' line, but then drops back down to 3 when it explores the 'Uncle' line, instead. And then, I suppose, the count drops all the way back to 2 when the function finds that 'Cousin' has no kids?
I often struggle with these kinds of recursion problems. What I want to do is pretty straightforward: check if a person has kids and count them, check if their kids have kids and count them, add them to the total ... keep going until there are no more kids. But I get very muddled when I try to actually, well, write the code that does that.
Any help or guidance is appreciated.

答:
You can use treelib to achieve your desired result using the library's methods. Recursive functions are a great way to traverse a tree structure but it is very useful to have a good foundation for them to work on. Depending on what other functions you will be building, treelib can come in very handy indeed to avoid reinventing the wheel and losing time in the process. Especially if what you're working on is a family tree.

Treelib can be installed by pip install treelib.

Code

```<code>>>> from treelib import Tree
>>> family = Tree()
>>> family.create_node("Great Grandfather", "Great Grandfather")  # root node
>>> family.create_node("Grandfather", "Grandfather", parent="Great Grandfather")
>>> family.create_node("Uncle", "Uncle", parent="Grandfather")
>>> family.create_node("Father", "Father", parent="Grandfather")
>>> family.create_node("Cousin", "Cousin", parent="Uncle")
>>> family.create_node("Son1", "Son1", parent="Father")
>>> family.create_node("Son2", "Son2", parent="Father")

>>> family.show() # tree.show() prints the tree in human-readable format

Great Grandfather
└── Grandfather
    ├── Father
    │   ├── Son1
    │   └── Son2
    └── Uncle
        └── Cousin

>>> def descendants(person, tree):
...     person_family = tree.subtree(person) # Create a subtree starting with person.
...     return person_family.size() - 1 # Subtracting 1 for Great Grandfather because tree.size() returns the total number of nodes in a tree.

>>> person = "Great Grandfather"
>>> print("{person} has {desc} descendants.".format(person=person, desc=descendants(person, family)))
Great Grandfather has 6 descendants.

>>> person = "Grandfather"
>>> print("{person} has {desc} descendants.".format(person=person, desc=descendants(person, family)))
Grandfather has 5 descendants.

>>> person = "Father"
>>> print("{person} has {desc} descendants.".format(person=person, desc=descendants(person, family)))
Father has 2 descendants.
</code>```

Body:
I'm kind of beating my head against a wall here and I'm hoping that someone on stackoverflow can help me.
Let's say I have a python dictionary that looks like:

{
    'Son1': 'Father',
    'Son2': 'Father',
    'Father': 'Grandfather',
    'Grandfather': 'Great Grandfather',
    'Uncle': 'Grandfather',
    'Cousin': 'Uncle',
}

Right, so each key is a person and the corresponding value is that person's parent. All I want to do at the moment is find out how many total descendants a given person has.
I've got a pretty simple function that finds and returns a list of a given person's immediate children.

def get_kids(person, dictionary):
    kids = []
    for key in dictionary:
        if dictionary[key] == person:
            kids.append(key)
    return kids

Which works fine. From there, I keep thinking that all I need to do is write a recursive function that's something like:

def descendants(person, dictionary, count):
    kids = get_kids(person, dictionary)
    count = count + len(kids)
    for kid in kids:
         descendants(kid, dictionary, count)
    return count

But this doesn't work. I think because the 'count' variable resets at the end of a 'line' of descendants, instead of being a running total. e.g. If I run:

descendants('Grandfather', familydictionary, 0)

I get back a value of 2 (instead of the hoped-for 5). Presumably, the count reaches 4 when the function is exploring the 'Father' line, but then drops back down to 3 when it explores the 'Uncle' line, instead. And then, I suppose, the count drops all the way back to 2 when the function finds that 'Cousin' has no kids?
I often struggle with these kinds of recursion problems. What I want to do is pretty straightforward: check if a person has kids and count them, check if their kids have kids and count them, add them to the total ... keep going until there are no more kids. But I get very muddled when I try to actually, well, write the code that does that.
Any help or guidance is appreciated.

Body:
You can use treelib to achieve your desired result using the library's methods. Recursive functions are a great way to traverse a tree structure but it is very useful to have a good foundation for them to work on. Depending on what other functions you will be building, treelib can come in very handy indeed to avoid reinventing the wheel and losing time in the process. Especially if what you're working on is a family tree.

Treelib can be installed by pip install treelib.

Code

>>> from treelib import Tree
>>> family = Tree()
>>> family.create_node("Great Grandfather", "Great Grandfather")  # root node
>>> family.create_node("Grandfather", "Grandfather", parent="Great Grandfather")
>>> family.create_node("Uncle", "Uncle", parent="Grandfather")
>>> family.create_node("Father", "Father", parent="Grandfather")
>>> family.create_node("Cousin", "Cousin", parent="Uncle")
>>> family.create_node("Son1", "Son1", parent="Father")
>>> family.create_node("Son2", "Son2", parent="Father")

>>> family.show() # tree.show() prints the tree in human-readable format

Great Grandfather
└── Grandfather
    ├── Father
    │   ├── Son1
    │   └── Son2
    └── Uncle
        └── Cousin

>>> def descendants(person, tree):
...     person_family = tree.subtree(person) # Create a subtree starting with person.
...     return person_family.size() - 1 # Subtracting 1 for Great Grandfather because tree.size() returns the total number of nodes in a tree.

>>> person = "Great Grandfather"
>>> print("{person} has {desc} descendants.".format(person=person, desc=descendants(person, family)))
Great Grandfather has 6 descendants.

>>> person = "Grandfather"
>>> print("{person} has {desc} descendants.".format(person=person, desc=descendants(person, family)))
Grandfather has 5 descendants.

>>> person = "Father"
>>> print("{person} has {desc} descendants.".format(person=person, desc=descendants(person, family)))
Father has 2 descendants.


问:
#line keyword in C
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

```<code>char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"
</code>```

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.

答:
This is done so that the line number changes.

This is done in order to show the line numbers of the Lex input file, for example, in error messages and warnings. Because Lex generates C code, without #line directives compile errors and warnings wouldn't be of any value.

Title: #line keyword in C

Body:
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.


问:
Remove ViewPager2 Overscroll animation
Can't find a way to remove the ViewPager2 overscroll shadow animation.
I know on ViewPager, you can directly just set the overscrollMode attribute to never, however, it does not work on ViewPager2

Already tried the following

```<code><androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
    android:layout_height="match_parent"
        android:overScrollMode="never"/>
</code>```

```<code>binding.viewPager.apply {
        adapter = adapter
        orientation = ViewPager2.ORIENTATION_VERTICAL
        overScrollMode = ViewPager2.OVER_SCROLL_NEVER
        offscreenPageLimit = if (containsVideo) 2 else 5
}
</code>```

答:
Use             android:overScrollMode="never"</p>
```<code> <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/infoViewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:overScrollMode="never"
        app:layout_constraintBottom_toTopOf="@id/guideLine1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        />
</code>```

Title: Remove ViewPager2 Overscroll animation

Body:
Can't find a way to remove the ViewPager2 overscroll shadow animation.
I know on ViewPager, you can directly just set the overscrollMode attribute to never, however, it does not work on ViewPager2

Already tried the following

<androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
    android:layout_height="match_parent"
        android:overScrollMode="never"/>

binding.viewPager.apply {
        adapter = adapter
        orientation = ViewPager2.ORIENTATION_VERTICAL
        overScrollMode = ViewPager2.OVER_SCROLL_NEVER
        offscreenPageLimit = if (containsVideo) 2 else 5
}

Body:
Use             android:overScrollMode="never"

 <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/infoViewPager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:overScrollMode="never"
        app:layout_constraintBottom_toTopOf="@id/guideLine1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        />


问:
Request Focus on TextField in jetpack compose
How to auto focus on textfield in jetpack compose. When i click on textfield and start typing on it. Meantime when i click back button,then when i'm try to click on textfield, nothing happens.

val textState = remember { mutableStateOf(TextFieldValue()) }
TextField(
    modifier = Modifier.fillMaxWidth(),
    value = textState.value,
    onValueChange = { value : TextFieldValue ->
        textState.value = value
    }
)
```

答:
    @Composable fun SomeComposable() {
        val focusRequester = remember { FocusRequester() }

    OutlinedTextField(
        value = TextFieldValue(
        text = state.text, // state come from else where
        selection = TextRange(state.text.length,state.text.length)),

        onValueChange = { _:TextFieldValue -> Unit },
        modifier = Modifier
          .fillMaxWidth()
          .focusRequester(focusRequester),)

    SideEffect {
        focusRequester.requestFocus()
        }
    }

```

Why SideEffect: the very first line of the docs.

For the Cursor Position this answer helped.
onValueChanged is left as is in my working code, I have no need for it.

Body:
    @Composable fun SomeComposable() {
        val focusRequester = remember { FocusRequester() }

    OutlinedTextField(
        value = TextFieldValue(
        text = state.text, // state come from else where
        selection = TextRange(state.text.length,state.text.length)),

        onValueChange = { _:TextFieldValue -> Unit },
        modifier = Modifier
          .fillMaxWidth()
          .focusRequester(focusRequester),)

    SideEffect {
        focusRequester.requestFocus()
        }
    }

Why SideEffect: the very first line of the docs.

For the Cursor Position this answer helped.
onValueChanged is left as is in my working code, I have no need for it.


问:
Counting adjacent -1s in a 2d array for a given row/column without checking positions out of bounds
Need help figuring out a different way to write count(), it's something that will add to my code here:

```<code>public class Grid
{
    private int [][] array;
    private int max;

    public Grid(int max)
    {
        array = new int[10][10];
        this.max = max;
        setRandom();

    }

    public void setRandom()
    {
        int i = 0;
        while(i < max)
        {
            int r = (int)(Math.random() * 9) + 0;
            int c = (int)(Math.random() * 9) + 0;
            if(array[r][c] != -1)
                {
                    array[r][c] = -1;
                    i++;
                }
        }
    }

    public void print()
    {
        for(int r = 0; r < array.length; r++)
        {
            for(int c = 0; c < array[r].length; c++)
            {
                System.out.print(array[r][c] + " ");
            }
                System.out.println();
        }
    }

    public int count(int row, int col)
    {
    // method here
    }

    public static void main(String[] args)
    {
        Grid a = new Grid(20);
        a.count(5, 5);
        a.print();
    }
}
</code>```

I want count() to return the number of -1s found in the 2d array surrounding the input position, and it also must not check a position "outside the bounds" (more specifically, the positions that aren't adjacent for a given row/column). Essentially it's like Minesweeper in a sense: let's say I pass in count(5, 5) (5 being the row and column respectively), it will check all adjacent positions surrounding (5, 5).

In this case, the highlighted blue is the position being checked and the yellow are adjacent positions. The white area is out of bounds and won't be checked. The position (5, 5) gets a value of 3 since there are 3 -1's surrounding the position. Visual here: https://imgur.com/a/0KCZdne

I came up with this code:

```<code>    public int count(int row, int col)
        {
            int value = 0;
            for(int r = -1; r < 2; r++)
            {
                for(int c = -1; c < 2; c++)
                {
                    if(c == 0 & r == 0)
                        continue;
                    if(array[row + r][col + c] == -1)
                    {
                        value++;
                    }
                }
            }
            return value;
        }
</code>```

but when I pass in a.count(4, 7) in main(), nothing happens to the grid and it stays the same. I also want to find a different way to go about this without using continue
This is the output:

```<code>0 0 -1 -1 0 -1 0 0 0 0
-1 0 0 -1 -1 0 -1 0 0 0
0 0 0 0 0 0 0 0 -1 0
0 0 0 0 0 0 0 0 0 0
-1 0 -1 0 0 0 0 -1 -1 0
0 0 -1 -1 0 0 0 0 0 0
0 0 -1 0 -1 0 0 0 -1 0
0 0 -1 0 0 0 0 -1 0 0
0 0 -1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
</code>```

and I want my expected output to look something like this (if I passed in a.count(4, 7) - 4 being the row, 7 being the column)

```<code>0 0 -1 -1 0 -1 0 0 0 0
-1 0 0 -1 -1 0 -1 0 0 0
0 0 0 0 0 0 0 0 -1 0
0 0 0 0 0 0 0 0 0 0
-1 0 -1 0 0 0 0 -1 -1 0
0 0 -1 -1 0 0 0 0 0 0
0 0 -1 0 -1 0 0 0 -1 0
0 0 -1 **4** 0 0 0 -1 0 0
0 0 -1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
</code>```

(the 4 is the value in the position I passed in - since there are 4 -1s surrounding it, (3, 7) has a value of 4)

答:
You should check both the indices of row and column that you are trying to access is valid or not
Just add a check to prevent ArrayIndexOutOfBoundsException.

public int count(int row, int col) {
        int value = 0;
        for(int r = -1; r < 2; r++) {
            for(int c = -1; c < 2; c++) {
                if(c == 0 & r == 0)
                        continue;
                int newR = row + r;
                int newC = col + c;

                if(newR < 0 || newR >= array.length || newC < 0 || newC >= array[0].length)
                    continue;

                if(array[newR][newC] == -1)
                    value++;
            }
        }
        return value;
    }
```
<p><strong>This is what I could come up with to avoid continue</strong></p>
<pre class="lang-java prettyprint-override"><code>     public int count(int row, int col) {
        int value = 0;
        value += isValidIndex(row - 1, col - 1)? array[row - 1][col - 1]: 0;
        value += isValidIndex(row - 1, col)? array[row - 1][col]: 0;
        value += isValidIndex(row - 1, col + 1)? array[row - 1][col + 1]: 0;
        value += isValidIndex(row, col - 1)? array[row][col - 1]: 0;
        value += isValidIndex(row, col + 1)? array[row][col + 1]: 0;
        value += isValidIndex(row + 1, col - 1)? array[row + 1][col - 1]: 0;
        value += isValidIndex(row + 1, col)? array[row + 1][col]: 0;
        value += isValidIndex(row + 1, col + 1)? array[row + 1][col + 1]: 0;
        return -value;
    }

    public boolean isValidIndex(int row, int col) {
        return !(row < 0 || col < 0 || row >= array.length || col >= array[0].length);
    }
</code>```

Body:
Need help figuring out a different way to write count(), it's something that will add to my code here:

public class Grid
{
    private int [][] array;
    private int max;

    public Grid(int max)
    {
        array = new int[10][10];
        this.max = max;
        setRandom();

    }

    public void setRandom()
    {
        int i = 0;
        while(i < max)
        {
            int r = (int)(Math.random() * 9) + 0;
            int c = (int)(Math.random() * 9) + 0;
            if(array[r][c] != -1)
                {
                    array[r][c] = -1;
                    i++;
                }
        }
    }

    public void print()
    {
        for(int r = 0; r < array.length; r++)
        {
            for(int c = 0; c < array[r].length; c++)
            {
                System.out.print(array[r][c] + " ");
            }
                System.out.println();
        }
    }

    public int count(int row, int col)
    {
    // method here
    }

    public static void main(String[] args)
    {
        Grid a = new Grid(20);
        a.count(5, 5);
        a.print();
    }
}

I want count() to return the number of -1s found in the 2d array surrounding the input position, and it also must not check a position "outside the bounds" (more specifically, the positions that aren't adjacent for a given row/column). Essentially it's like Minesweeper in a sense: let's say I pass in count(5, 5) (5 being the row and column respectively), it will check all adjacent positions surrounding (5, 5).

In this case, the highlighted blue is the position being checked and the yellow are adjacent positions. The white area is out of bounds and won't be checked. The position (5, 5) gets a value of 3 since there are 3 -1's surrounding the position. Visual here: https://imgur.com/a/0KCZdne

I came up with this code:

    public int count(int row, int col)
        {
            int value = 0;
            for(int r = -1; r < 2; r++)
            {
                for(int c = -1; c < 2; c++)
                {
                    if(c == 0 & r == 0)
                        continue;
                    if(array[row + r][col + c] == -1)
                    {
                        value++;
                    }
                }
            }
            return value;
        }

but when I pass in a.count(4, 7) in main(), nothing happens to the grid and it stays the same. I also want to find a different way to go about this without using continue
This is the output:

0 0 -1 -1 0 -1 0 0 0 0
-1 0 0 -1 -1 0 -1 0 0 0
0 0 0 0 0 0 0 0 -1 0
0 0 0 0 0 0 0 0 0 0
-1 0 -1 0 0 0 0 -1 -1 0
0 0 -1 -1 0 0 0 0 0 0
0 0 -1 0 -1 0 0 0 -1 0
0 0 -1 0 0 0 0 -1 0 0
0 0 -1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

and I want my expected output to look something like this (if I passed in a.count(4, 7) - 4 being the row, 7 being the column)

0 0 -1 -1 0 -1 0 0 0 0
-1 0 0 -1 -1 0 -1 0 0 0
0 0 0 0 0 0 0 0 -1 0
0 0 0 0 0 0 0 0 0 0
-1 0 -1 0 0 0 0 -1 -1 0
0 0 -1 -1 0 0 0 0 0 0
0 0 -1 0 -1 0 0 0 -1 0
0 0 -1 **4** 0 0 0 -1 0 0
0 0 -1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

(the 4 is the value in the position I passed in - since there are 4 -1s surrounding it, (3, 7) has a value of 4)

Body:
You should check both the indices of row and column that you are trying to access is valid or not
Just add a check to prevent ArrayIndexOutOfBoundsException.

public int count(int row, int col) {
        int value = 0;
        for(int r = -1; r < 2; r++) {
            for(int c = -1; c < 2; c++) {
                if(c == 0 & r == 0)
                        continue;
                int newR = row + r;
                int newC = col + c;

                if(newR < 0 || newR >= array.length || newC < 0 || newC >= array[0].length)
                    continue;

                if(array[newR][newC] == -1)
                    value++;
            }
        }
        return value;
    }

This is what I could come up with to avoid continue

     public int count(int row, int col) {
        int value = 0;
        value += isValidIndex(row - 1, col - 1)? array[row - 1][col - 1]: 0;
        value += isValidIndex(row - 1, col)? array[row - 1][col]: 0;
        value += isValidIndex(row - 1, col + 1)? array[row - 1][col + 1]: 0;
        value += isValidIndex(row, col - 1)? array[row][col - 1]: 0;
        value += isValidIndex(row, col + 1)? array[row][col + 1]: 0;
        value += isValidIndex(row + 1, col - 1)? array[row + 1][col - 1]: 0;
        value += isValidIndex(row + 1, col)? array[row + 1][col]: 0;
        value += isValidIndex(row + 1, col + 1)? array[row + 1][col + 1]: 0;
        return -value;
    }

    public boolean isValidIndex(int row, int col) {
        return !(row < 0 || col < 0 || row >= array.length || col >= array[0].length);
    }


问:
Histogram of string in C
I need to find how many times letters appear in string. But I need to ignore the difference between lowercase and uppercase letters.

```<code>#include <stdio.h>
#include <string.h>
void stringHistogram(char *s) {
  int i, len = 0, counts[256] = {0};
  len = strlen(s);
  for (i = 0; i < len; i++) {
    counts[(s[i])]++;
  }
  for (i = 65; i < 123; i++) {
      if(i>=91&&i<=96)continue;
    if (counts[i] > 0)
       printf("%c occurs %d times.\n", i, counts[i]);
  }
}
int main() {
  char s[] = "!!!!!PrOgraMMing -------iN C Is easy....";
  stringHistogram(s);

  return 0;
}
</code>```

For example in this string "I" appears once and "i" appears twice. I want to add these two numbers and print number of them as one character. Program output should be "I appears 3 times."
Could you help me modify these code?

答:
You do not need to use strlen and then iterate the string again. Use the correct type for sizes.

```<code>void stringHistogram(const char *s)
{
    size_t counts[256] = {0};

    while(*s) counts[toupper((unsigned char)*s++)] += 1;

    for(size_t i = 0; i < sizeof(counts) / sizeof(counts[0]); i++)
        if (counts[i] > 0)
            printf("%3zu (`%c`) occurs %zu times.\n", i, isprint((unsigned char)i) ? (char)i : '.', counts[i]);
}
</code>```

Title: Histogram of string in C

Body:
I need to find how many times letters appear in string. But I need to ignore the difference between lowercase and uppercase letters.

#include <stdio.h>
#include <string.h>
void stringHistogram(char *s) {
  int i, len = 0, counts[256] = {0};
  len = strlen(s);
  for (i = 0; i < len; i++) {
    counts[(s[i])]++;
  }
  for (i = 65; i < 123; i++) {
      if(i>=91&&i<=96)continue;
    if (counts[i] > 0)
       printf("%c occurs %d times.\n", i, counts[i]);
  }
}
int main() {
  char s[] = "!!!!!PrOgraMMing -------iN C Is easy....";
  stringHistogram(s);

  return 0;
}

For example in this string "I" appears once and "i" appears twice. I want to add these two numbers and print number of them as one character. Program output should be "I appears 3 times."
Could you help me modify these code?

Body:
You do not need to use strlen and then iterate the string again. Use the correct type for sizes.

void stringHistogram(const char *s)
{
    size_t counts[256] = {0};

    while(*s) counts[toupper((unsigned char)*s++)] += 1;

    for(size_t i = 0; i < sizeof(counts) / sizeof(counts[0]); i++)
        if (counts[i] > 0)
            printf("%3zu (`%c`) occurs %zu times.\n", i, isprint((unsigned char)i) ? (char)i : '.', counts[i]);
}


问:
Unable to cast PersistentGenericBag to ISet exception
I am getting this exception:

Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag`1[System.Int64]'</code> to type <code>'System.Collections.Generic.ISet`1[System.Int64]'

I use:

```<code>public virtual ISet<long> Ids { get; set; }
</code>```

I am not doing any explicit mapping here using FNH.

答: NHibernate does not support NET4 ISet out of the box. You need to add this package.</p>

Body:
I am getting this exception:

Unable to cast object of type 'NHibernate.Collection.Generic.PersistentGenericBag`1[System.Int64]'</code> to type <code>'System.Collections.Generic.ISet`1[System.Int64]'

I use:

public virtual ISet<long> Ids { get; set; }

I am not doing any explicit mapping here using FNH.


问:
Django - How to only allow staff users to see their own posts in admin panel
I have a model called listings and I want staff users to only be able to view, edit, delete listings in the admin panel that they created. Currently staff users can view edit and delete all of the listings

here is my listings/admin.py

```<code>from django.contrib import admin

from .models import Listing

class ListingAdmin(admin.ModelAdmin):

    list_display =('id','Full_Name','Is_Published','Town_Or_City','District','Region','List_Date')
    list_display_links = ('id','Full_Name')
    list_editable = ('Is_Published',)
    search_fields = ('Full_Name','Town_Or_City','District','Region',)

admin.site.register(Listing, ListingAdmin)
</code>```

here is my listings/models.py

```<code>from django.db import models
from datetime import datetime
from FuneralHomes.models import FuneralHome

class Listing(models.Model):
    index = models.ForeignKey(index, on_delete=models.DO_NOTHING,blank=True)
    Full_Name = models.CharField(max_length=200)
    First_Name = models.CharField(max_length=200)
    Last_Name = models.CharField(max_length=200)
    Nee = models.CharField(max_length=200, blank=True)
    Town_Or_City = models.CharField(max_length=200)
    District = models.CharField(max_length=200, blank=True)
    Region = models.CharField(max_length=200)
    List_Date = models.DateField(max_length=200)
    Photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
    Is_Published = models.BooleanField(default=True)
    List_Date = models.DateTimeField(default=datetime.now, blank=True)
    def __str__(self):
        return self.Full_Name
</code>```

答:
The admin panel really isn't the place for things like this (as explained in the first paragraph of the Django documentation).

A quick a dirty way of accomplishing what you're trying to do is probably overriding the delete method for this model to check if the user created it. For only listing the user's posts you could utilize the Manager class. Finally, to handle editing, you would have to override the save method to see if it already exists and if the user created it.

Body:
I have a model called listings and I want staff users to only be able to view, edit, delete listings in the admin panel that they created. Currently staff users can view edit and delete all of the listings

here is my listings/admin.py

from django.contrib import admin

from .models import Listing

class ListingAdmin(admin.ModelAdmin):

    list_display =('id','Full_Name','Is_Published','Town_Or_City','District','Region','List_Date')
    list_display_links = ('id','Full_Name')
    list_editable = ('Is_Published',)
    search_fields = ('Full_Name','Town_Or_City','District','Region',)

admin.site.register(Listing, ListingAdmin)

here is my listings/models.py

from django.db import models
from datetime import datetime
from FuneralHomes.models import FuneralHome

class Listing(models.Model):
    index = models.ForeignKey(index, on_delete=models.DO_NOTHING,blank=True)
    Full_Name = models.CharField(max_length=200)
    First_Name = models.CharField(max_length=200)
    Last_Name = models.CharField(max_length=200)
    Nee = models.CharField(max_length=200, blank=True)
    Town_Or_City = models.CharField(max_length=200)
    District = models.CharField(max_length=200, blank=True)
    Region = models.CharField(max_length=200)
    List_Date = models.DateField(max_length=200)
    Photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
    Is_Published = models.BooleanField(default=True)
    List_Date = models.DateTimeField(default=datetime.now, blank=True)
    def __str__(self):
        return self.Full_Name


问:
Try Except Python, functions doesnt get read?
i am a beginner with python and i have the following problem.I want to create a code that takes 3 inputs separated by comma but at the same time these inputs must be int,str,int/float .I have created a function(check) that returns True if those creteria are met.nevertheless it seems that when i insert this line inside the 'try' ,nothing happens.So i can get a answer 10 for the name.</p>
```<code>    while True:

        try:
            aa, name, note = [x for x in input("insert the following aa,name,note :\n").split(',')]
            check(aa,name,note )==True

        except:
            print("Please insert the data with the following format : aa,name,note")
            continue

        else:
            break
</code>```

答:
as been said earlier this is not a great practice to just leave except blank. also you can just use  because you're using bool function, but if you really want to use exceptions you can try this;

while True:

        try:
            aa, name, note = [x for x in input("insert the following aa,name,note :\n").split(',')]
            assert(check(aa,name,note)) # assert will throw exception if argument is False

        except:
            print("Please insert the data with the following format : aa,name,note")
            continue

        else:
            break

```

Body:
i am a beginner with python and i have the following problem.I want to create a code that takes 3 inputs separated by comma but at the same time these inputs must be int,str,int/float .I have created a function(check) that returns True if those creteria are met.nevertheless it seems that when i insert this line inside the 'try' ,nothing happens.So i can get a answer 10 for the name.

    while True:

        try:
            aa, name, note = [x for x in input("insert the following aa,name,note :\n").split(',')]
            check(aa,name,note )==True

        except:
            print("Please insert the data with the following format : aa,name,note")
            continue

        else:
            break


问:
Automatically hide rows with empty cells in predefined column - only hides non-empty cells
I currently have the following script but in contrast to my expectations it only hides the rows with non-empty cells in column F and keeps the one with empty cells unhidden...what is wrong? ==="" is correct right?

```<code>var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange(6,6,274,1);
</code>```
```<code>function onOpen() {
{

    //get the values to those rows
    var values = range.getValues();

    //go through every row
    for (var i=0; i<values.length; i++){

        //if row value is equal to empty
        if(values[i][0] === ""){

        //hide that row
        sheet.hideRows(i+1);
        }
    }
}

</code>```

Also, is there a way to do this whole thing in multiple sheets but with different ranges without having to completely multiplying the whole script with different variables? I am quite new to AppScript and the "for every i" is still something I do not understand how it works...Thank you so much for your help!

Edit: Can I also add another
if(values[i][0] > "") { sheet.showRows(i+1)}; to check for changes in the rows and unhide them again?

答:
```<code>function onOpen() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getActiveSheet();
  const vs = sh.getRange(6, 6, 274, 1).getValues().flat();
  vs.forEach((e,i) => {if(!e)sh.hideRows(i + 6);});
}
</code>```

Body:
I currently have the following script but in contrast to my expectations it only hides the rows with non-empty cells in column F and keeps the one with empty cells unhidden...what is wrong? ==="" is correct right?

var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange(6,6,274,1);

function onOpen() {
{

    //get the values to those rows
    var values = range.getValues();

    //go through every row
    for (var i=0; i<values.length; i++){

        //if row value is equal to empty
        if(values[i][0] === ""){

        //hide that row
        sheet.hideRows(i+1);
        }
    }
}

Also, is there a way to do this whole thing in multiple sheets but with different ranges without having to completely multiplying the whole script with different variables? I am quite new to AppScript and the "for every i" is still something I do not understand how it works...Thank you so much for your help!

Edit: Can I also add another
if(values[i][0] > "") { sheet.showRows(i+1)}; to check for changes in the rows and unhide them again?


问:
Converting PyTorch transforms.compose method into Keras
I understand that we use transforms.compose to transform images via torch.transforms. I want to do the same in Keras  and spending hours on internet I couldnt get how to write a method in keras that can do the same. Below is the Torch way:

```<code># preprocessing
data_transform = transforms.Compose([
   transforms.ToTensor(),
   transforms.Normalize(mean=[.5], std=[.5])
])
</code>```

Can someone please point me in the right direction.

答:
It is a bit trivial in Tensorflow. Tensorflow recommends using the pre-processing/augmentation as part of the model itself.

I do not have your complete code but I assume you would be using tf.data.Dataset API to create your dataset. This is the recommended way of building the dataset in Tensorflow.

Having said that you can just prepend augmentation layers in your model.

```<code># Following is the pre-processing pipeline for e.g
# Step 1: Image resizing.
# Step 2: Image rescaling.
# Step 3: Image normalization

# Having Data Augmentation as part of the input pipeline.
# Step 1: Random flip.
# Step 2: Random Rotate.

pre_processing_pipeline = tf.keras.Sequential([
  layers.Resizing(IMG_SIZE, IMG_SIZE),
  layers.Rescaling(1./255),
  layers.Normalization(mean=[.5], variance=[.5]),
])

data_augmentation = tf.keras.Sequential([
  layers.RandomFlip("horizontal_and_vertical"),
  layers.RandomRotation(0.2),
])

# Then add it to your model.
# This would be different in your case as you might be using a pre-trained model.

model = tf.keras.Sequential([
  # Add the preprocessing layers you created earlier.
  resize_and_rescale,
  data_augmentation,
  layers.Conv2D(16, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  # Rest of your model.
])
</code>```

For a complete list of layers check out this link. The above-given code can be found on the website here.

Body:
I understand that we use transforms.compose to transform images via torch.transforms. I want to do the same in Keras  and spending hours on internet I couldnt get how to write a method in keras that can do the same. Below is the Torch way:

# preprocessing
data_transform = transforms.Compose([
   transforms.ToTensor(),
   transforms.Normalize(mean=[.5], std=[.5])
])

Can someone please point me in the right direction.

Body:
It is a bit trivial in Tensorflow. Tensorflow recommends using the pre-processing/augmentation as part of the model itself.

I do not have your complete code but I assume you would be using tf.data.Dataset API to create your dataset. This is the recommended way of building the dataset in Tensorflow.

Having said that you can just prepend augmentation layers in your model.

# Following is the pre-processing pipeline for e.g
# Step 1: Image resizing.
# Step 2: Image rescaling.
# Step 3: Image normalization

# Having Data Augmentation as part of the input pipeline.
# Step 1: Random flip.
# Step 2: Random Rotate.

pre_processing_pipeline = tf.keras.Sequential([
  layers.Resizing(IMG_SIZE, IMG_SIZE),
  layers.Rescaling(1./255),
  layers.Normalization(mean=[.5], variance=[.5]),
])

data_augmentation = tf.keras.Sequential([
  layers.RandomFlip("horizontal_and_vertical"),
  layers.RandomRotation(0.2),
])

# Then add it to your model.
# This would be different in your case as you might be using a pre-trained model.

model = tf.keras.Sequential([
  # Add the preprocessing layers you created earlier.
  resize_and_rescale,
  data_augmentation,
  layers.Conv2D(16, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  # Rest of your model.
])

For a complete list of layers check out this link. The above-given code can be found on the website here.


问:
AttributeError: 'list' object has no attribute 'click' using find_element(By.Xpath) Selenium and Python
There was a change to the find_element_by_xpath() to find_element(By.Xpath) and now the click is not working.

Code trials:

```<code>search_btn = self.driver.find_elements(
    By.XPATH, "//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]").click()
time.sleep(4)
search_btn.click()
time.sleep(5)
</code>```

Error:

```<code>DevTools listening on ws://127.0.0.1:52534/devtools/browser/5aafde31-7b7e-456f-9639-cdfa2bb70678
[16904:17532:0211/180317.139:ERROR:chrome_browser_main_extra_parts_metrics.cc(227)] START: ReportBluetoothAvailability(). If you don't see the END: message, this is crbug.com/1216328.
[16904:17532:0211/180317.140:ERROR:chrome_browser_main_extra_parts_metrics.cc(230)] END: ReportBluetoothAvailability()
[16904:17532:0211/180317.140:ERROR:chrome_browser_main_extra_parts_metrics.cc(235)] START: GetDefaultBrowser(). If you don't see the END: message, this is crbug.com/1216328.
[16904:12228:0211/180317.149:ERROR:device_event_log_impl.cc(214)] [18:03:17.148] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[16904:12228:0211/180317.157:ERROR:device_event_log_impl.cc(214)] [18:03:17.157] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[16904:17532:0211/180317.159:ERROR:chrome_browser_main_extra_parts_metrics.cc(239)] END: GetDefaultBrowser()
Traceback (most recent call last):
  File "C:\!!!Angela\Paid screen scraper\data scraping\data scraping\my_ui_scrapy12.py", line 278, in show_page
    By.XPATH, "//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]").click()
AttributeError: 'list' object has no attribute 'click'
 c:\data scraping\data scraping> [22108:16084:0211/180503.560:ERROR:gpu_init.cc(454)] Passthrough is not supported, GL is disabled, ANGLE is
</code>```

答:
find_elements()

find_elements() find elements and returns a list, given a By strategy and locator.

So this line of code:

```<code>search_btn = self.driver.find_elements( By.XPATH, "//[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]")
</code>```

would return a list and list has no method as click(). Hence the next line:

```<code>search_btn.click()
</code>```

raises the error:

```<code>AttributeError: 'list' object has no attribute 'click'
</code>```

Solution

Replace find_elements() with find_element() you would be good to go.

Body:
There was a change to the find_element_by_xpath() to find_element(By.Xpath) and now the click is not working.

Code trials:

search_btn = self.driver.find_elements(
    By.XPATH, "//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]").click()
time.sleep(4)
search_btn.click()
time.sleep(5)

Error:

DevTools listening on ws://127.0.0.1:52534/devtools/browser/5aafde31-7b7e-456f-9639-cdfa2bb70678
[16904:17532:0211/180317.139:ERROR:chrome_browser_main_extra_parts_metrics.cc(227)] START: ReportBluetoothAvailability(). If you don't see the END: message, this is crbug.com/1216328.
[16904:17532:0211/180317.140:ERROR:chrome_browser_main_extra_parts_metrics.cc(230)] END: ReportBluetoothAvailability()
[16904:17532:0211/180317.140:ERROR:chrome_browser_main_extra_parts_metrics.cc(235)] START: GetDefaultBrowser(). If you don't see the END: message, this is crbug.com/1216328.
[16904:12228:0211/180317.149:ERROR:device_event_log_impl.cc(214)] [18:03:17.148] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[16904:12228:0211/180317.157:ERROR:device_event_log_impl.cc(214)] [18:03:17.157] USB: usb_device_handle_win.cc:1049 Failed to read descriptor from node connection: A device attached to the system is not functioning. (0x1F)
[16904:17532:0211/180317.159:ERROR:chrome_browser_main_extra_parts_metrics.cc(239)] END: GetDefaultBrowser()
Traceback (most recent call last):
  File "C:\!!!Angela\Paid screen scraper\data scraping\data scraping\my_ui_scrapy12.py", line 278, in show_page
    By.XPATH, "//*[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]").click()
AttributeError: 'list' object has no attribute 'click'
 c:\data scraping\data scraping> [22108:16084:0211/180503.560:ERROR:gpu_init.cc(454)] Passthrough is not supported, GL is disabled, ANGLE is

Body:
find_elements()

find_elements() find elements and returns a list, given a By strategy and locator.

So this line of code:

search_btn = self.driver.find_elements( By.XPATH, "//[@id='viewContainer']/app-listing-container/app-search-container/app-search-form-container/form/div[3]/button[2]")

would return a list and list has no method as click(). Hence the next line:

search_btn.click()

raises the error:

AttributeError: 'list' object has no attribute 'click'

Solution

Replace find_elements() with find_element() you would be good to go.


问:
R: Return a vector using %in% operator
I have a vector with delimiters and I want to generate a vector of the same length with boolean values based on whether or not one of the delimited values contains what I am after. I cannot find a way to do this neatly in vector-based logic. As an example:

```<code>x <- c('a', 'a; b', 'ab; c', 'b; c', 'c; a', 'c')
</code>```

Using some magic asking whether 'a' %in% x, I want to get the vector:

```<code>TRUE, TRUE, FALSE, FALSE, TRUE, FALSE
</code>```

I initially tried the following:

```<code>'a' %in% trimws(strsplit(x, ';'))
</code>```

But this unexpectedly collapses the entire list and returns TRUE, rather than a vector, since one of the elements in x is 'a'. Is there a way to get the vector I am looking for without rewriting the code into a for-loop?

答:
Update: To consider white spaces:

```<code>library(stringr)
x <- str_replace_all(string=x, pattern=" ", repl="")
x
[1] "a"    "a;b"  "ab;c" "b;c"  "c;a"  "c"

str_detect(x, 'a$|a;')
</code>```
```<code>[1]  TRUE  TRUE FALSE FALSE  TRUE FALSE
</code>```

First answer:
If you want to use str_detect we have to account on a + delimiter ;:

```<code>library(stringr)
str_detect(x, 'a$|a;')
</code>```
```<code>[1]  TRUE  TRUE FALSE FALSE  TRUE FALSE
</code>```

Title: R: Return a vector using %in% operator

Body:
I have a vector with delimiters and I want to generate a vector of the same length with boolean values based on whether or not one of the delimited values contains what I am after. I cannot find a way to do this neatly in vector-based logic. As an example:

x <- c('a', 'a; b', 'ab; c', 'b; c', 'c; a', 'c')

Using some magic asking whether 'a' %in% x, I want to get the vector:

TRUE, TRUE, FALSE, FALSE, TRUE, FALSE

I initially tried the following:

'a' %in% trimws(strsplit(x, ';'))

But this unexpectedly collapses the entire list and returns TRUE, rather than a vector, since one of the elements in x is 'a'. Is there a way to get the vector I am looking for without rewriting the code into a for-loop?

Body:
Update: To consider white spaces:

library(stringr)
x <- str_replace_all(string=x, pattern=" ", repl="")
x
[1] "a"    "a;b"  "ab;c" "b;c"  "c;a"  "c"

str_detect(x, 'a$|a;')

[1]  TRUE  TRUE FALSE FALSE  TRUE FALSE

First answer:
If you want to use str_detect we have to account on a + delimiter ;:

library(stringr)
str_detect(x, 'a$|a;')

[1]  TRUE  TRUE FALSE FALSE  TRUE FALSE


问:
Reset field in Django Admin page
Imagine, that I have model and in the Django admin form I can update my fields. I want to implement something like: update one field and the second one will be reset in admin form in real time (I'll hope it can help real admin in the future do not forget redefine this second field,  because it's very important in my situation). Is that possible to implement something like that without custom admin form?</p>

答:
To achieve this without a custom template or form, you can just include a custom script, for example:

Assuming you have an app named people and it has a model called Person with two fields first_name and last_name:

Include javascript into the admin page

# people/admin.py

from django.contrib import admin
from people.models import Person

class PersonAdmin(admin.ModelAdmin):
    class Media:
        js = ('people/js/person.js',)

admin.site.register(Person, PersonAdmin)
```
<p>Then create the <code>person/js/person.js</code> script:</p>
<pre class="lang-js prettyprint-override"><code>'use strict';

//execute when everything is loaded
window.addEventListener('load', () => {
    let first_field = document.querySelector('form input[name=first_name]'); //field name
    let second_field = document.querySelector('form input[name=last_name]'); //field name

    //just when the fields are found (add or update)
    if(first_field && second_field) {
        //here you can implement whatever logic you want
        first_field.addEventListener('input', () => {
            second_field.value = '';
        });
    }
});
</code>```

Now every time the first_name changes last_name will be cleared. This idea can be extended to do more interesting things.

Title: Reset field in Django Admin page

Body:
To achieve this without a custom template or form, you can just include a custom script, for example:

Assuming you have an app named people and it has a model called Person with two fields first_name and last_name:

Include javascript into the admin page

# people/admin.py

from django.contrib import admin
from people.models import Person

class PersonAdmin(admin.ModelAdmin):
    class Media:
        js = ('people/js/person.js',)

admin.site.register(Person, PersonAdmin)

Then create the person/js/person.js script:

'use strict';

//execute when everything is loaded
window.addEventListener('load', () => {
    let first_field = document.querySelector('form input[name=first_name]'); //field name
    let second_field = document.querySelector('form input[name=last_name]'); //field name

    //just when the fields are found (add or update)
    if(first_field && second_field) {
        //here you can implement whatever logic you want
        first_field.addEventListener('input', () => {
            second_field.value = '';
        });
    }
});

Now every time the first_name changes last_name will be cleared. This idea can be extended to do more interesting things.