来源: stackexchange

问:
How to handle redirect for login_required in htmx partial view?
I have two views.

class IndexView(TemplateView):
    template_name = 'index.html'

@require_POST
@login_required
def partial_view(request):
    return render(request, 'partials/stuff.html')
```

I want the index page to be "public" but if user takes action (which triggers partial view), they should be redirected to LOGIN_URL, if not logged in.

The problem is that my partial view will return the entire LOGIN_URL page. So there's a page within a page now.

Is it possible to redirect the "parent" page when using partial views?

答:
I didn't manage to make "post-login redirection" work but my solution is good enough for my needs.

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.conf import settings
from django.contrib.auth.decorators import login_required as django_login_required
from django.http import HttpResponse
from functools import wraps

from django.shortcuts import resolve_url

def login_required(function=None, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    @wraps(function)
    def wrapper(request, *args, **kwargs):
        if not request.user.is_authenticated and request.htmx:
            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)
            return HttpResponse(status=204, headers={'HX-Redirect': resolved_login_url})
        return django_login_required(
            function=function,
            login_url=login_url,
            redirect_field_name=redirect_field_name
        )(request, *args, **kwargs)
    return wrapper

```

ContentLicense: CC BY-SA 4.0

Body:
I have two views.

class IndexView(TemplateView):
    template_name = 'index.html'

@require_POST
@login_required
def partial_view(request):
    return render(request, 'partials/stuff.html')

I want the index page to be "public" but if user takes action (which triggers partial view), they should be redirected to LOGIN_URL, if not logged in.

The problem is that my partial view will return the entire LOGIN_URL page. So there's a page within a page now.

Is it possible to redirect the "parent" page when using partial views?


问:
Move "Cursor" of readObject (Stop reading the same object)
There are 3 objects in the "or" file. The loop returns the same object over and over again and I do not know how to tell the readObject() to move onto the next object.

```<code>import java.io.*;
import java.util.*;

public class Mainclass {
    public static void main(String[] args) {

        int l = 1;

        while (l > 0) {

            try {

                InputStream is = new FileInputStream("or.rtf");
                ObjectInputStream ois = new ObjectInputStream(is);
                Stone p = (Stone) ois.readObject();
                System.out.println(p);
                ois.close();

            }   catch(Exception e) {
                    if(e instanceof EOFException) {
                        l--;
                        System.err.println();
                    } else if(e instanceof FileNotFoundException) {
                        l--;
                        System.err.println(e);
                    } else {
                        System.err.println(e);
                    }
            }
        }
    }
}
</code>```

EDIT: New code looks like this:

```<code>import java.io.*;
import java.util.*;

public class Mainclass {
    public static void main(String[] args) {

        InputStream is;
        try {
            is = new FileInputStream("or.rtf");

            ObjectInputStream ois;
            try {
                ois = new ObjectInputStream(is);

                int l = 1;
                while (l > 0) {

                    try {

                        Stone p = (Stone) ois.readObject();
                        System.out.println(p);
                        ois.close();

                    }   catch(Exception e) {
                            if(e instanceof EOFException) {
                                l--;
                                System.err.println();
                            } else if(e instanceof FileNotFoundException) {
                                l--;
                                System.err.println(e);
                            } else {
                                System.err.println(e);
                            }
                    }
                }

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

</code>```

Now I get an IOException right from the start (Stream closed). I tried incorporating the advice given by moving the InputStream out of the loop and implementing the code for correct data into the "try" branches.

答: You need to create only one InputStream and call the readObject() inside a while loop.

Body:
There are 3 objects in the "or" file. The loop returns the same object over and over again and I do not know how to tell the readObject() to move onto the next object.

import java.io.*;
import java.util.*;

public class Mainclass {
    public static void main(String[] args) {

        int l = 1;

        while (l > 0) {

            try {

                InputStream is = new FileInputStream("or.rtf");
                ObjectInputStream ois = new ObjectInputStream(is);
                Stone p = (Stone) ois.readObject();
                System.out.println(p);
                ois.close();

            }   catch(Exception e) {
                    if(e instanceof EOFException) {
                        l--;
                        System.err.println();
                    } else if(e instanceof FileNotFoundException) {
                        l--;
                        System.err.println(e);
                    } else {
                        System.err.println(e);
                    }
            }
        }
    }
}

EDIT: New code looks like this:

import java.io.*;
import java.util.*;

public class Mainclass {
    public static void main(String[] args) {

        InputStream is;
        try {
            is = new FileInputStream("or.rtf");

            ObjectInputStream ois;
            try {
                ois = new ObjectInputStream(is);

                int l = 1;
                while (l > 0) {

                    try {

                        Stone p = (Stone) ois.readObject();
                        System.out.println(p);
                        ois.close();

                    }   catch(Exception e) {
                            if(e instanceof EOFException) {
                                l--;
                                System.err.println();
                            } else if(e instanceof FileNotFoundException) {
                                l--;
                                System.err.println(e);
                            } else {
                                System.err.println(e);
                            }
                    }
                }

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

Now I get an IOException right from the start (Stream closed). I tried incorporating the advice given by moving the InputStream out of the loop and implementing the code for correct data into the "try" branches.


问:
Show TS6133 (declared but never read) as warning instead of error
Previously when working on react projects using typescript, there are instances where I would declare a variable without reading it and it would notify about it as a warning on console. VSCode would also notify via a yellow squiggly line.

On the project I am working on, Unused variables are displayed as errors which 'breaks' the app. I would like that unused variables be notified as a warning and not an error.

Some of the things tried include modifying tsconfig.json.

```<code>{
    "noUnusedLocals": false,
    "noUnusedParameters": false,
}
</code>```

While this notifies me of unused variables in the console, and doesn't 'break' the app, VSCode doesn't notify of unused variables.

tsconfig.json

```<code>{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true
  },
  "include": ["src"]
}

</code>```

.eslintrc.json

```<code>{
  "root": true,
  "extends": ["react-app", "react-app/jest"],
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "rules": {
    "@typescript-eslint/no-unused-vars": ["warning"]
  }
}
</code>```

package.json

```<code>{
  "name": "project",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.3",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/styles": "^4.11.3",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "material-ui-image": "^3.3.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 0"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/jest": "^26.0.20",
    "@types/node": "^14.14.31",
    "@types/react": "^17.0.2",
    "@types/react-dom": "^17.0.1",
    "@types/react-router-dom": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.15.2",
    "@typescript-eslint/parser": "^4.15.2",
    "eslint": "^7.20.0",
    "prettier": "2.2.1"
  }
}

</code>```

Error Message:

```<code>D:/path/to/project/src/components/ThemeProvider.tsx
TypeScript error in D:/path/to/project/src/components/ThemeProvider.tsx(23,7):
'someVariable' is declared but its value is never read.  TS6133

    21 |   },
    22 | });
  > 23 | const someVariable = {};
       |       ^
    24 |
    25 | const ThemeProvider = ({ children }: { children: ReactNode }) => {
    26 |   return <MUIThemeProvider {...{ theme }}>{children}</MUIThemeProvider>;
</code>```

答:
Creating a .env file solved the issue for me. These are the variables I set in the .env

```<code>TSC_COMPILE_ON_ERROR=true
ESLINT_NO_DEV_ERRORS=true
</code>```

More info can be found in cra's documentation

Body:
Previously when working on react projects using typescript, there are instances where I would declare a variable without reading it and it would notify about it as a warning on console. VSCode would also notify via a yellow squiggly line.

On the project I am working on, Unused variables are displayed as errors which 'breaks' the app. I would like that unused variables be notified as a warning and not an error.

Some of the things tried include modifying tsconfig.json.

{
    "noUnusedLocals": false,
    "noUnusedParameters": false,
}

While this notifies me of unused variables in the console, and doesn't 'break' the app, VSCode doesn't notify of unused variables.

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true
  },
  "include": ["src"]
}

.eslintrc.json

{
  "root": true,
  "extends": ["react-app", "react-app/jest"],
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "rules": {
    "@typescript-eslint/no-unused-vars": ["warning"]
  }
}

package.json

{
  "name": "project",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.3",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/styles": "^4.11.3",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "material-ui-image": "^3.3.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 0"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/jest": "^26.0.20",
    "@types/node": "^14.14.31",
    "@types/react": "^17.0.2",
    "@types/react-dom": "^17.0.1",
    "@types/react-router-dom": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.15.2",
    "@typescript-eslint/parser": "^4.15.2",
    "eslint": "^7.20.0",
    "prettier": "2.2.1"
  }
}

Error Message:

D:/path/to/project/src/components/ThemeProvider.tsx
TypeScript error in D:/path/to/project/src/components/ThemeProvider.tsx(23,7):
'someVariable' is declared but its value is never read.  TS6133

    21 |   },
    22 | });
  > 23 | const someVariable = {};
       |       ^
    24 |
    25 | const ThemeProvider = ({ children }: { children: ReactNode }) => {
    26 |   return <MUIThemeProvider {...{ theme }}>{children}</MUIThemeProvider>;

Body:
Creating a .env file solved the issue for me. These are the variables I set in the .env

TSC_COMPILE_ON_ERROR=true
ESLINT_NO_DEV_ERRORS=true

More info can be found in cra's documentation


问:
cp: cannot create regular file '/home/Documents': Permission denied
I am learning linux CLI, I created a file app.txt in home directory. Now I am copying it through CLI to Documents and it is showing me an error:

```<code>cp: cannot create regular file '/home/Documents': Permission denied
</code>```

P.S (I have checked whoami and it is showing zain which is my root)

Can anyone confirm what is wrong with it ?

答:
give 777 (readable, writable and executable) permissions to file or directory</p>
```<code>sudo chmod -R 777 /folder-location
</code>```

Body:
I am learning linux CLI, I created a file app.txt in home directory. Now I am copying it through CLI to Documents and it is showing me an error:

cp: cannot create regular file '/home/Documents': Permission denied

P.S (I have checked whoami and it is showing zain which is my root)

Can anyone confirm what is wrong with it ?

Body:
give 777 (readable, writable and executable) permissions to file or directory

sudo chmod -R 777 /folder-location


问:
SQLite - DB Browser
How can I use SQL to calculate Feet and inches from a column that gives the Height value?

Example
Height = 65
I need to transform into Feet and inches, by dividing 65/12 = 5 feet 42 inches.
I am new, so What is the function that I need to use?

Thanks

答:
You can use division and modulo. Most SQL dialects have a concatenation function or operator:

```<code>select Concat(65/12, ' feet ', 65 % 12, ' inches')
</code>```

5 feet 5 inches

Title: SQLite - DB Browser

Body:
You can use division and modulo. Most SQL dialects have a concatenation function or operator:

select Concat(65/12, ' feet ', 65 % 12, ' inches')

5 feet 5 inches


问:
How to find the most frequent letters and the number of occurrences, using Stream API?
I have List with single letters inside. I need to count all duplicates and find the most frequent duplicate. The list generates randomly, so it may contain several most frequent letters.

Is it possible to create only one map inside one Stream or put the second map inside Stream? I need only one Stream chain, using the method groupingBy().

```<code>public static void mostFrequentlyDuplicateLetters(List<String> letters) {
     Map<String, Long> collect = letterList
            .stream()
            .collect(Collectors.groupingBy(String::valueOf, Collectors.counting()))
            .entrySet()
            .stream()
            .filter(// How to find the most frequent letters and put them on a map?))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        }
</code>```

答:
First of all what you need as your return type is actually Map.Entry, not the whole Map, since you just want an entry with highest number of occurrences.

You can try this way:

   public Map.Entry<String,Long> mostFrequentlyDuplicateLetters(List<String> letterList){
        return letterList
                .stream()
                .collect(Collectors.groupingBy(String::valueOf, Collectors.counting()))
                .entrySet()
                .stream().max(Map.Entry.comparingByValue())
                .get();
    }

```

Body:
I have List with single letters inside. I need to count all duplicates and find the most frequent duplicate. The list generates randomly, so it may contain several most frequent letters.

Is it possible to create only one map inside one Stream or put the second map inside Stream? I need only one Stream chain, using the method groupingBy().

public static void mostFrequentlyDuplicateLetters(List<String> letters) {
     Map<String, Long> collect = letterList
            .stream()
            .collect(Collectors.groupingBy(String::valueOf, Collectors.counting()))
            .entrySet()
            .stream()
            .filter(// How to find the most frequent letters and put them on a map?))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        }


问:
x-cache: Miss from cloudfront in AWS
I am serving images from s3 via CloudFront. when I inspect I am still getting a message x-cache: Miss from CloudFront It would be great if someone could assist how to configure it in the right way so images would server from CloudFront cache.

答:
Amazon CloudFront is a 'pull-through cache'. This means that there is initially nothing in the cache.

It works like this:

A user requests a resource (eg HTML page or an image) via a CloudFront URL

The request is sent to a nearby CloudFront edge location

The edge location checks its local cache -- if the requested resource is found, it is returned to the user ('Hit')

Otherwise, it forwards the request to a regional cache -- if the requested resource is found, it is returned to the edge location, which stores it in its local cache. The resource is then returned to the user.

If the resource was not found in the regional cache, the request is forwarded to the Origin, which returns the resource. It is then stored in the regional cache and returned to the edge location, which stores it and returns it to the user.

Therefore, items are only stored in the cache when they are first requested. Plus, they are only stored in the edge location that was accessed by the user. So, if a user in Paris requests the resource, it will be stored in their edge location. But, when a user in Auckland requests the same resource, it will not be in their local cache until it is accessed by a nearby user.

Items remain in the cache for a period of time based on the recency of requests and the size of the object. CloudFront has very big caches -- they even cache Prime Video movies!

So, the answer to your question about how to configure CloudFront to serve images from the cache is that there is nothing to configure -- it will be done automatically when a resource is first requested. Just run your command again and you'll see that it was a 'Hit' from the cache.

Title: x-cache: Miss from cloudfront in AWS


问:
pyscreenshot as ImageGrab doesn't work after compiling with PyInstaller to exe
When I use the code normally before compiling it works perfectly but when compiling to .exe with cxfreeze or pyinstaller and running the software freezes</p>
```<code>import pyscreenshot as ImageGrab
import threading

def wprint():
    print("Wprint")
    global tempimg
    imagem = ImageGrab.grab()
    tempimg = imagem
    print("End Wprint")

x = threading.Thread(target=wprint)
x.start()
</code>```

答:
If we turn on logging, we can see that the module works by spawning a process to run PIL in

DEBUG:pyscreenshot.loader:running "pil" in child process
DEBUG:easyprocess:command: ['C:\\Users\\user\\.virtualenvs\\random\\Scripts\\python.exe', '-m', 'pyscreenshot.cli.grab', '--filename', 'C:\\Users\\user\\AppData\\Local\\Temp\\pyscreenshotbza0zwqm\\screenshot.png', '--backend', 'pil', '--debug']
DEBUG:easyprocess:process was started (pid=29996)
Wprint
DEBUG:easyprocess:process has ended, return code=0
DEBUG:easyprocess:stdout=
DEBUG:easyprocess:stderr=
DEBUG:PIL.PngImagePlugin:STREAM b'IHDR' 16 13
DEBUG:PIL.PngImagePlugin:STREAM b'IDAT' 41 65536
End Wprint
```

When you package your application, it'll try to run the new process against your generated exe as the interpreter (the first argument above), but your script doesn't handle anything from the arguments so it's just started again, which spawn an another process, and this will repeat until your resources are exhausted or until you terminate it.

The pypi home page of the pyscreenshot package mentions that it's mostly obsolete as PIL (pillow) now properly handles what it tried to initially solve, and it appears that it wasn't necessary on your platform. So you can also give pillow's ImageGrab a try directly which should have a normal Python API.

The pyscreenshot module is obsolete in most cases. It was created because PIL ImageGrab module worked on Windows only, but now Linux and macOS are also supported. There are some features in pyscreenshot which can be useful in special cases: flexible backends, Wayland support, sometimes better performance, optional subprocessing.

Body:
When I use the code normally before compiling it works perfectly but when compiling to .exe with cxfreeze or pyinstaller and running the software freezes

import pyscreenshot as ImageGrab
import threading

def wprint():
    print("Wprint")
    global tempimg
    imagem = ImageGrab.grab()
    tempimg = imagem
    print("End Wprint")

x = threading.Thread(target=wprint)
x.start()

Body:
If we turn on logging, we can see that the module works by spawning a process to run PIL in

DEBUG:pyscreenshot.loader:running "pil" in child process
DEBUG:easyprocess:command: ['C:\\Users\\user\\.virtualenvs\\random\\Scripts\\python.exe', '-m', 'pyscreenshot.cli.grab', '--filename', 'C:\\Users\\user\\AppData\\Local\\Temp\\pyscreenshotbza0zwqm\\screenshot.png', '--backend', 'pil', '--debug']
DEBUG:easyprocess:process was started (pid=29996)
Wprint
DEBUG:easyprocess:process has ended, return code=0
DEBUG:easyprocess:stdout=
DEBUG:easyprocess:stderr=
DEBUG:PIL.PngImagePlugin:STREAM b'IHDR' 16 13
DEBUG:PIL.PngImagePlugin:STREAM b'IDAT' 41 65536
End Wprint

When you package your application, it'll try to run the new process against your generated exe as the interpreter (the first argument above), but your script doesn't handle anything from the arguments so it's just started again, which spawn an another process, and this will repeat until your resources are exhausted or until you terminate it.

The pypi home page of the pyscreenshot package mentions that it's mostly obsolete as PIL (pillow) now properly handles what it tried to initially solve, and it appears that it wasn't necessary on your platform. So you can also give pillow's ImageGrab a try directly which should have a normal Python API.

The pyscreenshot module is obsolete in most cases. It was created because PIL ImageGrab module worked on Windows only, but now Linux and macOS are also supported. There are some features in pyscreenshot which can be useful in special cases: flexible backends, Wayland support, sometimes better performance, optional subprocessing.


问:
Why would cv2.COLOR_RGB2GRAY and cv2.COLOR_BGR2GRAY give different results?
I always thought that converting an image from colored to grayscale is simple: intensity of each pixel would be an average of intensities of each color channel. But I noticed that cv2.COLOR_RGB2GRAY and cv2.COLOR_BGR2GRAY give different results. When I was experimenting with them I also found that it would also be  different from the average of intensities of each color channel.

P.S. I was completely baffled when I found that

```<code>img_read_as_color[:,:,0]/3+img_read_as_color[:,:,1]/3+img_read_as_color[:,:,2]/3 == (img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2])/3
</code>```

but when shown as immage

```<code>(img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2])/3
</code>```

would look like

```<code>img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2]
</code>```

Can someone explain to me why this is happening?

My full code:

```<code>import matplotlib.pyplot as plt
import cv2

sample = r'G:\Python\knight-mare\screenshots\2020-07-12-02-40-44.jpg'
img_read_as_grayscale = cv2.imread(sample, cv2.IMREAD_GRAYSCALE)
img_read_as_color = cv2.imread(sample, cv2.IMREAD_COLOR)
img_RGB_to_grayscale = cv2.cvtColor(img_read_as_color, cv2.COLOR_RGB2GRAY)
img_BGR_to_grayscale = cv2.cvtColor(img_read_as_color, cv2.COLOR_BGR2GRAY)
plt.imshow(img_read_as_grayscale)
plt.title('img_read_as_grayscale')
plt.show()
plt.imshow(img_read_as_color)
plt.title('img_read_as_color')
plt.show()
plt.imshow(img_RGB_to_grayscale)
plt.title('img_RGB_to_grayscale')
plt.show()
plt.imshow(img_BGR_to_grayscale)
plt.title('img_BGR_to_grayscale')
plt.show()

channel_avg_div_separately = img_read_as_color[:,:,0]/3+img_read_as_color[:,:,1]/3+img_read_as_color[:,:,2]/3
channel_avg_div_together = (img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2])/3
channel_sum = img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2]
plt.imshow(channel_avg_div_separately)
plt.title('channel_avg_div_separately')
plt.show()
plt.imshow(channel_avg_div_together)
plt.title('channel_avg_div_together')
plt.show()
plt.imshow(channel_sum)
plt.title('channel_sum')
plt.show()
</code>```

答:
I think the problem is with the MatPlotLib .imshow() method.  In my experiments both:

```<code>img_read_as_grayscale = cv2.imread(sample, cv2.IMREAD_GRAYSCALE)
</code>```

and

```<code>img_BGR_to_grayscale = cv2.cvtColor(img_read_as_color, cv2.COLOR_BGR2GRAY)
</code>```

will be properly displayed as a grayscale image when using cv2.imshow()
but will be displayed with a weird blue and green color with plt.imshow().

You can fix this by specifying cmap='gray'

```<code>plt.imshow(img_BGR_to_grayscale, cmap='gray')
</code>```

Body:
I always thought that converting an image from colored to grayscale is simple: intensity of each pixel would be an average of intensities of each color channel. But I noticed that cv2.COLOR_RGB2GRAY and cv2.COLOR_BGR2GRAY give different results. When I was experimenting with them I also found that it would also be  different from the average of intensities of each color channel.

P.S. I was completely baffled when I found that

img_read_as_color[:,:,0]/3+img_read_as_color[:,:,1]/3+img_read_as_color[:,:,2]/3 == (img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2])/3

but when shown as immage

(img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2])/3

would look like

img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2]

Can someone explain to me why this is happening?

My full code:

import matplotlib.pyplot as plt
import cv2

sample = r'G:\Python\knight-mare\screenshots\2020-07-12-02-40-44.jpg'
img_read_as_grayscale = cv2.imread(sample, cv2.IMREAD_GRAYSCALE)
img_read_as_color = cv2.imread(sample, cv2.IMREAD_COLOR)
img_RGB_to_grayscale = cv2.cvtColor(img_read_as_color, cv2.COLOR_RGB2GRAY)
img_BGR_to_grayscale = cv2.cvtColor(img_read_as_color, cv2.COLOR_BGR2GRAY)
plt.imshow(img_read_as_grayscale)
plt.title('img_read_as_grayscale')
plt.show()
plt.imshow(img_read_as_color)
plt.title('img_read_as_color')
plt.show()
plt.imshow(img_RGB_to_grayscale)
plt.title('img_RGB_to_grayscale')
plt.show()
plt.imshow(img_BGR_to_grayscale)
plt.title('img_BGR_to_grayscale')
plt.show()

channel_avg_div_separately = img_read_as_color[:,:,0]/3+img_read_as_color[:,:,1]/3+img_read_as_color[:,:,2]/3
channel_avg_div_together = (img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2])/3
channel_sum = img_read_as_color[:,:,0]+img_read_as_color[:,:,1]+img_read_as_color[:,:,2]
plt.imshow(channel_avg_div_separately)
plt.title('channel_avg_div_separately')
plt.show()
plt.imshow(channel_avg_div_together)
plt.title('channel_avg_div_together')
plt.show()
plt.imshow(channel_sum)
plt.title('channel_sum')
plt.show()

Body:
I think the problem is with the MatPlotLib .imshow() method.  In my experiments both:

img_read_as_grayscale = cv2.imread(sample, cv2.IMREAD_GRAYSCALE)

and

img_BGR_to_grayscale = cv2.cvtColor(img_read_as_color, cv2.COLOR_BGR2GRAY)

will be properly displayed as a grayscale image when using cv2.imshow()
but will be displayed with a weird blue and green color with plt.imshow().

You can fix this by specifying cmap='gray'

plt.imshow(img_BGR_to_grayscale, cmap='gray')


问:
Removing a single character in sequential order in a word using python 3.9.7
```<code>word = input("Word: ")
for n in range(0, len(word)):
 sliced_front = word.replace(word[n:], '')
 sliced_back = word.replace(word[:n+1], '')
 print(sliced_front, sliced_back)
</code>```

In above code, if I enter 'breatd', this is the output:

```<code>     reatd
    b eatd
    br atd
    bre td
    brea d
    breat
</code>```

If I enter 'states', this is the output:

```<code>     tate
    s ates
    st tes
    sta es
    stat s
    tate
</code>```

If I enter 'events', this is the output:

```<code>     vnts
    e ents
    ev nts
    eve ts
    even s
    event
</code>```

Why does python remove 's' twice in the first and last iterations when the input is 'states', while removing 'e' twice only in the first iteration, not in third iteration when input is 'events'?

I want to remove a single character in each iteration.  How can I make this stop removing the repeated character twice in a single iteration?

答: per python docs: link will replace all instances of that string, if want to only replace first need to specify count parameter

Body:
word = input("Word: ")
for n in range(0, len(word)):
 sliced_front = word.replace(word[n:], '')
 sliced_back = word.replace(word[:n+1], '')
 print(sliced_front, sliced_back)

In above code, if I enter 'breatd', this is the output:

     reatd
    b eatd
    br atd
    bre td
    brea d
    breat

If I enter 'states', this is the output:

     tate
    s ates
    st tes
    sta es
    stat s
    tate

If I enter 'events', this is the output:

     vnts
    e ents
    ev nts
    eve ts
    even s
    event

Why does python remove 's' twice in the first and last iterations when the input is 'states', while removing 'e' twice only in the first iteration, not in third iteration when input is 'events'?

I want to remove a single character in each iteration.  How can I make this stop removing the repeated character twice in a single iteration?


问:
No routes matched location "/cart" in router router dom v 6
When I console.log  qty (in the code below), I see No routes matched location "/cart"  (from browser console) instead of value of qty. In react-router-dom v5 everything works well by passing location as props to the component, but that isn't working in v6. The following block of code work in router-dom v5:

```<code>export function CartScreen({ match, location, history}) {
    const qty = location.search ? Number(location.search.split("=")[1]): 1

    console.log('qty:', qty)

    return (
        <div>
            <h1>Add to CART</h1>
        </div>
    )
}
</code>```

Add to Cart Handler:

```<code>const addToCartHandler = () =>{
        history(`/cart/${match.id}?qty=${qty}`)
    }

<Button type='button' onClick={addToCartHandler} > Add To Cart </Button>
</code>```

However, the above code is no valid in router-dom v6, so I try to achieve the same result by changing it to the one below(but it is not working):

```<code>const CartScreen = () => {
    const match = useParams()
    const location = useLocation();
    const productID = match.id
    const qty = location.search ? Number(location.search.split("=")[1]): 1

    console.log('qty:', qty)

    return (
        <div>
            <h1>Add to CART</h1>
        </div>
    )
}
</code>```

App.js

```<code>function App() {
    return (
    <Router>
      <Routes>
          <Route path='/cart/:id?' element={<CartScreen/>} />
      </Routes>
    </Router>
  );
}

export default App;
</code>```

The main issue that is with the the way I used location in  router dom v 6.

答: For the addTo cart handler you  need to use the useNavigate() instead of the history since is no longer required in react-router dom v6</p>

Body:
When I console.log  qty (in the code below), I see No routes matched location "/cart"  (from browser console) instead of value of qty. In react-router-dom v5 everything works well by passing location as props to the component, but that isn't working in v6. The following block of code work in router-dom v5:

export function CartScreen({ match, location, history}) {
    const qty = location.search ? Number(location.search.split("=")[1]): 1

    console.log('qty:', qty)

    return (

Add to CART

    )
}

Add to Cart Handler:

const addToCartHandler = () =>{
        history(`/cart/${match.id}?qty=${qty}`)
    }

<Button type='button' onClick={addToCartHandler} > Add To Cart </Button>

However, the above code is no valid in router-dom v6, so I try to achieve the same result by changing it to the one below(but it is not working):

const CartScreen = () => {
    const match = useParams()
    const location = useLocation();
    const productID = match.id
    const qty = location.search ? Number(location.search.split("=")[1]): 1

    console.log('qty:', qty)

    return (

Add to CART

    )
}

App.js

function App() {
    return (
    <Router>
      <Routes>
          <Route path='/cart/:id?' element={<CartScreen/>} />
      </Routes>
    </Router>
  );
}

export default App;

The main issue that is with the the way I used location in  router dom v 6.


问:
Moving only images in a directory to a new directory
I have a directory containing N images, but each image is itself contained in a subdirectory, which is otherwise empty. It looks like this:

```<code>- Images
 - Image1
   - image1.jpg
 - Image2
   - image2.jpg
 - Image3
   - image3.jpg
 - Image4
...etc
</code>```

I would like to move it to a new directory that will contain only the images, like so:

```<code>- New Directory
 - image1.jpg
 - image2.jpg
 - image3.jpg
...etc
</code>```

Any help is greatly appreciated.

答:
This simple solution ended up working for me:</p>
```<code>import os

rootdir = './Images'

for subdir, dirs, files in os.walk(rootdir):
  for file in files:
    os.rename((os.path.join(subdir, file)),'./NewDirectory/'+str(file))
</code>```

Body:
I have a directory containing N images, but each image is itself contained in a subdirectory, which is otherwise empty. It looks like this:

- Images
 - Image1
   - image1.jpg
 - Image2
   - image2.jpg
 - Image3
   - image3.jpg
 - Image4
...etc

I would like to move it to a new directory that will contain only the images, like so:

- New Directory
 - image1.jpg
 - image2.jpg
 - image3.jpg
...etc

Any help is greatly appreciated.

Body:
This simple solution ended up working for me:

import os

rootdir = './Images'

for subdir, dirs, files in os.walk(rootdir):
  for file in files:
    os.rename((os.path.join(subdir, file)),'./NewDirectory/'+str(file))


问:
How do I pass/send a triggered sequential primary key generated to the next page in Oracle Apex?
I'm trying to pass a primary key value to another page in Oracle Apex Cloud. The problem here is that the Primary Key is generated using triggers.

When I used Oracle's Apex feature set Item in branches to send in the primary key to the next page, it didn't work and caused an error because it was trying to read data from the hidden Item ( Primary Key ) in the first page which is null because the primary key is only generated after an INSERT action so the Primary Key in the form will remain empty which means I can't retrieve it using Oracle's Apex set Item feature. So I want to send the primary key that is generated after the Form has been submitted to the next Form/Page.

I've searched around for a workaround this problem but can't seem to figure it out myself. I saw a method using "Return Key as Item" to send in the primary key to the next page but the explanation wasn't really detailed ( at the very least to me ) so I don't even know where to start or how to do it.

答:
You don't explain what process is creating the primary key, so I'm doing a bit of guessing here:

I'm assuming that this a region of type form that creates the row with a new primary key value. I created a region on the DEPT sample table with primary key item  P1_DEPTNO

By setting the attribute "Return Primary Key after Insert" the item P1_DEPTNO will get the primary key value of the row that has been inserted and can then be passed on to another page.


问:
When do I need to use a GeoSeries when creating a GeoDataFrame, and when is a list enough?
```<code>import geopandas as gpd
import matplotlib.pyplot as plt
from shapely.geometry import Polygon, Point
import numpy as np
</code>```

I define a polygon:

```<code>polygon = Polygon([(0,0),(0,1),(1,1),(1,0)])
</code>```

and create a list of random points:

```<code>np.random.seed(42)
points = [Point([np.random.uniform(low=-1,high=1),
                 np.random.uniform(low=-1,high=1)]) for _ in range(1000)]
</code>```

I want to know which points are within the polygon. I create a GeoDataFrame with a column called points, by first converting the points list to GeoSeries:

```<code>gdf = gpd.GeoDataFrame(dict(points=gpd.GeoSeries(points)))
</code>```

Then simply do:

```<code>gdf.points.within(polygon)
</code>```

which returns a pandas.core.series.Series of booleans, indicating which points are within the polygon.

However, if I don't create the GeoDataFrame from a list, not a GeoSeries object:

```<code>gdf = gpd.GeoDataFrame(dict(points=points))
</code>```

and then do:

```<code>gdf.points.within(polygon)
</code>```

I get:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-171-831eddc859a1> in <module>()
----> 1 gdf.points.within(polygon)

/usr/local/lib/python3.7/dist-packages/pandas/core/generic.py in __getattr__(self, name)
   5485         ):
   5486             return self[name]
-> 5487         return object.__getattribute__(self, name)
   5488
   5489     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'within'
</code>```

In the examples given on the geopandas.GeoDataFrame page, a GeoDataFrame is create from a list, not a GeoSeries of shapely.geometry.Point objects:

```<code>from shapely.geometry import Point
d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
gdf = geopandas.GeoDataFrame(d, crs="EPSG:4326")
</code>```

When do I need to convert my lists to GeoSeries first, and when can I keep them as lists when creating GeoDataFrames?

答:
On the docs for geopandas.GeoDataFrame, where you got your example, there's a little note:

Notice that the inferred dtype of ‘geometry’ columns is geometry.

Which can be seen here, and you can observe it yourself:

```<code>>>> import geopandas as gpd

>>> gpd.GeoDataFrame({'geometry': [Point(0,0)]}).dtypes
geometry    geometry
dtype: object

>>> gpd.GeoDataFrame({'geometryXXX': [Point(0,0)]}).dtypes
geometryXXX    object
dtype: object
</code>```

From the docs for geopandas.GeoSeries:

A Series object designed to store shapely geometry objects.

...so it makes sense that it would try to convert the objects it's created with to the geometry dtype. In fact, when you try to create a GeoSeries with non-shapely objects, you'll get a warning:

```<code>>>> gpd.GeoSeries([1,2,3])
<ipython-input-53-ca5248fcdaf8>:1: FutureWarning:     You are passing non-geometry data to the GeoSeries constructor. Currently,
    it falls back to returning a pandas Series. But in the future, we will start
    to raise a TypeError instead.
  gpd.GeoSeries([1,2,3])
</code>```

...which, as the warning says, will become an error in the future.

Since you're not creating a GeoSeries object (your using a list instead), and since the column is not called geometry, the GeoDataFrame makes its dtype be the most general it can convert the objects within to - object. Therefore, since the column is of dtype object and not geometry, you can't call geometry-specific methods, such as within.

If you need to use a list, you've two simple choices.

Method 1. Pass the geometry= keyword argument to GeoDataFrame():

```<code>>>> gdf = gpd.GeoDataFrame({'points': [Point(0,0), Point(0,1)]}, geometry='points')
>>> gdf['points'].dtypes
<geopandas.array.GeometryDtype at 0x12882a1c0>
>>> gdf['points'].within
<bound method GeoPandasBase.within of 0    POINT (0.00000 0.00000)
1    POINT (0.00000 1.00000)
Name: points, dtype: geometry>
</code>```

Method 2. Use astype like you'd do with a normal dataframe:

```<code>>>> gdf = gpd.GeoDataFrame({'points': [Point(0,0), Point(0,1)]})
>>> gdf['points'].dtype
dtype('O')
>>> gdf['points'].within
...
AttributeError: 'Series' object has no attribute 'within'

>>> gdf['points'] = gdf['points'].astype('geometry')
>>> gdf['points'].dtype
<geopandas.array.GeometryDtype at 0x122189e20>
>>> gdf['points'].within
<bound method GeoPandasBase.within of 0    POINT (0.00000 0.00000)
1    POINT (0.00000 1.00000)
Name: points, dtype: geometry>
</code>```

Body:
import geopandas as gpd
import matplotlib.pyplot as plt
from shapely.geometry import Polygon, Point
import numpy as np

I define a polygon:

polygon = Polygon([(0,0),(0,1),(1,1),(1,0)])

and create a list of random points:

np.random.seed(42)
points = [Point([np.random.uniform(low=-1,high=1),
                 np.random.uniform(low=-1,high=1)]) for _ in range(1000)]

I want to know which points are within the polygon. I create a GeoDataFrame with a column called points, by first converting the points list to GeoSeries:

gdf = gpd.GeoDataFrame(dict(points=gpd.GeoSeries(points)))

Then simply do:

gdf.points.within(polygon)

which returns a pandas.core.series.Series of booleans, indicating which points are within the polygon.

However, if I don't create the GeoDataFrame from a list, not a GeoSeries object:

gdf = gpd.GeoDataFrame(dict(points=points))

and then do:

gdf.points.within(polygon)

I get:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-171-831eddc859a1> in <module>()
----> 1 gdf.points.within(polygon)

/usr/local/lib/python3.7/dist-packages/pandas/core/generic.py in __getattr__(self, name)
   5485         ):
   5486             return self[name]
-> 5487         return object.__getattribute__(self, name)
   5488
   5489     def __setattr__(self, name: str, value) -> None:

AttributeError: 'Series' object has no attribute 'within'

In the examples given on the geopandas.GeoDataFrame page, a GeoDataFrame is create from a list, not a GeoSeries of shapely.geometry.Point objects:

from shapely.geometry import Point
d = {'col1': ['name1', 'name2'], 'geometry': [Point(1, 2), Point(2, 1)]}
gdf = geopandas.GeoDataFrame(d, crs="EPSG:4326")

When do I need to convert my lists to GeoSeries first, and when can I keep them as lists when creating GeoDataFrames?

Body:
On the docs for geopandas.GeoDataFrame, where you got your example, there's a little note:

Notice that the inferred dtype of ‘geometry’ columns is geometry.

Which can be seen here, and you can observe it yourself:

>>> import geopandas as gpd

>>> gpd.GeoDataFrame({'geometry': [Point(0,0)]}).dtypes
geometry    geometry
dtype: object

>>> gpd.GeoDataFrame({'geometryXXX': [Point(0,0)]}).dtypes
geometryXXX    object
dtype: object

From the docs for geopandas.GeoSeries:

A Series object designed to store shapely geometry objects.

...so it makes sense that it would try to convert the objects it's created with to the geometry dtype. In fact, when you try to create a GeoSeries with non-shapely objects, you'll get a warning:

>>> gpd.GeoSeries([1,2,3])
<ipython-input-53-ca5248fcdaf8>:1: FutureWarning:     You are passing non-geometry data to the GeoSeries constructor. Currently,
    it falls back to returning a pandas Series. But in the future, we will start
    to raise a TypeError instead.
  gpd.GeoSeries([1,2,3])

...which, as the warning says, will become an error in the future.

Since you're not creating a GeoSeries object (your using a list instead), and since the column is not called geometry, the GeoDataFrame makes its dtype be the most general it can convert the objects within to - object. Therefore, since the column is of dtype object and not geometry, you can't call geometry-specific methods, such as within.

If you need to use a list, you've two simple choices.

Method 1. Pass the geometry= keyword argument to GeoDataFrame():

>>> gdf = gpd.GeoDataFrame({'points': [Point(0,0), Point(0,1)]}, geometry='points')
>>> gdf['points'].dtypes
<geopandas.array.GeometryDtype at 0x12882a1c0>
>>> gdf['points'].within
<bound method GeoPandasBase.within of 0    POINT (0.00000 0.00000)
1    POINT (0.00000 1.00000)
Name: points, dtype: geometry>

Method 2. Use astype like you'd do with a normal dataframe:

>>> gdf = gpd.GeoDataFrame({'points': [Point(0,0), Point(0,1)]})
>>> gdf['points'].dtype
dtype('O')
>>> gdf['points'].within
...
AttributeError: 'Series' object has no attribute 'within'

>>> gdf['points'] = gdf['points'].astype('geometry')
>>> gdf['points'].dtype
<geopandas.array.GeometryDtype at 0x122189e20>
>>> gdf['points'].within
<bound method GeoPandasBase.within of 0    POINT (0.00000 0.00000)
1    POINT (0.00000 1.00000)
Name: points, dtype: geometry>


问:
sha256sum: 'standard input': no properly formatted checksum lines found
I'm trying to verify an installer by typing this command.

```<code>grep node-vx.y.z.tar.gz SHASUMS256.txt | sha256sum -c -
</code>```

But I get a response like this from Terminal

```<code>sha256sum: 'standard input': no properly formatted checksum lines found
</code>```

Obviously, I already have SHASUMS256.txt file and on the right path on Terminal(MacOS).

Also prior to this, I've already installed CoreUtils from brew by running this command.

```<code>brew install coreutils
</code>```

So what does 'standard input': no properly formatted checksum lines found mean in this context on MacOS Terminal?

答:
It would help if you posted the contents of the file:

SHASUMS256.txt

If it is properly formatted it should contain a line that looks something like:

09ac98ea433e8cb19d09ead1a0bd439cafb1c3e4cb699af04b4e4da1f6ca3f02 node-vx.y.z.tar.gz

You could get your stderr output for 2 possible reasons.

The line in SHASUMS256.txt is not formatted correctly. It should be formatted as <ChecksumHash> <Filename> without the <>s.

The output from your grep search is blank (no output because grep returned no matches). This is more likely and I would suggest running the grep command by itself first to see what the output is prior to piping it into sha256sum.

Body:
I'm trying to verify an installer by typing this command.

grep node-vx.y.z.tar.gz SHASUMS256.txt | sha256sum -c -

But I get a response like this from Terminal

sha256sum: 'standard input': no properly formatted checksum lines found

Obviously, I already have SHASUMS256.txt file and on the right path on Terminal(MacOS).

Also prior to this, I've already installed CoreUtils from brew by running this command.

brew install coreutils

So what does 'standard input': no properly formatted checksum lines found mean in this context on MacOS Terminal?


问:
How to add content from C# to XAML
I have used a litle XamarinForms before and then i did a
naming to be able to point the c# code to it.

```<code>   <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   x:Class="MauiTest.MainPage"
   BackgroundColor="{DynamicResource SecondaryColor}">

    <StackLayout x:name="_stacklayoutname">
    <Label Text="" x:Name="_Lable"/>
    </StackLayout>
</ContentPage>
</code>```

And then i did like this in the MainPage.xaml.cs

```<code>   public MainPage()
    {
        InitializeComponent();
        _stacklayoutname.Children.Add(new Label { Text = "TEST" });
        _Lable.Text = "TEST";
    }
</code>```

now it get this, but i can change the _Lable to "Text".
how can i point to a stacklayout.

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   CS0103  The name '_stacklayoutname' does not exist in the current context   MauiTest (net6.0-android), MauiTest (net6.0-ios), MauiTest (net6.0-maccatalyst), MauiTest (net6.0-windows10.0.19041)    *** 11  Active
</code>```

答:
this is wrong

```<code><StackLayout x:name="_stacklayoutname">
</code>```

it should be

```<code><StackLayout x:Name="_stacklayoutname">
</code>```

Title: How to add content from C# to XAML

Body:
I have used a litle XamarinForms before and then i did a
naming to be able to point the c# code to it.

   <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   x:Class="MauiTest.MainPage"
   BackgroundColor="{DynamicResource SecondaryColor}">

    <StackLayout x:name="_stacklayoutname">

    </StackLayout>
</ContentPage>

And then i did like this in the MainPage.xaml.cs

   public MainPage()
    {
        InitializeComponent();
        _stacklayoutname.Children.Add(new Label { Text = "TEST" });
        _Lable.Text = "TEST";
    }

now it get this, but i can change the _Lable to "Text".
how can i point to a stacklayout.

Severity    Code    Description Project File    Line    Suppression State
Error   CS0103  The name '_stacklayoutname' does not exist in the current context   MauiTest (net6.0-android), MauiTest (net6.0-ios), MauiTest (net6.0-maccatalyst), MauiTest (net6.0-windows10.0.19041)    *** 11  Active

Body:
this is wrong

<StackLayout x:name="_stacklayoutname">

it should be

<StackLayout x:Name="_stacklayoutname">


问:
how to grow columns to be the same height of content of either column using css flexbox?
Demo: https://jsfiddle.net/chovy/7vgLpm9h/7/

I'm having a hard time getting the nav to be as tall as the content (or if you remove content having the content be as tall as the nav).

Both should be 100% of height of the tallest column.

I also need to position last nav item at bottom of navigation bar.

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

html,
body,
main {
  height: 100%;
  min-height: 100vh;
  width: 100vw;
}

main {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}

aside {
  width: 100rem;
  border: 1px solid red;
  align-self: stretch;
  flex-grow: 1;
}

section {
  flex-grow: 1;
  border: 1px solid green;
}

nav li {
  margin-bottom: 1rem;
}

nav li:last-child {
  margin-top: auto;
  margin-bottom: 0;
  color: blue;
  font-weight: 700;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <aside>
    <header>header</header>
    <nav>
      <ul>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
      </ul>
    </nav>
  </aside>
  <section>
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column.
  </section>
</main></code>```

答:
Simplify your code like below. You have to remove some unnecessary properties

body {
  margin: 0;
}
main {
  min-height: 100vh;
  display: flex;
}
aside {
  width:100px;
  border: 1px solid red;
  display: flex;
  flex-direction: column;
}
nav {
  flex-grow: 1;
  display: flex;
}
ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
}
section {
  flex: 1;
  border: 1px solid green;
}
nav li:not(:last-child) {
  margin-bottom: 1rem;
}
nav li:last-child {
  margin-top: auto;
  color: blue;
  font-weight: 700;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
  <aside>
    <header>header</header>
    <nav>
      <ul>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
      </ul>
    </nav>
  </aside>
  <section>
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column.
  </section>
</main></code>```

Body:
Demo: https://jsfiddle.net/chovy/7vgLpm9h/7/

I'm having a hard time getting the nav to be as tall as the content (or if you remove content having the content be as tall as the nav).

Both should be 100% of height of the tallest column.

I also need to position last nav item at bottom of navigation bar.

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

html,
body,
main {
  height: 100%;
  min-height: 100vh;
  width: 100vw;
}

main {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
}

aside {
  width: 100rem;
  border: 1px solid red;
  align-self: stretch;
  flex-grow: 1;
}

section {
  flex-grow: 1;
  border: 1px solid green;
}

nav li {
  margin-bottom: 1rem;
}

nav li:last-child {
  margin-top: auto;
  margin-bottom: 0;
  color: blue;
  font-weight: 700;
}

    header

link 1

link 1

link 1

link 1

link 1

link 1

link 1

link 1

    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column.

Body:
Simplify your code like below. You have to remove some unnecessary properties

body {
  margin: 0;
}
main {
  min-height: 100vh;
  display: flex;
}
aside {
  width:100px;
  border: 1px solid red;
  display: flex;
  flex-direction: column;
}
nav {
  flex-grow: 1;
  display: flex;
}
ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
}
section {
  flex: 1;
  border: 1px solid green;
}
nav li:not(:last-child) {
  margin-bottom: 1rem;
}
nav li:last-child {
  margin-top: auto;
  color: blue;
  font-weight: 700;
}

<main>
  <aside>
    <header>header</header>
    <nav>
      <ul>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
        <li>link 1</li>
      </ul>
    </nav>
  </aside>
  <section>
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column. grow this to 100% of either column.
    grow this to 100% of either column.
  </section>
</main>


问:
Why is InterstitialAd not loaded after the first trigger?
I manage to get the first ad to show, but app crashed the next time I try to trigger an ad. And gives me this error: Error: InterstitialAd.show() The requested InterstitialAd has not loaded and could not be shown

In App.js

```<code>componentDidMount() {
    const eventListener = interstitial.onAdEvent(type => {
      if (type === AdEventType.LOADED) {
        this.setState({
          setLoaded: true,
        });
      }
    });

    interstitial.load();
    eventListener();

  }

showAds = () => {
    interstitial.show();
    // No advert ready to show yet
    if (!this.state.loaded) {
      console.log('null');
      return null;
    }
  };

// This trigger is within another function
      this.showAds();
</code>```

I have a class component so I use ComponentDidMount instead of useEffect. Might that cause some troubles?

UPDATE:

```<code>    this.state = {
      loaded: false,
      setLoaded: false,
      Listener: null,
    };
</code>```

The above state is an attempt to redo

```<code>const [loaded, setLoaded] = useState(false);
</code>```

答:
constructor () {
    super();
    this.Listener=null
  }

componentDidMount() {
    this.Listener = interstitial.onAdEvent(type => {
      if (type === AdEventType.LOADED) {
        this.setState({
          loaded: true,
        });
      }else if(type === AdEventType.CLOSED){
        this.loadAd()
     }
    });
    this.loadAd()
 }

componentWillUnmount(){
  if(this.Listener!==null){
   this.Listener()
  }
}

loadAd = () =>{
   this.setState({
      loaded: false,
   });
   interstitial.load();
}

showAds = () => {
   if (!this.state.loaded) {
     console.log('null');
     return null;
   }else{
     interstitial.show();
   }
 };
```

Body:
I manage to get the first ad to show, but app crashed the next time I try to trigger an ad. And gives me this error: Error: InterstitialAd.show() The requested InterstitialAd has not loaded and could not be shown

In App.js

componentDidMount() {
    const eventListener = interstitial.onAdEvent(type => {
      if (type === AdEventType.LOADED) {
        this.setState({
          setLoaded: true,
        });
      }
    });

    interstitial.load();
    eventListener();

  }

showAds = () => {
    interstitial.show();
    // No advert ready to show yet
    if (!this.state.loaded) {
      console.log('null');
      return null;
    }
  };

// This trigger is within another function
      this.showAds();

I have a class component so I use ComponentDidMount instead of useEffect. Might that cause some troubles?

UPDATE:

    this.state = {
      loaded: false,
      setLoaded: false,
      Listener: null,
    };

The above state is an attempt to redo

const [loaded, setLoaded] = useState(false);


问:
Extracting Attribute from the whole XDocument
Following XDocument contains (x,y) coordinates stored in the XElement members with different names under attributes 'x','y','x1','y1','z', and 'z1':

```<code><?xml version="1.0" encoding="utf-8"?>
<shapes>
  <shape>
    <connections />
    <foreground>
      <strokewidth width="0.1" />
      <path>
        <move x="1395.6" y="84.6" />
        <line x="80.1" y="84.6" />
        <curve x1="75.1" y1="84.6" x2="71.1" y2="88.6" x3="71.1" y3="93.6" />
        <line x="71.1" y="402.6" />
        <close />
      </path>
      <fillstroke />
    </foreground>
  </shape>
</shapes>
</code>```

What is the easiest recommended way to extract only the values of the attribute 'x' from the whole document without looping through all the elements and checking for the particular attribute? Given XML would  ideally result with the list of 'x' coordinates:

```<code>float[] x= {1395.6, 80.1, 71.1};
float[] x1 = {75.1};
</code>```

And the same for 'y', 'y1',...

EDIT:
Since the coordinates are always in the 'leaf' xml element, I eventually used:

```<code>return fileXml.Root.Descendants()
                .Where(e => e.HasElements == false) // leaf element
                .Where(e => e.Attribute("x") != null)
                .Select(c => c.Attribute("x").Value).Select(float.Parse)
                .ToList(); // or .ToArray();
</code>```

It can be wrapped in a helper function as well.

答:
You should the methods of the XmlConvert class instead of float.Parse():

```<code>float f = XmlConvert.ToSingle(text);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Following XDocument contains (x,y) coordinates stored in the XElement members with different names under attributes 'x','y','x1','y1','z', and 'z1':

<?xml version="1.0" encoding="utf-8"?>
<shapes>
  <shape>
    <connections />
    <foreground>
      <strokewidth width="0.1" />
      <path>
        <move x="1395.6" y="84.6" />
        <line x="80.1" y="84.6" />
        <curve x1="75.1" y1="84.6" x2="71.1" y2="88.6" x3="71.1" y3="93.6" />
        <line x="71.1" y="402.6" />
        <close />
      </path>
      <fillstroke />
    </foreground>
  </shape>
</shapes>

What is the easiest recommended way to extract only the values of the attribute 'x' from the whole document without looping through all the elements and checking for the particular attribute? Given XML would  ideally result with the list of 'x' coordinates:

float[] x= {1395.6, 80.1, 71.1};
float[] x1 = {75.1};

And the same for 'y', 'y1',...

EDIT:
Since the coordinates are always in the 'leaf' xml element, I eventually used:

return fileXml.Root.Descendants()
                .Where(e => e.HasElements == false) // leaf element
                .Where(e => e.Attribute("x") != null)
                .Select(c => c.Attribute("x").Value).Select(float.Parse)
                .ToList(); // or .ToArray();

It can be wrapped in a helper function as well.

Body:
You should the methods of the XmlConvert class instead of float.Parse():

float f = XmlConvert.ToSingle(text);


问:
SQL Server 2008, temp tables, cursor
I've been working at this for a while. I was wondering how I could get this table:

```<code>id       open_dt             ops_hrs
1        10/31/2011          7:00AM - 5:30PM
2        11/1/2011           7:00AM - 5:00PM
3        11/2/2011           7:00AM - 5:00PM
4        11/3/2011           7:00AM - 5:00PM
5        11/6/2011           7:00AM - 7:00PM
6        11/8/2011           7:00AM - 5:00PM
</code>```

to look like this table:

```<code>max_date          min_date     ops_hrs
10/31/2011        10/31/2011   7:00AM - 5:30PM
11/1/2011         11/3/2011    7:00AM - 5:00PM
11/6/2011         11/6/2011    7:00AM - 7:00PM
11/8/2011         11/8/2011    7:00AM - 5:00PM
</code>```

I tried using a cursor but it is not necessary. Also, it has to be grouped. As soon as consecutive days break a new grouping occurs. Any help would be appreciated.

This query will generate the above sample data

```<code>;
WITH pdog (id, open_dt,ops_hrs) AS
(
SELECT 1, CAST('10/31/2011' AS datetime),  '7:00AM - 5:30PM'
UNION ALL SELECT 2, CAST('11/1/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 3, CAST('11/2/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 4, CAST('11/3/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 5, CAST('11/6/2011' AS datetime),'7:00AM - 7:00PM'
UNION ALL SELECT 6, CAST('11/8/2011' AS datetime),'7:00AM - 5:00PM'
)
SELECT * FROM pdog
</code>```

答:
```<code>;WITH    CTE
          AS ( SELECT   * ,
                        DATEDIFF(DAY, 0, open_dt) -  ROW_NUMBER() OVER
                              ( PARTITION BY ops_hrs ORDER BY open_dt ) AS Grp
               FROM     @x
             )
    SELECT
            MIN(open_dt) AS min_date ,
            MAX(open_dt) AS max_date ,
            ops_hrs
    FROM    CTE
    GROUP BY ops_hrs ,
            Grp
    ORDER BY min_date
</code>```

Title: SQL Server 2008, temp tables, cursor

Body:
I've been working at this for a while. I was wondering how I could get this table:

id       open_dt             ops_hrs
1        10/31/2011          7:00AM - 5:30PM
2        11/1/2011           7:00AM - 5:00PM
3        11/2/2011           7:00AM - 5:00PM
4        11/3/2011           7:00AM - 5:00PM
5        11/6/2011           7:00AM - 7:00PM
6        11/8/2011           7:00AM - 5:00PM

to look like this table:

max_date          min_date     ops_hrs
10/31/2011        10/31/2011   7:00AM - 5:30PM
11/1/2011         11/3/2011    7:00AM - 5:00PM
11/6/2011         11/6/2011    7:00AM - 7:00PM
11/8/2011         11/8/2011    7:00AM - 5:00PM

I tried using a cursor but it is not necessary. Also, it has to be grouped. As soon as consecutive days break a new grouping occurs. Any help would be appreciated.

This query will generate the above sample data

;
WITH pdog (id, open_dt,ops_hrs) AS
(
SELECT 1, CAST('10/31/2011' AS datetime),  '7:00AM - 5:30PM'
UNION ALL SELECT 2, CAST('11/1/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 3, CAST('11/2/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 4, CAST('11/3/2011' AS datetime),'7:00AM - 5:00PM'
UNION ALL SELECT 5, CAST('11/6/2011' AS datetime),'7:00AM - 7:00PM'
UNION ALL SELECT 6, CAST('11/8/2011' AS datetime),'7:00AM - 5:00PM'
)
SELECT * FROM pdog


问:
Prevent table header from scrolling vertically (to work in IE 11)
I'm stuck using IE 11 as a rendering engine in my Windows app. I know that there are quite a lot of examples how to prevent a table header from scrolling vertically, but I can't seem to make them work in IE. Is there any way to make it work there?

Here's an example of HTML I'm using for the table:

```<code><table width='100%' border='0' cellpadding='0' cellspacing='0'>
 <thead>
  <tr>
   <th scope='col'>Col 1</th>
   <th scope='col'>Col 2</th>
   <th scope='col'>Col 3</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>---</td>
   <td>---</td>
   <td>---</td>
   <td>---</td>
  </tr>
  <tr>
   <td>+++</td>
   <td>+++</td>
   <td>+++</td>
   <td>+++</td>
  </tr>
 </tbody>
</table>
</code>```

I need to make sure that the thead stays on top of the table no matter how long the list of rows in it is.

答:
So with this what you can do is assign the table itself a relative position but then apply the position:sticky value to the table head class.

There's an article here that I feel can provide a bit more value as well https://css-tricks.com/position-sticky-and-table-headers/

In the future, it would also help if we could see the CSS you're using; so we can let you know if you're on the right track.

Body:
I'm stuck using IE 11 as a rendering engine in my Windows app. I know that there are quite a lot of examples how to prevent a table header from scrolling vertically, but I can't seem to make them work in IE. Is there any way to make it work there?

Here's an example of HTML I'm using for the table:

   Col 1
   Col 2
   Col 3

   ---
   ---
   ---
   ---

   +++
   +++
   +++
   +++

I need to make sure that the thead stays on top of the table no matter how long the list of rows in it is.


答:
First of all, replace returns a copy of the string with all occurrences of the old substring replaced by the new one. To replace only the first occurrence of the old substring - you need to use the optional argument count. However, for the need you described, it is probably better to use a slice.

Secondly, there is no need to provide range with a start parameter of 0, as it is the default value of the start parameter.

Putting it all together:

```<code>word = input("Word: ")
for letter in range(len(word)):
    print(word[:letter ] + ' ' + word[letter +1:])
</code>```

Output (given the input "states"):

```<code>tates
s ates
st tes
sta es
stat s
state
</code>```

Title: Removing a single character in sequential order in a word using python 3.9.7

Body:
First of all, replace returns a copy of the string with all occurrences of the old substring replaced by the new one. To replace only the first occurrence of the old substring - you need to use the optional argument count. However, for the need you described, it is probably better to use a slice.

Secondly, there is no need to provide range with a start parameter of 0, as it is the default value of the start parameter.

Putting it all together:

word = input("Word: ")
for letter in range(len(word)):
    print(word[:letter ] + ' ' + word[letter +1:])

Output (given the input "states"):

tates
s ates
st tes
sta es
stat s
state


问:
Reading syslog output on a Mac
I have a program that was written for linux and I am trying to build and run it on my MacOS 10.5 machine. The program builds and runs without problem, however it makes many calls to syslog. I know that syslogd is running on my mac, however I can't seem to find where my syslog calls are output to.

The syslog calls are of the form

```<code>syslog (LOG_WARNING, "Log message");
</code>```

Any idea where I might find my log output?

答:
If you need complex syslog analysis (navigation hour by hour in terminal, regexp, comparing in real time w\ other files or even running SQL over syslog) lnav would seamlessly provide it for you.

Installation:

brew install lnav
```
<p>Usage:</p>
<pre class="lang-sh prettyprint-override"><code>lnav /var/log/system.log
</code>```

UI itself:

OwnerDisplayName: arigreen

Title: Reading syslog output on a Mac

Body:
I have a program that was written for linux and I am trying to build and run it on my MacOS 10.5 machine. The program builds and runs without problem, however it makes many calls to syslog. I know that syslogd is running on my mac, however I can't seem to find where my syslog calls are output to.

The syslog calls are of the form

syslog (LOG_WARNING, "Log message");

Any idea where I might find my log output?

Body:
If you need complex syslog analysis (navigation hour by hour in terminal, regexp, comparing in real time w\ other files or even running SQL over syslog) lnav would seamlessly provide it for you.

Installation:

brew install lnav

Usage:

lnav /var/log/system.log

UI itself:


问:
Create DHCP Server Using VirtualBox's VBoxManage utility
I am creating  a dhcp server using the following command.

VBoxManage dhcpserver add --netname dirtylan --ip 10.6.66.1 --netmask
255.255.255.0 --lower-ip=10.6.66.64 --upper-ip=10.6.66.128 --enable

When I list the dhcpservers using the following command

VBoxManage list dhcpservers

I see it is created as follows.

NetworkName:    dirtylan Dhcpd IP:       10.6.66.1 LowerIPAddress:
10.6.66.64 UpperIPAddress: 10.6.66.128 NetworkMask:    255.255.255.0 Enabled:        Yes Global Configuration:
minLeaseTime:     default
defaultLeaseTime: default
maxLeaseTime:     default
Forced options:   None
Suppressed opts.: None
1/legacy: 255.255.255.0 Groups:               None Individual Configs:   None

But it does not run. I also can not see it from the virtual machines' network settings and when I try to restart it using the following command

VBoxManage dhcpserver restart --netname dirtylan

I get the below error.

VBoxManage.exe: error: not running VBoxManage.exe: error: Details:
code E_FAIL (0x80004005), component DHCPServerWrap, interface
IDHCPServer, callee IUnknown VBoxManage.exe: error: Context:
"Restart()" at line 1063 of file VBoxManageDHCPServer.cpp
VBoxManage.exe: error: Failed to restart server

I want to use this to create an internal network. I realized that it is not running when I manually entered its name "dirtylan" on the network config and the machine didn't get an IP.

I need help to fix this problem.

Kind Regards,
Ferda

答: Rebooting the host did the magic for me</p>

Body: Rebooting the host did the magic for me


问:
Iterate over two strings checking to see if it matches with its pair
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

```<code>    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }
</code>```

'''

答:
Since you want to count only the places where there are differences, you can iterate through the minimum length present in both the strings and find out the places where they are different.
In the end, you can add absolute difference of length between seq1 and seq2 and return that value to the main function.
For the logic, all you have to do is apply 4 if conditions to check if character is A,G,C,T and if suitable pair is present in the other string.

```<code>public class CountMismatches {

    public static void main(String[] args) {
        {
            String seq1 = "TTCGATGGAGCTGTA";
            String seq2 = "TAGCTAGCTCGGCATGA";

            System.out.println(count_mismatches(seq1, seq2));

        }
    }

    public static int count_mismatches(String seq1, String seq2) {

        int finalCounter = 0;

        for (int i = 0; i < Math.min(seq1.length(), seq2.length()); i++) {
            char c1 = seq1.charAt(i);

            char c2 = seq2.charAt(i);

            if (c1 == 'A') {
                if (c2 == 'T')
                    continue;
                else
                    finalCounter++;

            } else if (c1 == 'T') {
                if (c2 == 'A')
                    continue;
                else
                    finalCounter++;
            } else if (c1 == 'G') {
                if (c2 == 'C')
                    continue;
                else
                    finalCounter++;
            } else if (c1 == 'C') {
                if (c2 == 'G')
                    continue;
                else
                    finalCounter++;
            }
        }
        return finalCounter + (Math.abs(seq1.length() - seq2.length()));

    }
}
</code>```

and the output is as follows :

```<code>5
</code>```

Body:
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }

'''

Body:
Since you want to count only the places where there are differences, you can iterate through the minimum length present in both the strings and find out the places where they are different.
In the end, you can add absolute difference of length between seq1 and seq2 and return that value to the main function.
For the logic, all you have to do is apply 4 if conditions to check if character is A,G,C,T and if suitable pair is present in the other string.

public class CountMismatches {

    public static void main(String[] args) {
        {
            String seq1 = "TTCGATGGAGCTGTA";
            String seq2 = "TAGCTAGCTCGGCATGA";

            System.out.println(count_mismatches(seq1, seq2));

        }
    }

    public static int count_mismatches(String seq1, String seq2) {

        int finalCounter = 0;

        for (int i = 0; i < Math.min(seq1.length(), seq2.length()); i++) {
            char c1 = seq1.charAt(i);

            char c2 = seq2.charAt(i);

            if (c1 == 'A') {
                if (c2 == 'T')
                    continue;
                else
                    finalCounter++;

            } else if (c1 == 'T') {
                if (c2 == 'A')
                    continue;
                else
                    finalCounter++;
            } else if (c1 == 'G') {
                if (c2 == 'C')
                    continue;
                else
                    finalCounter++;
            } else if (c1 == 'C') {
                if (c2 == 'G')
                    continue;
                else
                    finalCounter++;
            }
        }
        return finalCounter + (Math.abs(seq1.length() - seq2.length()));

    }
}

and the output is as follows :

5


答:
replace replaces all occurrences of the letter, not by position

You should use a slice instead:

```<code>word = 'abcdabc'
for n in range(len(word)):
    print(word[:n]+' '+word[n+1:])
</code>```

Output:

```<code> bcdabc
a cdabc
ab dabc
abc abc
abcd bc
abcda c
abcdab
</code>```

Body:
word = input("Word: ")
for n in range(0, len(word)):
 sliced_front = word.replace(word[n:], '')
 sliced_back = word.replace(word[:n+1], '')
 print(sliced_front, sliced_back)

In above code, if I enter 'breatd', this is the output:

     reatd
    b eatd
    br atd
    bre td
    brea d
    breat

If I enter 'states', this is the output:

     tate
    s ates
    st tes
    sta es
    stat s
    tate

If I enter 'events', this is the output:

     vnts
    e ents
    ev nts
    eve ts
    even s
    event

Why does python remove 's' twice in the first and last iterations when the input is 'states', while removing 'e' twice only in the first iteration, not in third iteration when input is 'events'?

I want to remove a single character in each iteration.  How can I make this stop removing the repeated character twice in a single iteration?

Body:
replace replaces all occurrences of the letter, not by position

You should use a slice instead:

word = 'abcdabc'
for n in range(len(word)):
    print(word[:n]+' '+word[n+1:])

Output:

 bcdabc
a cdabc
ab dabc
abc abc
abcd bc
abcda c
abcdab


问:
Draw borders within bars in barplot?
I'm drawing a simple barplot with thick bar borders:

```<code>par(lwd=3)
barplot(c(6,7))
arrows(0,0,10,0,lwd=1)
</code>```

The borders stick out slightly over the x-axis, which looks bad.

Is there any way to draw the border within each bar, rather than around it?

答:
My suggestion after failing to find a clip()-ping or an easy "inner border" answer is this suggestion:

```<code>opar <- par(lwd=3)
barplot(c(6,7))
arrows(0,0,10,0,lwd=3, col="grey")
par(opar)
</code>```

It has the advantage that it doesn't clip the top of the higher bars. Bet you didn't notice that. I didn't notice it until I used lwd=10.

Title: Draw borders within bars in barplot?

Body:
I'm drawing a simple barplot with thick bar borders:

par(lwd=3)
barplot(c(6,7))
arrows(0,0,10,0,lwd=1)

The borders stick out slightly over the x-axis, which looks bad.

Is there any way to draw the border within each bar, rather than around it?

Body:
My suggestion after failing to find a clip()-ping or an easy "inner border" answer is this suggestion:

opar <- par(lwd=3)
barplot(c(6,7))
arrows(0,0,10,0,lwd=3, col="grey")
par(opar)

It has the advantage that it doesn't clip the top of the higher bars. Bet you didn't notice that. I didn't notice it until I used lwd=10.