问:
Cors not allowed while using Axios
Hey I was working with fetch a normal fetch to request my API in my server, and It was working, but I found out that Axios is easier, so I tried to replace every fetch, but it looks like xhr doesn't work because of cors,

I already allowed cors when I was working with fetch, but for some reason cors is not allowed for xhr (Axios) requests

here is Axios defaults:

```<code>import axios from "axios"
import store from "@/store"
import { getLocalStorage } from "@/services/functions.services.js"

axios.defaults.baseURL = store.getters.getData("serverLink")
axios.defaults.withCredentials = true

axios.defaults.headers.common["Authorization"] = `Bearer ${getLocalStorage("access_token")} ${getLocalStorage("refresh_token")}`

</code>```

and here is how I use Axios:

```<code>function fetchF(link, body, method) {
    return new Promise(async (resolve, reject) => {
        axios[method.toLowerCase()](link, body)
            .then(rsp => {
                setLocalStorage("access_token", rsp.access_token);
                setLocalStorage("refresh_token", rsp.refresh_token);
                resolve(rsp);
            }).catch(error => {
                setLocalStorage("access_token", "");
                setLocalStorage("refresh_token", "");
                store.dispatch("changeData", {
                    option: "alertEl",
                    value: "Please log in, and try again",
                });
                return resolve({ isSuccess: false, err: "Please log in, and try again" });
            })
    });
}
</code>```

and here is how I enabled cors on the server-side:

```<code>app.use(cors({
    credentials: true,
}));

</code>```

here is the error:
error in the network page

答:
If a browser sends a CORS request with credentials: true, the browser will not accept a response with 'Access-Control-Allow-Origin:*. You must sepecify Access-Control-Allow-Origin to one domain. Such as Access-Control-Allow-Origin:example.com.

Ref. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#requests_with_credentials

Title: Cors not allowed while using Axios

Body:
Hey I was working with fetch a normal fetch to request my API in my server, and It was working, but I found out that Axios is easier, so I tried to replace every fetch, but it looks like xhr doesn't work because of cors,

I already allowed cors when I was working with fetch, but for some reason cors is not allowed for xhr (Axios) requests

here is Axios defaults:

import axios from "axios"
import store from "@/store"
import { getLocalStorage } from "@/services/functions.services.js"

axios.defaults.baseURL = store.getters.getData("serverLink")
axios.defaults.withCredentials = true

axios.defaults.headers.common["Authorization"] = `Bearer ${getLocalStorage("access_token")} ${getLocalStorage("refresh_token")}`

and here is how I use Axios:

function fetchF(link, body, method) {
    return new Promise(async (resolve, reject) => {
        axios[method.toLowerCase()](link, body)
            .then(rsp => {
                setLocalStorage("access_token", rsp.access_token);
                setLocalStorage("refresh_token", rsp.refresh_token);
                resolve(rsp);
            }).catch(error => {
                setLocalStorage("access_token", "");
                setLocalStorage("refresh_token", "");
                store.dispatch("changeData", {
                    option: "alertEl",
                    value: "Please log in, and try again",
                });
                return resolve({ isSuccess: false, err: "Please log in, and try again" });
            })
    });
}

and here is how I enabled cors on the server-side:

app.use(cors({
    credentials: true,
}));

here is the error:
error in the network page


来源: stackexchange

问:
Strange function in ActivityManager: isUserAMonkey. What does this mean, what is its use?
I found the following function in package android.app.ActivityManager.

```<code>public static boolean isUserAMonkey ()
</code>```

The reference describes:

public static boolean isUserAMonkey ()   Since: API Level 8

Returns "true" if the user interface is currently being messed with by a monkey.

I was shocked by this strange function. And have a few questions.

What does this (user interface is currently being messed with by a
monkey) mean?

What is the practical use of this function?

Why do they use isUserAMonkey for the function name?

答:
The story of how this method was created is quite interesting and i couldn't resist sharing it. I think it explains perfectly why such a method is needed.

"One day i walked into the monkey lab to hear a voice say, '911 -What's
your emergency?" That situation resulted in Dianne adding a new
function to the API, isUserAMonkey() which is used to gate actions
that monkeys shouldn't take during tests (including dialing the phone
and resetting the device).

Androids: The Team That Built the Android Operating System (Haase, Chet)

ContentLicense: CC BY-SA 3.0

Body:
I found the following function in package android.app.ActivityManager.

public static boolean isUserAMonkey ()

The reference describes:

public static boolean isUserAMonkey ()   Since: API Level 8

Returns "true" if the user interface is currently being messed with by a monkey.

I was shocked by this strange function. And have a few questions.

What does this (user interface is currently being messed with by a
monkey) mean?

What is the practical use of this function?

Why do they use isUserAMonkey for the function name?

ContentLicense: CC BY-SA 4.0


问:
The android sdk location cannot be at the filesystem root
I have installed Android Studio in the F:\ drive. My Flutter project is in the E:\ drive.

The Flutter plugin is installed in the Android Studio. But when I open my project in Android Studio and I go to the SDK Manager, it shows the following error:

The android sdk location cannot be at the filesystem root

Every package is disabled and the checkboxes are disabled, so I cannot click them to install Android SDK. The "Edit" link next to the error is not working either.

答:
Using the new android studio (bumble bee version) .
Restart the app and make sure you have an internet access
That will be enough to create the SDK and it’s directories</p>


问:
Intermittent column does not belong to table exception
I have a stored procedure that gets called hundreds of times per minute.  Every once in a rare while I will get an exception that a column does not exist in the query.  Here is the exception:

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.ArgumentException: Column 'SubjectID' does not belong to table .

[ArgumentException: Column 'SubjectID' does not belong to table .]
   System.Data.DataRow.GetDataColumn(String columnName) +1775157
   System.Data.DataRow.get_Item(String columnName) +13
   System.Data.DataTableReader.get_Item(String name) +66

Here is the C# that calls the stored proc:

```<code>DataTableReader dtr;
        dtr = Util.getDepartmentsByTerm(term);
        ddlSubject.Items.Add(new ListItem("Select A Subject...", ""));
        while (dtr.Read())
        {
            //The following line throws the exception!
            var value = (string)dtr["SubjectID"];
            var text = (string)dtr["title"];
            var count = (int) dtr["Count"];
            //if (!text.Contains("(0)"))
            if(count > 0)
                ddlSubject.Items.Add(new ListItem(text, value));
        }
</code>```

Pretty simple... here's the stored procedure:

```<code>ALTER PROCEDURE [dbo].[selectDepartmentsByTerm]

(

@term nvarchar(50),
@version int

)

AS
SELECT SubjectID, Subject as Title,(select count(distinct courseno)
  from RegistrationBlock WITH (NOLOCK)
 where RegistrationBlock.Subject = Subjects.SubjectID
   and RegistrationBlock.version = @version
   and (@term = '' OR RegistrationBlock.term = @term)) as "Count"
  FROM Subjects WITH (NOLOCK)
 where Version = @version
 order by subject
GO
</code>```

答:
Tom H.'s comment on my question solved this:

I've seen a post that said that this problem can be caused by a corruption in the connection pool. Make sure that your connections are all being closed properly. You can read some more ways to diagnose/fix the problem here: http://www.ksvali.com/2010/08/solution-to-random-error-column-does-not-belong-to-table/

Body:
I have a stored procedure that gets called hundreds of times per minute.  Every once in a rare while I will get an exception that a column does not exist in the query.  Here is the exception:

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.ArgumentException: Column 'SubjectID' does not belong to table .

[ArgumentException: Column 'SubjectID' does not belong to table .]
   System.Data.DataRow.GetDataColumn(String columnName) +1775157
   System.Data.DataRow.get_Item(String columnName) +13
   System.Data.DataTableReader.get_Item(String name) +66

Here is the C# that calls the stored proc:

DataTableReader dtr;
        dtr = Util.getDepartmentsByTerm(term);
        ddlSubject.Items.Add(new ListItem("Select A Subject...", ""));
        while (dtr.Read())
        {
            //The following line throws the exception!
            var value = (string)dtr["SubjectID"];
            var text = (string)dtr["title"];
            var count = (int) dtr["Count"];
            //if (!text.Contains("(0)"))
            if(count > 0)
                ddlSubject.Items.Add(new ListItem(text, value));
        }

Pretty simple... here's the stored procedure:

ALTER PROCEDURE [dbo].[selectDepartmentsByTerm]

(

@term nvarchar(50),
@version int

)

AS
SELECT SubjectID, Subject as Title,(select count(distinct courseno)
  from RegistrationBlock WITH (NOLOCK)
 where RegistrationBlock.Subject = Subjects.SubjectID
   and RegistrationBlock.version = @version
   and (@term = '' OR RegistrationBlock.term = @term)) as "Count"
  FROM Subjects WITH (NOLOCK)
 where Version = @version
 order by subject
GO


问:
find pairs of numbers where cube is equal to square
We are given a number N and we have to find pairs i and j where i^3=j^2

For example, let N=50 so for this we will have 3 pairs (1,1),(4,8),(9,27)
basically, we have to find pairs where the cube of one number is the same as the square of the other number in a given pair

the constraint is

1<=N<10^6

1<=i,j<N

Naive approach use 2 for loops iterate through each element and get those pairs where cube is equal to sum time complexity is O(n*2)

```<code>def get_pair(N):
    for i in range(1,N):
        for j in range(1,N):
            if i*i*i==j*j:
                print(i,j)
N=50
get_pair(N)
</code>```

what will be an optimal way to solve this problem with a better time complexity?

答:
Another naive approach could be to use the "basic" values ?

```<code>def get_pair(N):
    for i in range(N):
        if(i**3 > MAX):
            break    # Limit to the max you want, and i**3 > i**2 if i > 1

        print(i**2, i**3)
</code>```

Time complexity seems to be O(n) (Not an expert, so correct me if i'm wrong)

This is made so that the first element cubed == second element squared:

```<code>first = a^2
second = a^3

first^3 = a^(2*3) = a^6
second^2 = a^(3*2) = a^6
</code>```

Body:
We are given a number N and we have to find pairs i and j where i^3=j^2

For example, let N=50 so for this we will have 3 pairs (1,1),(4,8),(9,27)
basically, we have to find pairs where the cube of one number is the same as the square of the other number in a given pair

the constraint is

1<=N<10^6

1<=i,j<N

Naive approach use 2 for loops iterate through each element and get those pairs where cube is equal to sum time complexity is O(n*2)

def get_pair(N):
    for i in range(1,N):
        for j in range(1,N):
            if i*i*i==j*j:
                print(i,j)
N=50
get_pair(N)

what will be an optimal way to solve this problem with a better time complexity?

Body:
Another naive approach could be to use the "basic" values ?

def get_pair(N):
    for i in range(N):
        if(i**3 > MAX):
            break    # Limit to the max you want, and i**3 > i**2 if i > 1

        print(i**2, i**3)

Time complexity seems to be O(n) (Not an expert, so correct me if i'm wrong)

This is made so that the first element cubed == second element squared:

first = a^2
second = a^3

first^3 = a^(2*3) = a^6
second^2 = a^(3*2) = a^6


问:
JetBrains shows Error:Python 3.1 has reached end-of-life date and is no longer suppported in Python Plugin even though I installed Python Version 3.10

I configured python 3.6 in JetBrains initially but uninstalled it today since it reached end-of-life. I installed version 3.10 but I keep getting the error that "Python 3.1 has reached end of date."

Clicking on 'Configure Python Interpreter'>Project Settings>Modules>Dependencies>Python 3.10 doesn't solve the problem.

Using File->settings and searching for interpreter shows only this option . Used "Use SDK of module" and "specified Python Interpreter" options but the error persists. I can't find any other resolution on the JetBrains support page for this. Thank you for your help!

I tried removing all existing configuration SDK from File | Project Structure | Platform Settings | SDKs and adding Python 3.10 again.

A screenshot of the interpreter configured in an existing virtual environment is attached here.

When I click ok, I get this error.

I figured this may be since my venv was initially configured in the 3.6 version but I'm not able to configure a new venv with Python 3.10. (The Ok option is greyed out)

While trying to add venv manually using /venv or /venv2, I get the error- 'Specified path cannot be found'

答:
I had the same problem. My solution: delete Pycharm and install it again (maybe export your settings): https://www.jetbrains.com/pycharm/download/#section=windows

Fixed the problem for me.


问:
How to turn off automatic line splitting in vim?
I mainly use neovim and I found that setting :set textwidth=0 in ${HOME}/.config/nvim/init.vim has no effect.Textwidth is always 78.

The reason is that other scripts overwrite my settings, I found textwidth=78 in other scripts:

$ sudo find ! -path "./home/**" -name "*.vim" ! -path "./proc" ! -path "./run/**" ! -path "./root/**" | xargs grep "textwidth=78"
./usr/share/nvim/runtime/syntax/ada.vim:"vim: textwidth=78 nowrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/indent/ada.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/ftplugin/changelog.vim:    setlocal textwidth=78
./usr/share/nvim/runtime/ftplugin/help.vim:setlocal formatoptions+=tcroql textwidth=78
./usr/share/nvim/runtime/ftplugin/javascript.vim:" vim: textwidth=78 tabstop=8 shiftwidth=4 softtabstop=4 expandtab
./usr/share/nvim/runtime/ftplugin/ada.vim:" vim: textwidth=78 nowrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/ftplugin/occam.vim:setlocal textwidth=78
./usr/share/nvim/runtime/compiler/decada.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/autoload/adacomplete.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/autoload/decada.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/autoload/ada.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
```

The number of these scripts is a bit large, I don't want to delete them one by one, and I want to avoid modifying scripts that I don't understand as much as possible.

How should I force automatic line breaking off?

答:
You should take a look at :help fo-table as it's actually your :h 'formatoptions that is responsible to wrap the lines when typing in insert mode, see the t letter.

You can remove the letter with:

```<code>set formatoptions-=t
</code>```

You can identify where an option is set with the :h :verbose command:

```<code>:verbose set tw?
  textwidth=80
        Last set from ~/.config/.vim/vimrc line 131
Press ENTER or type command to continue
</code>```

Body:
I mainly use neovim and I found that setting :set textwidth=0 in ${HOME}/.config/nvim/init.vim has no effect.Textwidth is always 78.

The reason is that other scripts overwrite my settings, I found textwidth=78 in other scripts:

$ sudo find ! -path "./home/**" -name "*.vim" ! -path "./proc" ! -path "./run/**" ! -path "./root/**" | xargs grep "textwidth=78"
./usr/share/nvim/runtime/syntax/ada.vim:"vim: textwidth=78 nowrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/indent/ada.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/ftplugin/changelog.vim:    setlocal textwidth=78
./usr/share/nvim/runtime/ftplugin/help.vim:setlocal formatoptions+=tcroql textwidth=78
./usr/share/nvim/runtime/ftplugin/javascript.vim:" vim: textwidth=78 tabstop=8 shiftwidth=4 softtabstop=4 expandtab
./usr/share/nvim/runtime/ftplugin/ada.vim:" vim: textwidth=78 nowrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/ftplugin/occam.vim:setlocal textwidth=78
./usr/share/nvim/runtime/compiler/decada.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/autoload/adacomplete.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/autoload/decada.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab
./usr/share/nvim/runtime/autoload/ada.vim:" vim: textwidth=78 wrap tabstop=8 shiftwidth=3 softtabstop=3 noexpandtab

The number of these scripts is a bit large, I don't want to delete them one by one, and I want to avoid modifying scripts that I don't understand as much as possible.

How should I force automatic line breaking off?

Body:
You should take a look at :help fo-table as it's actually your :h 'formatoptions that is responsible to wrap the lines when typing in insert mode, see the t letter.

You can remove the letter with:

set formatoptions-=t

You can identify where an option is set with the :h :verbose command:

:verbose set tw?
  textwidth=80
        Last set from ~/.config/.vim/vimrc line 131
Press ENTER or type command to continue


问:
How to change orientation of each item in a ggplot2 legend?

The above shows 2 legends, one where each item is placed in a new column and one where each item is placed in a new row.

How can I control for that?

答:
This is controlled by the nrow and ncol arguments to guide_legend().

You can call guide_legend() either within guides():

```<code>plot +
  guides(color = guide_legend(nrow = 1))
</code>```

…or within scale_*():

```<code>plot +
  scale_color_discrete(guide = guide_legend(nrow = 1))
</code>```

Body:
This is controlled by the nrow and ncol arguments to guide_legend().

You can call guide_legend() either within guides():

plot +
  guides(color = guide_legend(nrow = 1))

…or within scale_*():

plot +
  scale_color_discrete(guide = guide_legend(nrow = 1))


问:
Can I COUNTIF across multiple columns in an array formula?
Seems simple to me..

I want to do something along the lines of =Countif(A2:X , "Yes")

I would wrap this in an arrayformula with a simple IF(A2:A = "" ,"" .....

I want it to bring back the number of "Yes" per row

So if row 2 has 12 yes' then bring back 12, row 3 has 7 so 7 etc

This has worked to an extent but brings back the count across the entire range rather than split by row

答:
Try:

```<code>=ArrayFormula(IF(A2:A="",,MMult(N(A2:X="Yes"),Sequence(Columns(A2:X))^0)))
</code>```

Or

```<code>=ArrayFormula(IF(A2:A="",,Len(RegexReplace(RegexReplace(Transpose(Query(Transpose(A2:X),,9^9)),"(?i)\bYes\b","~"),"[^~]",))))
</code>```

Or

```<code>=ArrayFormula(IF(A2:A="",,Len(Substitute(Transpose(Query(Transpose(IF(A2:X<>"Yes",,"~")),,9^9))," ",))))
</code>```

Update

If I wanted to ammend this formula to do if A2:X = No AND A1:X1 contains, for instance (AG) how would I do this?

```<code>=ArrayFormula(IF(A2:A="",,MMult((A2:X="No")*RegexMatch(A1:X1,"AG"),Sequence(Columns(A2:X))^0)))
</code>```

Body:
Try:

=ArrayFormula(IF(A2:A="",,MMult(N(A2:X="Yes"),Sequence(Columns(A2:X))^0)))

Or

=ArrayFormula(IF(A2:A="",,Len(RegexReplace(RegexReplace(Transpose(Query(Transpose(A2:X),,9^9)),"(?i)\bYes\b","~"),"[^~]",))))

Or

=ArrayFormula(IF(A2:A="",,Len(Substitute(Transpose(Query(Transpose(IF(A2:X<>"Yes",,"~")),,9^9))," ",))))

Update

If I wanted to ammend this formula to do if A2:X = No AND A1:X1 contains, for instance (AG) how would I do this?

=ArrayFormula(IF(A2:A="",,MMult((A2:X="No")*RegexMatch(A1:X1,"AG"),Sequence(Columns(A2:X))^0)))


问:
How to bind Telerik MVC grid to DropDownList via Ajax?
I am trying to bind a dropdownlist to a telerik grid, so that when the value of the dropdownlist changes the grid will update via ajax to show results. Here is my code so far:

IndexView:

<% Html.RenderPartial("AptProfileFilter"); %>
    <%= Html.Telerik().Grid(Model.profiles)//Initial Server Binding
             .Name("Profiles").DataBinding(dataBinding => dataBinding

             .Ajax()

             .Update("_AjaxBinding", "AptProfile", new {id = (string)ViewData["BuildingID"]}))
             .Columns(columns =>
                {
               columns.Bound(p => p.AptProfileID).Width(100);
               columns.Bound(p => p.Apartment.Building.Complex.Name).Width(100);
               columns.Bound(p => p.Apartment.Building.BuildingID).Width(100);
               columns.Bound(p => p.Apartment.AptRate).Width(100);
                })
              .Pageable()
              .Sortable()

I used FireBug to determine that the correct data is being posted( after selecting a element from my dropdownlist)
back to the Data collection in the GridModel class, but I do not understand why it is not updating the Grid with this new data?

I am very new to web development. Thanks for your help!

答: I've been wrestling with this too. take a look at the link below (bottom of comment), in which I asked the same type of question. In my case, I managed to get this working, but still have some questions about HOW I got it working. Anyway, I hope this helps ... Also, in my case, I'm using Razor views, which you might not be, based upon you use of the <% operators ... Telerik MVC Grid: How to use DropDownList in a column?</p>

ContentLicense: CC BY-SA 2.5


问:
How to check whether a variable is a class or not?
I was wondering how to check whether a variable is a class (not an instance!) or not.

I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type a class would have.

For example, in the following code

```<code>class Foo:
    pass

isinstance(Foo, **???**) # i want to make this return True.
</code>```

I tried to substitute  "class" with ???, but I realized that class is a keyword in python.

答:
Well, inspect.isclass is not working for me, instead, try this

class foo:
    pass

var = foo()

if str(type(var)).split(".")[0] == "<class '__main__":
    print("this is a class")
else:
    print(str(type(var)).split(".")[0])
```

So basically, type(var) is <class 'a type'>

Example: <class 'int'
But, when var is a class, it will appear something like <class '__main__.classname'>

So we split the string into <class '__main__ and we compare using if, if the string fit perfectly then it's a class

OwnerDisplayName: jeeyoungk

Body:
I was wondering how to check whether a variable is a class (not an instance!) or not.

I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type a class would have.

For example, in the following code

class Foo:
    pass

isinstance(Foo, **???**) # i want to make this return True.

I tried to substitute  "class" with ???, but I realized that class is a keyword in python.

LastEditorDisplayName: Jonathan Leffler

Body:
Well, inspect.isclass is not working for me, instead, try this

class foo:
    pass

var = foo()

if str(type(var)).split(".")[0] == "<class '__main__":
    print("this is a class")
else:
    print(str(type(var)).split(".")[0])

So basically, type(var) is <class 'a type'>

Example: <class 'int'
But, when var is a class, it will appear something like <class '__main__.classname'>

So we split the string into <class '__main__ and we compare using if, if the string fit perfectly then it's a class


问:
Finding the unit gradient vectors of an image
I am trying to find the unit gradient vectors of an image but am not sure how to begin with this. Are there any specific OpenCV or other Python package commands that can be used to achieve this? The formula that I have to implement is the following:
This will calculate the unit gradient vectors of the image in both the x and y directions.

Thank you in advance for any help or advice!

答:
Yes, you can with opencv-python Sobel/Scharr

Unfortunately I won't have time to provide a detailed answer, however I can share a few commented snippets that will be great starting points:

computing:

take an odd neighbourhood (e.g. 3x3)

calculate horizontal change (Gx = I(x+1,y) - I(x-1,y)) and vertical change (Gy = I(x,y+1) - I(x,y-1))

calculate gradient magnitude (mag = sqrt(Gx*Gx + Gy*Gy)) and orientation (o = math.degrees(atan2(Gy,Gx)))

Sobel examples:

import numpy as np
import cv2
# gradient kernels (3x3)

Gx = [ -1, 0, +1,
       -2, 0, +2,
       -1, 0, +1]

Gy = [ -1,-2, -1,
        0, 0,  0,
       +1,+2, +1]

# image
image = cv2.imread("yourImageHere.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Original", image)

# compute gradients along the X and Y axis, respectively
gX = cv2.Sobel(gray, ddepth=cv2.CV_64F, dx=1, dy=0)
gY = cv2.Sobel(gray, ddepth=cv2.CV_64F, dx=0, dy=1)

# the `gX` and `gY` images are now of the floating point data type,
# so we need to take care to convert them back to an unsigned 8-bit
# integer representation so other OpenCV functions can utilize them
gX = cv2.convertScaleAbs(gX)
gY = cv2.convertScaleAbs(gY)

# combine the sobel X and Y representations into a single image
sobelCombined = cv2.addWeighted(gX, 0.5, gY, 0.5, 0)
```
<p>manually computing magnitude and orientation</p>
<pre class="lang-py prettyprint-override"><code># compute gradients along the X and Y axis, respectively
gX = cv2.Sobel(gray, cv2.CV_64F, 1, 0)
gY = cv2.Sobel(gray, cv2.CV_64F, 0, 1)

# compute the gradient magnitude and orientation respectively
mag = np.sqrt((gX ** 2) + (gY ** 2))
orientation = np.arctan2(gY, gX) * (180 / np.pi) % 180

# find all pixels that are within the upper and low angle boundaries
idxs = np.where(orientation >= args["lower_angle"], orientation, -1)
idxs = np.where(orientation <= args["upper_angle"], idxs, -1)
mask = np.zeros(gray.shape, dtype="uint8")
mask[idxs > -1] = 255

# show the images
cv2.imshow("Mask", mask)
</code>```

Body:
Yes, you can with opencv-python Sobel/Scharr

Unfortunately I won't have time to provide a detailed answer, however I can share a few commented snippets that will be great starting points:

computing:

take an odd neighbourhood (e.g. 3x3)

calculate horizontal change (Gx = I(x+1,y) - I(x-1,y)) and vertical change (Gy = I(x,y+1) - I(x,y-1))

calculate gradient magnitude (mag = sqrt(Gx*Gx + Gy*Gy)) and orientation (o = math.degrees(atan2(Gy,Gx)))

Sobel examples:

import numpy as np
import cv2
# gradient kernels (3x3)

Gx = [ -1, 0, +1,
       -2, 0, +2,
       -1, 0, +1]

Gy = [ -1,-2, -1,
        0, 0,  0,
       +1,+2, +1]

# image
image = cv2.imread("yourImageHere.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow("Original", image)

# compute gradients along the X and Y axis, respectively
gX = cv2.Sobel(gray, ddepth=cv2.CV_64F, dx=1, dy=0)
gY = cv2.Sobel(gray, ddepth=cv2.CV_64F, dx=0, dy=1)

# the `gX` and `gY` images are now of the floating point data type,
# so we need to take care to convert them back to an unsigned 8-bit
# integer representation so other OpenCV functions can utilize them
gX = cv2.convertScaleAbs(gX)
gY = cv2.convertScaleAbs(gY)

# combine the sobel X and Y representations into a single image
sobelCombined = cv2.addWeighted(gX, 0.5, gY, 0.5, 0)

manually computing magnitude and orientation

# compute gradients along the X and Y axis, respectively
gX = cv2.Sobel(gray, cv2.CV_64F, 1, 0)
gY = cv2.Sobel(gray, cv2.CV_64F, 0, 1)

# compute the gradient magnitude and orientation respectively
mag = np.sqrt((gX ** 2) + (gY ** 2))
orientation = np.arctan2(gY, gX) * (180 / np.pi) % 180

# find all pixels that are within the upper and low angle boundaries
idxs = np.where(orientation >= args["lower_angle"], orientation, -1)
idxs = np.where(orientation <= args["upper_angle"], idxs, -1)
mask = np.zeros(gray.shape, dtype="uint8")
mask[idxs > -1] = 255

# show the images
cv2.imshow("Mask", mask)


问:
Call a function according to its string name
I have a code which would be very repetitive, which according to the name of the string of an array executes one function or another.

I give an example of a code as I could do it.

```<code>// I use underscore in NodeJS

_.each(refresh, (value, key) => {

    if(key === 'station') {

        station.add({ id: value });

    } else if(key === 'concentrator') {

        concentrator.add({ id: value });

    } else if....
});
</code>```

It is possible to run the function according to your string to avoid so much checking with IF, etc.

```<code>[key].add({ id: value });
</code>```

I have been watching several hours on the internet about the use of call, apply, etc; but I do not understand how it works well, perhaps because my knowledge of Javascript is not advanced.

Thanks !

答:
Creating an anonymous function on an object is the best approach. As you can use the key to call the method.

Here is an example in code pen:
https://codepen.io/liam-hamblin/pen/KKyapNP

The code above takes in the key used to assign the function and does not require any checks. However, it is always the best approach to check that the key exists before calling.

```<code>const operations = {};

operations.add = (obj) => {
  document.write("add - ");
  document.write(JSON.stringify(obj));
}

operations.subtract = (obj) => {
  document.write("subtract - ");
  document.write(JSON.stringify(obj));
}

const input = prompt("Enter Function Name, type either subtract or add");

if (operations[input]) {
  operations[input]({id:1});
} else {
  document.write("no matching method")
}
</code>```

Body:
I have a code which would be very repetitive, which according to the name of the string of an array executes one function or another.

I give an example of a code as I could do it.

// I use underscore in NodeJS

_.each(refresh, (value, key) => {

    if(key === 'station') {

        station.add({ id: value });

    } else if(key === 'concentrator') {

        concentrator.add({ id: value });

    } else if....
});

It is possible to run the function according to your string to avoid so much checking with IF, etc.

[key].add({ id: value });

I have been watching several hours on the internet about the use of call, apply, etc; but I do not understand how it works well, perhaps because my knowledge of Javascript is not advanced.

Thanks !

Body:
Creating an anonymous function on an object is the best approach. As you can use the key to call the method.

Here is an example in code pen:
https://codepen.io/liam-hamblin/pen/KKyapNP

The code above takes in the key used to assign the function and does not require any checks. However, it is always the best approach to check that the key exists before calling.

const operations = {};

operations.add = (obj) => {
  document.write("add - ");
  document.write(JSON.stringify(obj));
}

operations.subtract = (obj) => {
  document.write("subtract - ");
  document.write(JSON.stringify(obj));
}

const input = prompt("Enter Function Name, type either subtract or add");

if (operations[input]) {
  operations[input]({id:1});
} else {
  document.write("no matching method")
}


问:
Speeding up complex Android View Inflation
I have a relatively big XML layout (38 kB, 600 lines) with hierarchy like:

```<code><ScrollView>
 <LinearLayout>
  <TabHost>
   <LinearLayout>
    <FrameLayout> //tab widget
     <LinearLayout> //tab content
      <LinearLayout> //section
       <TextView> //section name
       <LinearLayout orientation="horizontal"> //item 1 box
        <TextView> //item 1 title
        <Spinner> //item 1 picker
       </LinearLayout>
       <LinearLayout> //item 2 box
        <TextView> //item 2 title
        <Spinner> //item 2 picker
       </LinearLayout>
       ...  //18 other items
      </LinearLayout>
      ... //4 other sections with 15 items each
</>
</code>```

It is a data entry form that has to have that many items and the best I can do now is to do to wrap setContentView and loading of data to the spinners in an AsyncTask with a "Loading..." dialog.

Does extensive using of themes also slow down the view inflation? The view inflater wouldn't need to look in loaded theme.xml, but if I were to inline the theme into the layout xml, it would also increase the size of the XML considerably, thus slow down the parser.

Is there something I could do to simplify the layout that would make it load at least twice as fast?
I'm thinking that I might try to get rid of the horizontal LinearLayouts, and build the "section" with TableLayout.

答:
First, three general comments:

You really want to avoid layouts that deeply nested.

Consider using RelativeLayout to replace nested LinearLayouts.

Use the layout_opt tool to get some suggestions on layout optimizations.

Now, more on #1 … have you considered writing your own layout? It sounds complex at first, but it can sometimes drastically improve layout performance. For example, if RelativeLayout doesn't serve the purpose, you may be able to combine your Linear-Frame-Linear-Linear chain into a single custom layout.

Lastly, is there a reason your tab indicators are scrollable? That seems like a navigation/UX problem.

Body:
I have a relatively big XML layout (38 kB, 600 lines) with hierarchy like:

<ScrollView>
 <LinearLayout>
  <TabHost>
   <LinearLayout>
    <FrameLayout> //tab widget
     <LinearLayout> //tab content
      <LinearLayout> //section
       <TextView> //section name
       <LinearLayout orientation="horizontal"> //item 1 box
        <TextView> //item 1 title
        <Spinner> //item 1 picker
       </LinearLayout>
       <LinearLayout> //item 2 box
        <TextView> //item 2 title
        <Spinner> //item 2 picker
       </LinearLayout>
       ...  //18 other items
      </LinearLayout>
      ... //4 other sections with 15 items each
</>

It is a data entry form that has to have that many items and the best I can do now is to do to wrap setContentView and loading of data to the spinners in an AsyncTask with a "Loading..." dialog.

Does extensive using of themes also slow down the view inflation? The view inflater wouldn't need to look in loaded theme.xml, but if I were to inline the theme into the layout xml, it would also increase the size of the XML considerably, thus slow down the parser.

Is there something I could do to simplify the layout that would make it load at least twice as fast?
I'm thinking that I might try to get rid of the horizontal LinearLayouts, and build the "section" with TableLayout.


问:
Batch Script task getting cancelled because of mysterious input
I have defined a Batch Script task in my Azure DevOps pipeline.  I can see from the logs that it starts and runs the first few commands in the bat file, but then all of a sudden I see "Cancelled" in the log and the task finishes as a successful task.

My bat file runs a custom executable that allows cancelling mid way through if it detects any input from the console.  This is what appears to be happening when the bat is run by the pipeline.

Why would the pipeline be entering input into the console window while the bat is still executing, and how do I get it to stop?

Batch Script Task Output:

Press Enter to stop

Running executable

Cancelled

executable finished with error code: -1

答:
At this point, I'm not even sure AzureDevOps was really entering input into the Console the ways I thought it was.  What I did ultimately discover, though, is that when a console app is run by AzureDevOps, it redirects all input, which prevents the console app from capturing the input for direction.  I ended up using this code to skip my logic that was looking for a "quit" operator when input is re-directed.</p>
```<code>        if (Environment.UserInteractive && !Console.IsInputRedirected)
        {
            // if don't test for UserInteractive, will run into issues when run by DevOps pipeline.
            // DevOps pipeline causes IsInputRedirected to be true, which results in this exception.
            // Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.

            Console.WriteLine("Press Enter to stop");
            while (true)
            {
                var input = Console.ReadKey();
                if (input.Key == ConsoleKey.Enter)
                {
                    // quit once enter is entered
                    return;
                }
            }
        }
        else
        {
            // if console does not allow user input, just wait until the task is cancelled
            ct.WaitHandle.WaitOne();
        }
</code>```

Body:
At this point, I'm not even sure AzureDevOps was really entering input into the Console the ways I thought it was.  What I did ultimately discover, though, is that when a console app is run by AzureDevOps, it redirects all input, which prevents the console app from capturing the input for direction.  I ended up using this code to skip my logic that was looking for a "quit" operator when input is re-directed.

        if (Environment.UserInteractive && !Console.IsInputRedirected)
        {
            // if don't test for UserInteractive, will run into issues when run by DevOps pipeline.
            // DevOps pipeline causes IsInputRedirected to be true, which results in this exception.
            // Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.

            Console.WriteLine("Press Enter to stop");
            while (true)
            {
                var input = Console.ReadKey();
                if (input.Key == ConsoleKey.Enter)
                {
                    // quit once enter is entered
                    return;
                }
            }
        }
        else
        {
            // if console does not allow user input, just wait until the task is cancelled
            ct.WaitHandle.WaitOne();
        }


答:
You do this with one loop (and minimal iterations) if you know that that pairs (x, y) are always y = x * i, this means you can use:

```<code>def get_pair(N):
    i = 1
    a = 1
    while a * i < N:
        b = a * i
        print(a,b)
        i += 1
        a = i**2

N=50
get_pair(N)
</code>```

This gets all 3 pairs:

```<code>1 1
4 8
9 27
</code>```

In only 3 total iterations.

Title: find pairs of numbers where cube is equal to square

Body:
You do this with one loop (and minimal iterations) if you know that that pairs (x, y) are always y = x * i, this means you can use:

def get_pair(N):
    i = 1
    a = 1
    while a * i < N:
        b = a * i
        print(a,b)
        i += 1
        a = i**2

N=50
get_pair(N)

This gets all 3 pairs:

1 1
4 8
9 27

In only 3 total iterations.


问:
Flutter: setState in TextButton not working
Dice image not changing on onPress

setState not setting dice image for random number

child: Image.asset('images/dice$leftDiceNumber.png'),  not working but

child: Image.asset('images/dice2.png'), is working that means hard code is working

var leftDiceNumber = 3; getting only dice3.png as i initialize it for leftDiceNumber

Please help for getting random image when onPress

No errors in App

```<code>class DicePage extends StatefulWidget {
  const DicePage({Key? key}) : super(key: key);

  @override
  _DicePageState createState() => _DicePageState();
}

class _DicePageState extends State<DicePage> {
  @override
  Widget build(BuildContext context) {
    var leftDiceNumber = 3;
    return Center(
      child: Row(
        children: [
          Expanded(
            child: TextButton(
              onPressed: () {
                setState(() {
                  leftDiceNumber = Random().nextInt(6) + 1;
                  print(leftDiceNumber); // getting value in console
                });
              },
              child: Image.asset('images/dice$leftDiceNumber.png'),
                      //child: Image.asset('images/dice1.png'), // ( works )
            ),),],
      ),);}}
</code>```

答:
That is because every time you call setState() it calls the build method, and you have defined leftDiceNumber = 3 inside the build method. So even though the setState() changes the value it again gets set to 3.

Solution: Move var leftDiceNumber = 3; outside the build method.

class _DicePageState extends State<DicePage> {
  var leftDiceNumber = 3;

@override
  Widget build(BuildContext context) {
    return YourWidget();
  }
}
```

Body:
Dice image not changing on onPress

setState not setting dice image for random number

child: Image.asset('images/dice$leftDiceNumber.png'),  not working but

child: Image.asset('images/dice2.png'), is working that means hard code is working

var leftDiceNumber = 3; getting only dice3.png as i initialize it for leftDiceNumber

Please help for getting random image when onPress

No errors in App

class DicePage extends StatefulWidget {
  const DicePage({Key? key}) : super(key: key);

  @override
  _DicePageState createState() => _DicePageState();
}

class _DicePageState extends State<DicePage> {
  @override
  Widget build(BuildContext context) {
    var leftDiceNumber = 3;
    return Center(
      child: Row(
        children: [
          Expanded(
            child: TextButton(
              onPressed: () {
                setState(() {
                  leftDiceNumber = Random().nextInt(6) + 1;
                  print(leftDiceNumber); // getting value in console
                });
              },
              child: Image.asset('images/dice$leftDiceNumber.png'),
                      //child: Image.asset('images/dice1.png'), // ( works )
            ),),],
      ),);}}


问:
Count the number of variables containing objects
I have an issue with .count. Its to do with the way it counts objects and also arrays containing objects.

For dull reasons, I have a situation where I don't know if what is being passed into my function is a single array of objects or 2 or more variables holding array lists of objects.

I though it would be easy to detect this. But because of the way count tries to help me out I am having trouble. When 2 or more arrays of objects are returned count reflects the number of arrays. But when only one is return count reflects the amount of objects in that array.

Simplified demo using simple arrays:

```<code>$Arr1 = "a","b","c"
$Arr2 ="d","f","e"

$arrayjoined = $Arr1,$Arr2

#count showing the number of arrays = 2
$arrayjoined.count

# Count on just one array = 3
$Arr1.count
</code>```

My original function works apart from occasions when only one array is returned. Is there any thing I can do to check for this, or force the count to return 1 to reflect just one array returned?

PS. I know I can use += to get the results into the same array in the example above but I can't do this with the arrays coming into my function.

答:
So what can we do if we can to count arrays in a array

```<code>$Array = 1,2,3
$CountArray = $Array
$CountArray.Length
$CountArray.Count
</code>```

Will return

```<code>3
3
</code>```

We can instead prepend the array with a ,

```<code>$Array = 1,2,3
$CountArray = ,$Array
$CountArray.Length
$CountArray.Count
</code>```

Which will return

```<code>1
1
</code>```

You can also add to an array like this

```<code>$Array = @()
$Array += ,@(1,2,3)
$Array.Length
$Array.Count
</code>```

Returns

```<code>1
1
</code>```

Body:
I have an issue with .count. Its to do with the way it counts objects and also arrays containing objects.

For dull reasons, I have a situation where I don't know if what is being passed into my function is a single array of objects or 2 or more variables holding array lists of objects.

I though it would be easy to detect this. But because of the way count tries to help me out I am having trouble. When 2 or more arrays of objects are returned count reflects the number of arrays. But when only one is return count reflects the amount of objects in that array.

Simplified demo using simple arrays:

$Arr1 = "a","b","c"
$Arr2 ="d","f","e"

$arrayjoined = $Arr1,$Arr2

#count showing the number of arrays = 2
$arrayjoined.count

# Count on just one array = 3
$Arr1.count

My original function works apart from occasions when only one array is returned. Is there any thing I can do to check for this, or force the count to return 1 to reflect just one array returned?

PS. I know I can use += to get the results into the same array in the example above but I can't do this with the arrays coming into my function.

Body:
So what can we do if we can to count arrays in a array

$Array = 1,2,3
$CountArray = $Array
$CountArray.Length
$CountArray.Count

Will return

3
3

We can instead prepend the array with a ,

$Array = 1,2,3
$CountArray = ,$Array
$CountArray.Length
$CountArray.Count

Which will return

1
1

You can also add to an array like this

$Array = @()
$Array += ,@(1,2,3)
$Array.Length
$Array.Count

Returns

1
1


问:
crash the program by implementing a TextWatcher class
when I call addTextChangedListener() method for editText and I implement TextWatcher class and override 3 methods beforTextChanged() onTextChanged() afterTextChanged().
the program does not give any errors but the program fails whit the implementation of the TextWatcher class and when run the app this message is displayed:
"unfortunately, My Application1 has stopped"

this is code:

```<code> package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

    private static final String TAG= "MainActivity";
    Button btn1, btn2;
    ImageView imageView;
    EditText editText;
    CheckBox checkBox;
    Switch aSwitch;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1=findViewById(R.id.firstButton);
        btn2=findViewById(R.id.secondButton);
        imageView=findViewById(R.id.imageView);
        editText.findViewById(R.id.editText);
        checkBox.findViewById(R.id.checkBox);
        aSwitch.findViewById(R.id.swiClick);

        btn1.setText(R.string.btn);
        btn1.setTextColor(getResources().getColor(R.color.purple_700));
        btn1.setBackgroundColor(getResources().getColor(R.color.teal_700));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "click btn1");
            }
        });

        btn2.setOnClickListener(this);

        imageView.setScaleType(ImageView.ScaleType.FIT_START);

        Toast.makeText(this,"salam",Toast.LENGTH_SHORT).show();

        editText.addTextChangedListener(this);

    }
    @Override
    public void onClick(View v) {
        Log.d(TAG, "click btn2");
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        Toast.makeText(this, editText.getText(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
}
</code>```

in run part show these message:

```<code>  Install successfully finished in 1 s 492 ms.
$ adb shell am start -n "com.example.myapplication1/com.example.myapplication1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 1833 on device '-google_nexus_5-192.168.81.101:5555'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
I/art: Late-enabling -Xcheck:jni
W/System: ClassLoader referenced unknown path: /data/app/com.example.myapplication1-1/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication1, PID: 1833
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication1/com.example.myapplication1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
        at com.example.myapplication1.MainActivity.onCreate(MainActivity.java:36)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I/Process: Sending signal. PID: 1833 SIG: 9
</code>```

wheres problem?

答:
editText.findViewById(R.id.editText);

That it even compiles... Didn't you mean:

```<code>editText = findViewById(R.id.editText);?
</code>```

(You have other ones..)

Body:
when I call addTextChangedListener() method for editText and I implement TextWatcher class and override 3 methods beforTextChanged() onTextChanged() afterTextChanged().
the program does not give any errors but the program fails whit the implementation of the TextWatcher class and when run the app this message is displayed:
"unfortunately, My Application1 has stopped"

this is code:

 package com.example.myapplication1;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

    private static final String TAG= "MainActivity";
    Button btn1, btn2;
    ImageView imageView;
    EditText editText;
    CheckBox checkBox;
    Switch aSwitch;

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1=findViewById(R.id.firstButton);
        btn2=findViewById(R.id.secondButton);
        imageView=findViewById(R.id.imageView);
        editText.findViewById(R.id.editText);
        checkBox.findViewById(R.id.checkBox);
        aSwitch.findViewById(R.id.swiClick);

        btn1.setText(R.string.btn);
        btn1.setTextColor(getResources().getColor(R.color.purple_700));
        btn1.setBackgroundColor(getResources().getColor(R.color.teal_700));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "click btn1");
            }
        });

        btn2.setOnClickListener(this);

        imageView.setScaleType(ImageView.ScaleType.FIT_START);

        Toast.makeText(this,"salam",Toast.LENGTH_SHORT).show();

        editText.addTextChangedListener(this);

    }
    @Override
    public void onClick(View v) {
        Log.d(TAG, "click btn2");
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        Toast.makeText(this, editText.getText(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }
}

in run part show these message:

  Install successfully finished in 1 s 492 ms.
$ adb shell am start -n "com.example.myapplication1/com.example.myapplication1.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 1833 on device '-google_nexus_5-192.168.81.101:5555'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
I/art: Late-enabling -Xcheck:jni
W/System: ClassLoader referenced unknown path: /data/app/com.example.myapplication1-1/lib/x86
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication1, PID: 1833
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication1/com.example.myapplication1.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.EditText.findViewById(int)' on a null object reference
        at com.example.myapplication1.MainActivity.onCreate(MainActivity.java:36)
        at android.app.Activity.performCreate(Activity.java:6237)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I/Process: Sending signal. PID: 1833 SIG: 9

wheres problem?

Body:
editText.findViewById(R.id.editText);

That it even compiles... Didn't you mean:

editText = findViewById(R.id.editText);?

(You have other ones..)


问:
How to present an ISO 8601 time string more readably
I have an Oracle 12c database column called "lag_time" which is VARCHAR2, with values in the following format:

lag_time

PT2H16M33S

PT11H40M12S

PT11M33S

P17DT12H32M47S

P233DT11H21M54S

PT10M28S

....

....

I need some suggestions and solutions on how to present this in a more readable way - preferably as total minutes. How can I do that?

答:
You can use the to_dsinterval() function to convert your strings to intervals:

```<code>to_dsinterval(lag_time)
</code>```

And you can then extract the various elements, multiply each of them to get the equivalent minute value, and add them together; for complete minutes:

```<code>select lag_time, lag_interval,
  (extract(day from lag_interval) * 1440)
  + (extract(hour from lag_interval) * 24)
  + extract(minute from lag_interval) as total_minutes
from (
  select lag_time, to_dsinterval(lag_time) as lag_interval
  from your_table
)
</code>```

LAG_TIME
LAG_INTERVAL
TOTAL_MINUTES

PT2H16M33S
+000000000 02:16:33.000000000
64

PT11H40M12S
+000000000 11:40:12.000000000
304

PT11M33S
+000000000 00:11:33.000000000
11

P17DT12H32M47S
+000000017 12:32:47.000000000
24800

P233DT11H21M54S
+000000233 11:21:54.000000000
335805

PT10M28S
+000000000 00:10:28.000000000
10

or to include fractional minutes:

```<code>select lag_time, lag_interval,
  (extract(day from lag_interval) * 1440)
  + (extract(hour from lag_interval) * 24)
  + extract(minute from lag_interval)
  + (extract(second from lag_interval) / 60) as total_minutes
from (
  select lag_time, to_dsinterval(lag_time) as lag_interval
  from your_table
)
</code>```

LAG_TIME
LAG_INTERVAL
TOTAL_MINUTES

PT2H16M33S
+000000000 02:16:33.000000000
64.55

PT11H40M12S
+000000000 11:40:12.000000000
304.2

PT11M33S
+000000000 00:11:33.000000000
11.55

P17DT12H32M47S
+000000017 12:32:47.000000000
24800.78333333333333

P233DT11H21M54S
+000000233 11:21:54.000000000
335805.9

PT10M28S
+000000000 00:10:28.000000000
10.466666666666666667

db<>fiddle

Of course, since you're storing strings you won't necessarily have valid values; you can handle that with the default ... on conversion error clause if you need to, but it would be better to store an actual interval value. If you really need the string value you could also add a virtual column to your table that converts it to an interval.

The column name suggests to me that you will only ever have positive values; you'd need to do a bit more work to handle negative values properly.

Body:
You can use the to_dsinterval() function to convert your strings to intervals:

to_dsinterval(lag_time)

And you can then extract the various elements, multiply each of them to get the equivalent minute value, and add them together; for complete minutes:

select lag_time, lag_interval,
  (extract(day from lag_interval) * 1440)
  + (extract(hour from lag_interval) * 24)
  + extract(minute from lag_interval) as total_minutes
from (
  select lag_time, to_dsinterval(lag_time) as lag_interval
  from your_table
)

LAG_TIME
LAG_INTERVAL
TOTAL_MINUTES

PT2H16M33S
+000000000 02:16:33.000000000
64

PT11H40M12S
+000000000 11:40:12.000000000
304

PT11M33S
+000000000 00:11:33.000000000
11

P17DT12H32M47S
+000000017 12:32:47.000000000
24800

P233DT11H21M54S
+000000233 11:21:54.000000000
335805

PT10M28S
+000000000 00:10:28.000000000
10

or to include fractional minutes:

select lag_time, lag_interval,
  (extract(day from lag_interval) * 1440)
  + (extract(hour from lag_interval) * 24)
  + extract(minute from lag_interval)
  + (extract(second from lag_interval) / 60) as total_minutes
from (
  select lag_time, to_dsinterval(lag_time) as lag_interval
  from your_table
)

LAG_TIME
LAG_INTERVAL
TOTAL_MINUTES

PT2H16M33S
+000000000 02:16:33.000000000
64.55

PT11H40M12S
+000000000 11:40:12.000000000
304.2

PT11M33S
+000000000 00:11:33.000000000
11.55

P17DT12H32M47S
+000000017 12:32:47.000000000
24800.78333333333333

P233DT11H21M54S
+000000233 11:21:54.000000000
335805.9

PT10M28S
+000000000 00:10:28.000000000
10.466666666666666667

db<>fiddle

Of course, since you're storing strings you won't necessarily have valid values; you can handle that with the default ... on conversion error clause if you need to, but it would be better to store an actual interval value. If you really need the string value you could also add a virtual column to your table that converts it to an interval.

The column name suggests to me that you will only ever have positive values; you'd need to do a bit more work to handle negative values properly.


问:
Cant render my component data correctly in 'React Native' - 'Using Axios'
Currently, I'm having a weird issue with regards to rendering my API. (I'm using Expo GO)

I'm using Axios, which calls the API inside of a UseEffect once I get location of the device.
The problem I'm facing is that the screen only renders the fetched data once I save or cntrl+s on VS Code.

I've tried to log the array, get nothing once the function is called.
I've also tried adding a button to call the function instead, only then it renders, which makes sense as it triggers a re-render.

WHEN I ENTER THE COMPONENT:
enter image description here

WHEN I SAVE THE FILE, IT THEN FETCHES DATA:
enter image description here

Would be much appreciated if anyone can help, maybe I'm missing some basic knowledge of how this works. Thanks guys!

import axios from 'axios';
import { SafeAreaView, StyleSheet, Text, View, Button, Alert, ScrollView, RefreshControl } from 'react-native';
import React, { Component, useState, useEffect, createContext } from 'react';
import { winners } from '../screens/MainScreen';
import * as Location from 'expo-location';
import { useIsFocused } from '@react-navigation/native';

const API = () => {

  const resturant = winners;

  const isFocused = useIsFocused();

  const [NamesFound, setNamesFound] = useState(0);

  const APIKey ='xxxxxxxxxx';
  const [Result, SetResult] = useState([]);
  const [Names, SetNames] = useState([]);

  const [lat, Setlat] = useState();
  const [long, Setlong] = useState();

  // const [location, setLocation] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [address, setAddress] = useState(null);
  const [RestAddress, setRestAddress] = useState([]);
  const [refreshing, setRefreshing] = useState(false);

  const [loading, setLoading] = useState(true);

  const wait = (timeout) => {
    return new Promise(resolve => setTimeout(resolve, timeout));
  }

    const onRefresh = React.useCallback(() => {
      setRefreshing(true);
      wait(2000).then(() => setRefreshing(false));
    }, []);

  const SampleFunction=(item)=>{

    Alert.alert(item);

  }

  const getLocation = () => {
    (async () => {
      let { status } = await Location.requestForegroundPermissionsAsync();
      if (status !== 'granted') {
        setErrorMsg('Permission to access location was denied');
      }

      Location.setGoogleApiKey(APIKey);

      // console.log(status)

      let { coords } = await Location.getCurrentPositionAsync();

      // setLocation(coords);

      Setlat(coords.latitude);
      Setlong(coords.longitude);

      if (coords) {
        let { longitude, latitude } = coords;

        let regionName = await Location.reverseGeocodeAsync({
          longitude,
          latitude,
        });
        setAddress(regionName[0].city);
        console.log(regionName[0].city);
      }

    })();
  };

  var config = {
    method: 'get',
    url: 'https://maps.googleapis.com/maps/api/place/textsearch/json?location='+lat+','+long+'&key='+APIKey+'&status=&query='+resturant,
    headers: { }
  };

  useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          SetResult(response.results);
          console.log(Result.map((name)=> name.name));
          SetNames(Result.map((name)=> name.name))
          setNamesFound(Names.length);
          console.log('API function called.')
          console.log (Names);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      getLocation();
      fetchData();

  }, []);

  return(

    <SafeAreaView style={styles.container}>

      {loading && <Text>Loading....</Text>}
      {!loading && isFocused && (
        <><Text style={styles.MainText}>{NamesFound} {winners}s within {address}</Text><ScrollView
          style={styles.scroll}
          refreshControl={<RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh} />}
        >
          {Names.map((item, key) => (
            <Text key={key} style={styles.TextStyle} onPress={SampleFunction.bind(this, item)}> {item} </Text>)
          )}
        </ScrollView></>
      )}

      {/* <Button title='CLICK ME FOR API' onPress={CallAPI} style={styles.btn}></Button> */}

    </SafeAreaView>
  );
};```

答:
You have to change these lines

```<code>  useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          SetResult(response.results);
          console.log(Result.map((name)=> name.name));
          SetNames(Result.map((name)=> name.name))
          setNamesFound(Names.length);
          console.log('API function called.')
          console.log (Names);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      getLocation();
      fetchData();

  }, []);
</code>```

to something like this

```<code>
  useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          const newResult = response.results;
          SetResult(newResult);

          const newNames = newResult.map((name)=> name.name);
          console.log(newNames);
          SetNames(newNames)
          setNamesFound(newNames.length);
          console.log('API function called.')
          console.log (newNames);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      getLocation();
      fetchData();

  }, []);
</code>```

Please notice how I use newResult and newName, which are derived from the immediate response, to set the states instead of using the state variable Result and Names.

To understand the reason,

You have to know that setting a state variable by using its setter (e.g. SetResult, SetNames will not immediately assign the value to the variable.

```<code>// This is the 1st time React calls your function
const [Result, SetResult] = useState([]); // Now Result = []
const [Names, SetNames] = useState([]); // Also Names = []

useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          SetResult(response.results);
          // Result still = [] here

          SetNames(Result.map((name)=> name.name))
          // Names still = [], likewise

          console.log('API function called.')
          console.log (Names);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      getLocation();
      fetchData();

  }, []);

</code>```

React "re-render" when the state variable's setter is called, and the value is then assigned to the variable.

```<code>// This is the 2nd time React calls your function
// , and it does so because you call SetResult
const [Result, SetResult] = useState([]); // Now Result = [...] <-- now it has value
const [Names, SetNames] = useState([]); // Also Names = [] <-- but this is still an empty list
</code>```
```<code>// This is the 3rd time React calls your function
// , and it does so because you call SetNames
const [Result, SetResult] = useState([]); // Now Result = [...] <-- now it has value
const [Names, SetNames] = useState([]); // Also Names = [...] <-- now it has value
</code>```

If you really want to make a state variable to depend on another variable, you can do it like this (though not need for the case in your question).

```<code>const [Result, SetResult] = useState([]);
const [Names, SetNames] = useState([]);

  useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          SetResult(response.results);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      fetchData();

  }, []);

  useEffect(() => {
    SetNames(Result.map((name)=> name.name))
  }, [Result]);
</code>```

In your case, I think it's better to do like this

```<code>const [result, setResult] = useState([]);
const names = result.map((name)=> name.name);
const namesFound = names.length;

useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          setResult(response.results);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      fetchData();

  }, []);
</code>```

Tip: I rename the variables to make the leading characters lower case, this is the convention, and it will make your code more readable to other developers.

Body:
You have to change these lines

  useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          SetResult(response.results);
          console.log(Result.map((name)=> name.name));
          SetNames(Result.map((name)=> name.name))
          setNamesFound(Names.length);
          console.log('API function called.')
          console.log (Names);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      getLocation();
      fetchData();

  }, []);

to something like this

  useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          const newResult = response.results;
          SetResult(newResult);

          const newNames = newResult.map((name)=> name.name);
          console.log(newNames);
          SetNames(newNames)
          setNamesFound(newNames.length);
          console.log('API function called.')
          console.log (newNames);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      getLocation();
      fetchData();

  }, []);

Please notice how I use newResult and newName, which are derived from the immediate response, to set the states instead of using the state variable Result and Names.

To understand the reason,

You have to know that setting a state variable by using its setter (e.g. SetResult, SetNames will not immediately assign the value to the variable.

// This is the 1st time React calls your function
const [Result, SetResult] = useState([]); // Now Result = []
const [Names, SetNames] = useState([]); // Also Names = []

useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          SetResult(response.results);
          // Result still = [] here

          SetNames(Result.map((name)=> name.name))
          // Names still = [], likewise

          console.log('API function called.')
          console.log (Names);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      getLocation();
      fetchData();

  }, []);

React "re-render" when the state variable's setter is called, and the value is then assigned to the variable.

// This is the 2nd time React calls your function
// , and it does so because you call SetResult
const [Result, SetResult] = useState([]); // Now Result = [...] <-- now it has value
const [Names, SetNames] = useState([]); // Also Names = [] <-- but this is still an empty list

// This is the 3rd time React calls your function
// , and it does so because you call SetNames
const [Result, SetResult] = useState([]); // Now Result = [...] <-- now it has value
const [Names, SetNames] = useState([]); // Also Names = [...] <-- now it has value

If you really want to make a state variable to depend on another variable, you can do it like this (though not need for the case in your question).

const [Result, SetResult] = useState([]);
const [Names, SetNames] = useState([]);

  useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          SetResult(response.results);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      fetchData();

  }, []);

  useEffect(() => {
    SetNames(Result.map((name)=> name.name))
  }, [Result]);

In your case, I think it's better to do like this

const [result, setResult] = useState([]);
const names = result.map((name)=> name.name);
const namesFound = names.length;

useEffect(() => {

      const fetchData = async () =>{
        setLoading(true);
        try {
          const {data: response} = await axios(config);
          setResult(response.results);

        } catch (error) {
          console.error(error.message);
        }
        setLoading(false);
      }

      fetchData();

  }, []);

Tip: I rename the variables to make the leading characters lower case, this is the convention, and it will make your code more readable to other developers.


问:
SIM800l - Disable "SMS Ready" and "Call Ready" unsolicited messages
My problem is related to SIM800 connection messages.

I use the module with STM32 developlment board. Sometimes module is reporting SMS Ready and Call Ready messages respectively. When I start to send AT commands to the module, it may send these messages (it doesn't happens all the times).

However, the commands I previously sent are apparently unrelated (for example HTTP commands), and SMS Ready / Call Ready messages is coming while they are not expected.

Because of this reason, Keil is reporting "Can not access" message in the debug session. Is it possible that disabling these messages when the connection is established? Or it means that module has an unexpected reset?

答:
For me, receiving a lot of messagens Call and SMS ready was a problem on current not enough to keep the module working.

(You can check it too watching the led blinking, if it blinks 6/7 times and stop for a while and restart over again, you have the same problem)

Just to SIM800 keep working is necessary at least 700mA.
Ps.: You can connect directly to your battery 18650 (3.7V-4.2V).

If you are using TP4056 module, you must remember there is 1A max current. try to connect in parallel more than 1 TP4056.


问:
MySqlConversionException when accessing DateTime field from DataReader
I have a C# application over MySql, using MySQL Connector; I'm trying to make a
DataReader request, the query executes fine, however, when trying to access a DateTime field, i'm getting MySqlConversionException {"Unable to convert MySQL date/time value to System.DateTime"}

this is the prototype

```<code>if (dr != null && !dr.Read()) return;

sesion.Id = Convert.ToInt32(dr["id"]);
sesion.Usuario = Convert.ToInt32(dr["usuario"]);
sesion.Estado = Convert.ToByte(dr["estado"]);
// doesn't work
sesion.FchCreacion = Convert.ToDateTime(dr["fch_creacion"]);
</code>```

Any suggestions?
Thanks in advance

答:
This error sometimes occurs if you have zero datetime values in your MySQL database (00/00/0000 00:00). Try adding this to the end of your connection string:</p>

```<code>Allow Zero Datetime=true
</code>```

OwnerDisplayName: Jhonny D. Cano -Leftware-

Body:
I have a C# application over MySql, using MySQL Connector; I'm trying to make a
DataReader request, the query executes fine, however, when trying to access a DateTime field, i'm getting MySqlConversionException {"Unable to convert MySQL date/time value to System.DateTime"}

this is the prototype

if (dr != null && !dr.Read()) return;

sesion.Id = Convert.ToInt32(dr["id"]);
sesion.Usuario = Convert.ToInt32(dr["usuario"]);
sesion.Estado = Convert.ToByte(dr["estado"]);
// doesn't work
sesion.FchCreacion = Convert.ToDateTime(dr["fch_creacion"]);

Any suggestions?
Thanks in advance

Body:
This error sometimes occurs if you have zero datetime values in your MySQL database (00/00/0000 00:00). Try adding this to the end of your connection string:

Allow Zero Datetime=true

OwnerDisplayName: David M


问:
How to set a timeout to a specific service function in Spring Boot?
I am creating an app in which some actions in the service need to be asynchronous.

I set the global timeout for 1 minute in the AsyncConfigurer.

This is OK for most of the actions, but in some actions, I need to set a longer timeout. For example in the following service action:

```<code>@Async
public Object someLongFunction() {
</code>```

Can someone tell me how to set a specific timeout for a specific action?

答:
Just change the return type of the function to java.util.concurrent.Future

It has java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit) method that you can leverage to define custom timeout

Body:
I am creating an app in which some actions in the service need to be asynchronous.

I set the global timeout for 1 minute in the AsyncConfigurer.

This is OK for most of the actions, but in some actions, I need to set a longer timeout. For example in the following service action:

@Async
public Object someLongFunction() {

Can someone tell me how to set a specific timeout for a specific action?


问:
php image upload
How to make a basic PHP uploader? I want my images to save in my htdocs/myfolder/

Here is my code:

```
<form enctype="multipart/form-data" method="post" action="img_uploader.php">
    <input type="file" name="fileToUpload" /><br />
    <input type="submit" value="Upload File" />
</form>
```

答:
In the working directory is fine work upload but, uploading in the database at the same time is note working any one solve this problem? kindly.

function doInsert(){
if(isset($_POST['save'])){
if ( $_POST['BRANCHNAME'] == "" || $_POST['BRANCHLOCATION'] == "" || $_POST['BRANCHCONTACTNO'] == "" ) {
$messageStats = false;
message("All field is required!","error");
redirect('index.php?view=add');
}else{

$branch = New Branch();
$branch->BRANCHNAME     = $_POST['BRANCHNAME'];
$branch->BRANCHLOCATION       = $_POST['BRANCHLOCATION'];
$branch->BRANCHCONTACTNO    = $_POST['BRANCHCONTACTNO'];
$branch->BRANCHLEVEL          = $_POST['BRANCHLEVEL'];
$branch->BRANCHSTATUS         = $_POST['BRANCHSTATUS'];
$branch->BRANCHMANAGER      = $_POST['BRANCHMANAGER'];
$branch->BRANCHDESCRIPTION    = $_POST['BRANCHDESCRIPTION'];
//$branch->PICLOCATION        = $_POST['PICLOCATION'];

```<code>        $branch->_FILES       = $_POST['PICLOCATION'];

        $file =$_FILES['PICLOCATION'];

        $filename = $file['name'];
        $filepath = $file['tmp_name'];
        $fileerror = $file['error'];

        if ($fileerror == 0) {
            $destfile = 'photos/'.$filename;
            move_uploaded_file($filepath, $destfile);

        $branch->LATITUDE                       = $_POST["LATITUDE"];
        $branch->LONGITUDE                      = $_POST["LONGITUDE"];
        $branch->create();

        message("New Branch created successfully!", "success");
        redirect("index.php");

    }
    }
</code>```

}
}

Title: php image upload

Body:
How to make a basic PHP uploader? I want my images to save in my htdocs/myfolder/

Here is my code:

<form enctype="multipart/form-data" method="post" action="img_uploader.php">
    <input type="file" name="fileToUpload" />

    <input type="submit" value="Upload File" />
</form>

Body:
In the working directory is fine work upload but, uploading in the database at the same time is note working any one solve this problem? kindly.

function doInsert(){
if(isset($_POST['save'])){
if ( $_POST['BRANCHNAME'] == "" || $_POST['BRANCHLOCATION'] == "" || $_POST['BRANCHCONTACTNO'] == "" ) {
$messageStats = false;
message("All field is required!","error");
redirect('index.php?view=add');
}else{

$branch = New Branch();
$branch->BRANCHNAME     = $_POST['BRANCHNAME'];
$branch->BRANCHLOCATION       = $_POST['BRANCHLOCATION'];
$branch->BRANCHCONTACTNO    = $_POST['BRANCHCONTACTNO'];
$branch->BRANCHLEVEL          = $_POST['BRANCHLEVEL'];
$branch->BRANCHSTATUS         = $_POST['BRANCHSTATUS'];
$branch->BRANCHMANAGER      = $_POST['BRANCHMANAGER'];
$branch->BRANCHDESCRIPTION    = $_POST['BRANCHDESCRIPTION'];
//$branch->PICLOCATION        = $_POST['PICLOCATION'];

        $branch->_FILES       = $_POST['PICLOCATION'];

        $file =$_FILES['PICLOCATION'];

        $filename = $file['name'];
        $filepath = $file['tmp_name'];
        $fileerror = $file['error'];

        if ($fileerror == 0) {
            $destfile = 'photos/'.$filename;
            move_uploaded_file($filepath, $destfile);

        $branch->LATITUDE                       = $_POST["LATITUDE"];
        $branch->LONGITUDE                      = $_POST["LONGITUDE"];
        $branch->create();

        message("New Branch created successfully!", "success");
        redirect("index.php");

    }
    }

}
}


问:
How to set application_name for postgres connections in Elixir
The code below in config.exs will set the application_name in postgresql to "myapp".  How can I use the Elixir node name instead?  (using Kernel.node here causes an argument error)</p>

```<code>config :db, DB.Repo,
  adapter: Ecto.Adapters.Postgres,
  database: "ahv2",
  username: "troy",
  password: "pass",
  hostname: "localhost",
  parameters: [
    {:application_name, "myapp"}
  ]
</code>```

答:
Changing application_name type inside parameters from a tuple to list do the work and it works for me.</p>
```<code>config :db, DB.Repo,
  adapter: Ecto.Adapters.Postgres,
  database: "ahv2",
  username: "troy",
  password: "pass",
  hostname: "localhost",
  parameters: [
    application_name, "myapp"
  ]
</code>```

Body:
The code below in config.exs will set the application_name in postgresql to "myapp".  How can I use the Elixir node name instead?  (using Kernel.node here causes an argument error)

config :db, DB.Repo,
  adapter: Ecto.Adapters.Postgres,
  database: "ahv2",
  username: "troy",
  password: "pass",
  hostname: "localhost",
  parameters: [
    {:application_name, "myapp"}
  ]

Body:
Changing application_name type inside parameters from a tuple to list do the work and it works for me.

config :db, DB.Repo,
  adapter: Ecto.Adapters.Postgres,
  database: "ahv2",
  username: "troy",
  password: "pass",
  hostname: "localhost",
  parameters: [
    application_name, "myapp"
  ]


问:
Extracting custom object array from appsettings.json
I'm trying to bind appsettings file into a generic class, but currently I can't map List<object> values.

I have an appsettings.Development.json hierarchy like this:

```<code>{
    "AppSettings":{
        "ApplicationName":"FOO"
        "MyValues":[
            {
                "Name":"Tryout1",
                "QuestionCount": 7
            },
            {
                "Name":"Tryout2"
                "SettingName":"ABCDEFG"
            }
        ]
    }
}
</code>```

And my generic class is like this:

```<code>public class AppSettings
{
    public string ApplicationName {get;set;}
    public List<object> MyValues {get;set;}
}
</code>```

When I use below code to bind this appsettings.Development.json into the generic class like this:

```<code>static ConfigurationHelper()
{
    var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile($"appsettings.{environmentName}.json")
        .Build();

    try
    {
        var tryout = config.Get(typeof(AppSettings));
    }
    catch (Exception ex)
    {

        throw ex;
    }
}

</code>```

tryout variable has the ApplicationName filled with value foo but the MyValues is just an empty array.

I also tried using object[] instead of List<object> and at that point it recognizes the amount of objects but all of the elements have the value null.

I don't want the MyValues array to be pre-defined because every element can and will have different fields and I want to make this process as generic as possible. How can I achieve this?

答:
So, I found a way of achieving my goal, just not that straightforward but still pretty simple:

First I had to change my appsettings.Development.json file like this:

```<code>{
    "AppSettings":{
        "ApplicationName":"FOO"
        "MyValues":[
            "Tryout1": {
                "Name":"Tryout1",
                "QuestionCount": 7
            },
            "Tryout2": {
                "Name":"Tryout2"
                "SettingName":"ABCDEFG"
            }
        ]
    }
}
</code>```

After this change, another change in the generic type is necessary, as follows:

```<code>public class AppSettings
{
    public string ApplicationName {get;set;}
    public Dictionary<string, CustomBaseClass> MyValues {get;set;}
    public List<object> _MyValues {get;set;}
}

public class CustomBaseClass
{
    public string Name { get; set; }
}

public class Tryout1 : CustomBaseClass
{
    public int QuestionCount {get;set;}
}

public class Tryout2 : CustomBaseClass
{
    public string SettingName {get;set;}
}
</code>```

This base class is important because we can't really bind the appsettings to an object, we still need a class. And base class, helps us bind these custom values like this:

```<code>private static List<Type> CustomTypes = new List<Type> { typeof(Tryout1), typeof(Tryout2) };

static ConfigurationHelper()
{
    var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile($"appsettings.{environmentName}.json")
        .Build();

    try
    {
        AppSettings = config.Get<AppSettingsContainer>();

        foreach (var keyValuePair in AppSettings.MyValues)
        {
            var type = CustomTypes.Where(t => t.Name == keyValuePair.Key).FirstOrDefault();

            if (type != null)
            {
                var myValue = config.GetSection(string.Format("AppSettings:MyValues:{0}", keyValuePair.Key)).Get(type);

                if (job != null)
                {
                    AppSettings._MyValues.Add(myValue);
                }
            }
        }
    }
    catch (Exception ex)
    {

        throw ex;
    }
}
</code>```

This should solve this problem, and huge thanks to andrewlock.net because I got the inital Dictionary<string, T> idea from there.

Body:
I'm trying to bind appsettings file into a generic class, but currently I can't map List<object> values.

I have an appsettings.Development.json hierarchy like this:

{
    "AppSettings":{
        "ApplicationName":"FOO"
        "MyValues":[
            {
                "Name":"Tryout1",
                "QuestionCount": 7
            },
            {
                "Name":"Tryout2"
                "SettingName":"ABCDEFG"
            }
        ]
    }
}

And my generic class is like this:

public class AppSettings
{
    public string ApplicationName {get;set;}
    public List<object> MyValues {get;set;}
}

When I use below code to bind this appsettings.Development.json into the generic class like this:

static ConfigurationHelper()
{
    var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile($"appsettings.{environmentName}.json")
        .Build();

    try
    {
        var tryout = config.Get(typeof(AppSettings));
    }
    catch (Exception ex)
    {

        throw ex;
    }
}

tryout variable has the ApplicationName filled with value foo but the MyValues is just an empty array.

I also tried using object[] instead of List<object> and at that point it recognizes the amount of objects but all of the elements have the value null.

I don't want the MyValues array to be pre-defined because every element can and will have different fields and I want to make this process as generic as possible. How can I achieve this?

Body:
So, I found a way of achieving my goal, just not that straightforward but still pretty simple:

First I had to change my appsettings.Development.json file like this:

{
    "AppSettings":{
        "ApplicationName":"FOO"
        "MyValues":[
            "Tryout1": {
                "Name":"Tryout1",
                "QuestionCount": 7
            },
            "Tryout2": {
                "Name":"Tryout2"
                "SettingName":"ABCDEFG"
            }
        ]
    }
}

After this change, another change in the generic type is necessary, as follows:

public class AppSettings
{
    public string ApplicationName {get;set;}
    public Dictionary<string, CustomBaseClass> MyValues {get;set;}
    public List<object> _MyValues {get;set;}
}

public class CustomBaseClass
{
    public string Name { get; set; }
}

public class Tryout1 : CustomBaseClass
{
    public int QuestionCount {get;set;}
}

public class Tryout2 : CustomBaseClass
{
    public string SettingName {get;set;}
}

This base class is important because we can't really bind the appsettings to an object, we still need a class. And base class, helps us bind these custom values like this:

private static List<Type> CustomTypes = new List<Type> { typeof(Tryout1), typeof(Tryout2) };

static ConfigurationHelper()
{
    var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile($"appsettings.{environmentName}.json")
        .Build();

    try
    {
        AppSettings = config.Get<AppSettingsContainer>();

        foreach (var keyValuePair in AppSettings.MyValues)
        {
            var type = CustomTypes.Where(t => t.Name == keyValuePair.Key).FirstOrDefault();

            if (type != null)
            {
                var myValue = config.GetSection(string.Format("AppSettings:MyValues:{0}", keyValuePair.Key)).Get(type);

                if (job != null)
                {
                    AppSettings._MyValues.Add(myValue);
                }
            }
        }
    }
    catch (Exception ex)
    {

        throw ex;
    }
}

This should solve this problem, and huge thanks to andrewlock.net because I got the inital Dictionary<string, T> idea from there.


问:
jQuery Find and List all LI elements within a UL within a specific DIV
I have 3 Columns of ULs each a Dynamic UL container that can have anywhere from 0-9 LI containers (eventually more). All my LI elements have an attribute "rel" which I am trying to ultimately find that attribute and use it for something else on all LI elements within that parent DIV. I do eventually want to find more based on each but for not the very least the rel.. Any Ideas how I can achieve that with jQuery? Example:

```<code><ul id="column1">
   <li rel="1">Info</li>
   <li rel="2">Info</li>
   <li rel="3">Info</li>
</ul>
<ul id="column2">
   <li rel="4">Info</li>
   <li rel="5">Info</li>
   <li rel="6">Info</li>
</ul>
<ul id="column3">
   <li rel="7">Info</li>
   <li rel="8">Info</li>
   <li rel="9">Info</li>
</ul>
</code>```

these elements are all sortable as well. So when I get a list of them I want to also keep them in the order they were found from top to bottom of each column.

I have tried find(), parent(), and similar, maybe I am approaching it wrong. But its still worth mentioning to help come up with an idea

答:
```<code>$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();
</code>```

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

```<code>var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});
</code>```

Body:
I have 3 Columns of ULs each a Dynamic UL container that can have anywhere from 0-9 LI containers (eventually more). All my LI elements have an attribute "rel" which I am trying to ultimately find that attribute and use it for something else on all LI elements within that parent DIV. I do eventually want to find more based on each but for not the very least the rel.. Any Ideas how I can achieve that with jQuery? Example:

Info

Info

Info

Info

Info

Info

Info

Info

Info

these elements are all sortable as well. So when I get a list of them I want to also keep them in the order they were found from top to bottom of each column.

I have tried find(), parent(), and similar, maybe I am approaching it wrong. But its still worth mentioning to help come up with an idea

Body:
$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});


问:
Best way to pass the logged in user to the backend in Django
I'm new to Django and I've correctly created a login/register and my account page. Now my problem is that no matter which user is logged in when it goes to my account page, the URL will also be ./account

Is there a way to pass which user is requesting the page and change the URL according to it but always pointing to the same template?

For instance, if the user logged in has username john clicking on my account it redirects to ./account/john but shows the same template. Basically I would like that the URLs reflect the user logged in

Currently, I manage the My account page as below.

navbar.html

```<code>{% if user.is_authenticated %}
   <li class="">
      <a href="{% url 'account' %}">
         <i class='bx bxs-user-detail icon' ></i>
         <span class="text nav-text">My profile</span>
      </a>
   </li>
</code>```

urls.py

```<code>from django.urls import path, include
from . import views

urlpatterns = [
    path('account', views.account_user, name="account"),
]
</code>```

答:
Basically you need 2 views.  One view is account/ which looks at request.user and then returns a 302 to redirect the user to the appropriate page (ex. John is logged in and is redirected to /account/john/).  The other view being the account display which is account/<slug:username>/ and shows the account information for the passed in username.

However, you could also just make the link in navbar.html point directly to /account/john/ since the person is logged in and you have that information available.

Body:
I'm new to Django and I've correctly created a login/register and my account page. Now my problem is that no matter which user is logged in when it goes to my account page, the URL will also be ./account

Is there a way to pass which user is requesting the page and change the URL according to it but always pointing to the same template?

For instance, if the user logged in has username john clicking on my account it redirects to ./account/john but shows the same template. Basically I would like that the URLs reflect the user logged in

Currently, I manage the My account page as below.

navbar.html

{% if user.is_authenticated %}

         My profile

urls.py

from django.urls import path, include
from . import views

urlpatterns = [
    path('account', views.account_user, name="account"),
]