问:
How to debug injected javascript code in IE compatibility mode?
I need to inject some Javascript scripts to IE and then invoke some methods.

I tried the following simple C# code (the Javascript code is to build xpath from a known HTML element).

```<code>string xpath = @"
(function(win) {
    ""use strict"";
    var doc = win.document;

    if (doc._xpath_installed) return;
    doc._xpath_installed = true;

    doc.createXPath = function (node, optimized) {
        if (node.nodeType === Node.DOCUMENT_NODE) {
            return '/';
        }

        var steps = [];
        var contextNode = node;
        while (contextNode) {
            var step = _xPathValue(contextNode, optimized);
            if (!step) {
                break;
            }  // Error - bail out early.
            steps.push(step);
            if (step.optimized) {
                break;
            }
            contextNode = contextNode.parentNode;
        }

        steps.reverse();

        var stepvalues = [];
        steps.forEach(function (step) {
            stepvalues.push(_steptostring(step));
        });
        return (steps.length && steps[0].optimized ? '' : '/') + stepvalues.join('/');
    };

    var _xPathValue = function (node, optimized) {
        var ownValue;
        var ownIndex = _xPathIndex(node);
        if (ownIndex === -1) {
            return null;
        }  // Error.

        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                if (optimized && node.getAttribute('id')) {
                    return _stepnew('//*[@id=""' + node.getAttribute('id') + '""]', true);
                }
                ownValue = node.localName;
                break;
            case Node.ATTRIBUTE_NODE:
                ownValue = '@' + node.nodeName;
                break;
            case Node.TEXT_NODE:
            case Node.CDATA_SECTION_NODE:
                ownValue = 'text()';
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                ownValue = 'processing-instruction()';
                break;
            case Node.COMMENT_NODE:
                ownValue = 'comment()';
                break;
            case Node.DOCUMENT_NODE:
                ownValue = '';
                break;
            default:
                ownValue = '';
                break;
        }

        if (ownIndex > 0) {
            ownValue += '[' + ownIndex + ']';
        }

        return _stepnew(ownValue, node.nodeType === Node.DOCUMENT_NODE);
    };

    var _xPathIndex = function (node) {
        // Returns -1 in case of error, 0 if no siblings matching the same expression,
        // <XPath index among the same expression-matching sibling nodes> otherwise.
        function areNodesSimilar(left, right) {
            if (left === right) {
                return true;
            }

            if (left.nodeType === Node.ELEMENT_NODE && right.nodeType === Node.ELEMENT_NODE) {
                return left.localName === right.localName;
            }

            if (left.nodeType === right.nodeType) {
                return true;
            }

            // XPath treats CDATA as text nodes.
            var leftType = left.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : left.nodeType;
            var rightType = right.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : right.nodeType;
            return leftType === rightType;
        }

        var siblings = node.parentNode ? node.parentNode.children : null;
        if (!siblings) {
            return 0;
        }  // Root node - no siblings.
        var hasSameNamedElements;
        for (var i = 0; i < siblings.length; ++i) {
            if (areNodesSimilar(node, siblings[i]) && siblings[i] !== node) {
                hasSameNamedElements = true;
                break;
            }
        }
        if (!hasSameNamedElements) {
            return 0;
        }
        var ownIndex = 1;  // XPath indices start with 1.
        for (var i = 0; i < siblings.length; ++i) {
            if (areNodesSimilar(node, siblings[i])) {
                if (siblings[i] === node) {
                    return ownIndex;
                }
                ++ownIndex;
            }
        }
        return -1;
    };

    var _stepnew = function(value, optimized) {
        return {
            value: value,
            optimized: optimized || false
        }
    };

    var _steptostring = function(step) {
        return step[""value""];
    };
})(window);
";
</code>```

And then I try to inject the xpath string and invoke a method,

```<code>// doc is the html document (type: mshtml.IHTMLDocument2)
// element is the html element (type: mshtml.IHTMLElement)

doc.parentWindow.execScript(xpath, "JScript");

object[] args = new object[2];
args[0] = element;
args[1] = 1;
object result = doc.GetType().InvokeMember("createXPath", BindingFlags.Instance | BindingFlags.InvokeMethod, null, doc, args);
</code>```

It works fine in Internet Explorer 11 (Windows 10).

However, when I add the website to Compatibility View (settings-> compatibility view settings), the InvokeMember call throws exception "Exception from HRESULT: 0x80020101", which means there are some script errors in the Javascript code.

My question is, is there a way to debug into this Javascript code in the above situation? Without debugging it is almost impossible to find the root cause only based on the information 0x80020101.

答: If you have script errors in your JS code, why don't you trace the client-side code's execution with console.log() or console.debug() so that you know what is happening in your application ?

Body:
I need to inject some Javascript scripts to IE and then invoke some methods.

I tried the following simple C# code (the Javascript code is to build xpath from a known HTML element).

string xpath = @"
(function(win) {
    ""use strict"";
    var doc = win.document;

    if (doc._xpath_installed) return;
    doc._xpath_installed = true;

    doc.createXPath = function (node, optimized) {
        if (node.nodeType === Node.DOCUMENT_NODE) {
            return '/';
        }

        var steps = [];
        var contextNode = node;
        while (contextNode) {
            var step = _xPathValue(contextNode, optimized);
            if (!step) {
                break;
            }  // Error - bail out early.
            steps.push(step);
            if (step.optimized) {
                break;
            }
            contextNode = contextNode.parentNode;
        }

        steps.reverse();

        var stepvalues = [];
        steps.forEach(function (step) {
            stepvalues.push(_steptostring(step));
        });
        return (steps.length && steps[0].optimized ? '' : '/') + stepvalues.join('/');
    };

    var _xPathValue = function (node, optimized) {
        var ownValue;
        var ownIndex = _xPathIndex(node);
        if (ownIndex === -1) {
            return null;
        }  // Error.

        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                if (optimized && node.getAttribute('id')) {
                    return _stepnew('//*[@id=""' + node.getAttribute('id') + '""]', true);
                }
                ownValue = node.localName;
                break;
            case Node.ATTRIBUTE_NODE:
                ownValue = '@' + node.nodeName;
                break;
            case Node.TEXT_NODE:
            case Node.CDATA_SECTION_NODE:
                ownValue = 'text()';
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                ownValue = 'processing-instruction()';
                break;
            case Node.COMMENT_NODE:
                ownValue = 'comment()';
                break;
            case Node.DOCUMENT_NODE:
                ownValue = '';
                break;
            default:
                ownValue = '';
                break;
        }

        if (ownIndex > 0) {
            ownValue += '[' + ownIndex + ']';
        }

        return _stepnew(ownValue, node.nodeType === Node.DOCUMENT_NODE);
    };

    var _xPathIndex = function (node) {
        // Returns -1 in case of error, 0 if no siblings matching the same expression,
        // <XPath index among the same expression-matching sibling nodes> otherwise.
        function areNodesSimilar(left, right) {
            if (left === right) {
                return true;
            }

            if (left.nodeType === Node.ELEMENT_NODE && right.nodeType === Node.ELEMENT_NODE) {
                return left.localName === right.localName;
            }

            if (left.nodeType === right.nodeType) {
                return true;
            }

            // XPath treats CDATA as text nodes.
            var leftType = left.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : left.nodeType;
            var rightType = right.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : right.nodeType;
            return leftType === rightType;
        }

        var siblings = node.parentNode ? node.parentNode.children : null;
        if (!siblings) {
            return 0;
        }  // Root node - no siblings.
        var hasSameNamedElements;
        for (var i = 0; i < siblings.length; ++i) {
            if (areNodesSimilar(node, siblings[i]) && siblings[i] !== node) {
                hasSameNamedElements = true;
                break;
            }
        }
        if (!hasSameNamedElements) {
            return 0;
        }
        var ownIndex = 1;  // XPath indices start with 1.
        for (var i = 0; i < siblings.length; ++i) {
            if (areNodesSimilar(node, siblings[i])) {
                if (siblings[i] === node) {
                    return ownIndex;
                }
                ++ownIndex;
            }
        }
        return -1;
    };

    var _stepnew = function(value, optimized) {
        return {
            value: value,
            optimized: optimized || false
        }
    };

    var _steptostring = function(step) {
        return step[""value""];
    };
})(window);
";

And then I try to inject the xpath string and invoke a method,

// doc is the html document (type: mshtml.IHTMLDocument2)
// element is the html element (type: mshtml.IHTMLElement)

doc.parentWindow.execScript(xpath, "JScript");

object[] args = new object[2];
args[0] = element;
args[1] = 1;
object result = doc.GetType().InvokeMember("createXPath", BindingFlags.Instance | BindingFlags.InvokeMethod, null, doc, args);

It works fine in Internet Explorer 11 (Windows 10).

However, when I add the website to Compatibility View (settings-> compatibility view settings), the InvokeMember call throws exception "Exception from HRESULT: 0x80020101", which means there are some script errors in the Javascript code.

My question is, is there a way to debug into this Javascript code in the above situation? Without debugging it is almost impossible to find the root cause only based on the information 0x80020101.


来源: stackexchange

问:
How to get subarray from array?
I have var ar = [1, 2, 3, 4, 5] and want some function getSubarray(array, fromIndex, toIndex), that result of call getSubarray(ar, 1, 3) is new array [2, 3, 4].

答:
I have var ar = [1, 2, 3, 4, 5] and want some function
getSubarray(array, fromIndex, toIndex), that result of call
getSubarray(ar, 1, 3) is new array [2, 3, 4].

Exact Solution

```<code>function getSubarray(array, fromIndex, toIndex) {
    return array.slice(fromIndex, toIndex+1);
}
</code>```

Let's Test the Solution

```<code>let ar = [1, 2, 3, 4, 5]
getSubarray(ar, 1, 3)

// result: [2,3,4]
</code>```

Array.prototype.slice()

The slice() method returns a shallow copy of a portion of an array
into a new array object selected from start to end (end not included)
where start and end represent the index of items in that array. The
original array will not be modified.

Basically, slice lets you select a subarray from an array.

For example, let's take this array:

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

Doing this:

console.log(animals.slice(2, 4));

Will give us this output:

// result: ["camel", "duck"]

Syntax:

```<code>slice() // creates a shallow copy of the array
slice(start) // shows only starting point and returns all values after start index
slice(start, end) // slices from start index to end index
</code>```

See shallow copy reference

ContentLicense: CC BY-SA 3.0

Title: How to get subarray from array?

Body:
I have var ar = [1, 2, 3, 4, 5] and want some function
getSubarray(array, fromIndex, toIndex), that result of call
getSubarray(ar, 1, 3) is new array [2, 3, 4].

Exact Solution

function getSubarray(array, fromIndex, toIndex) {
    return array.slice(fromIndex, toIndex+1);
}

Let's Test the Solution

let ar = [1, 2, 3, 4, 5]
getSubarray(ar, 1, 3)

// result: [2,3,4]

Array.prototype.slice()

The slice() method returns a shallow copy of a portion of an array
into a new array object selected from start to end (end not included)
where start and end represent the index of items in that array. The
original array will not be modified.

Basically, slice lets you select a subarray from an array.

For example, let's take this array:

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

Doing this:

console.log(animals.slice(2, 4));

Will give us this output:

// result: ["camel", "duck"]

Syntax:

slice() // creates a shallow copy of the array
slice(start) // shows only starting point and returns all values after start index
slice(start, end) // slices from start index to end index

See shallow copy reference

ContentLicense: CC BY-SA 4.0


问:
Uncaught ReferenceError: process is not defined (create-react-app 5.0.0)
I've migrated my react app to react-scripts 5.0.0 and now I get this error:

```<code>path.js:25 Uncaught ReferenceError: process is not defined
    at Object../node_modules/path/path.js (path.js:25:1)
    at Object.options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:61:1)
    at Object../node_modules/mime-types/index.js (index.js:16:1)
    at Object.options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:61:1)
    at Object../node_modules/react-s3-uploader/s3upload.js (s3upload.js:6:1)
    at Object.options.factory (react refresh:6:1)
</code>```

That's the line from path.js:

```<code>var isWindows = process.platform === 'win32';
</code>```

There's an issue on github https://github.com/facebook/create-react-app/issues/11773 that says such error caused by incorrect version of react-error-overlay but it seems that's no the case for me. I've tried every solution from this issue but the error is still there

```<code>$ npm why react-error-overlay                                                                                [20:54:29]
react-error-overlay@6.0.9
node_modules/react-error-overlay
  dev react-error-overlay@"6.0.9" from the root project
</code>```

答: downgrading react-scripts to 4.0.3 resolved my issue</p>

Body:
I've migrated my react app to react-scripts 5.0.0 and now I get this error:

path.js:25 Uncaught ReferenceError: process is not defined
    at Object../node_modules/path/path.js (path.js:25:1)
    at Object.options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:61:1)
    at Object../node_modules/mime-types/index.js (index.js:16:1)
    at Object.options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:24:1)
    at fn (hot module replacement:61:1)
    at Object../node_modules/react-s3-uploader/s3upload.js (s3upload.js:6:1)
    at Object.options.factory (react refresh:6:1)

That's the line from path.js:

var isWindows = process.platform === 'win32';

There's an issue on github https://github.com/facebook/create-react-app/issues/11773 that says such error caused by incorrect version of react-error-overlay but it seems that's no the case for me. I've tried every solution from this issue but the error is still there

$ npm why react-error-overlay                                                                                [20:54:29]
react-error-overlay@6.0.9
node_modules/react-error-overlay
  dev react-error-overlay@"6.0.9" from the root project


问:
Seq.Map string->string
all!

What is wrong with this code? I cannot understand what I am doing wrong with Seq.Map.
Here is the error message: The type 'unit' is not compatible with the type 'seq<'a>'

```<code>let getPathToLibFile value =
    let regex = new Regex("\"(?<data>[^<]*)\"")
    let matches = regex.Match(value)
    matches.Value

let importAllLibs (lines:string[]) =
    lines
    |> Seq.filter isImportLine
    |> Seq.iter (printfn "Libs found: %s")
    |> Seq.map getPathToLibFile // error in this line
    |> Seq.iter (printfn "Path to libs: %s")
</code>```

Is there any understandable examples on Seq.Map?

PS Example from wiki (it works):

```<code>(* Fibonacci Number formula *)
let rec fib n =
    match n with
    | 0 | 1 -> n
    | _ -> fib (n - 1) + fib (n - 2)

(* Print even fibs *)
[1 .. 10]
|> List.map     fib
|> List.filter  (fun n -> (n % 2) = 0)
|> printlist
</code>```

答:
WebSharper includes an operator you can define yourself like this:

```<code>let (|!>) a f = f a; a
</code>```

Allowing you to call a function of type 'a -> unit on the input value returning the same value.

Fixing your code would require but a slight modification:

```<code>lines
|> Seq.filter isImportLine
|!> Seq.iter (printfn "Libs found: %s")
|> Seq.map getPathToLibFile // error in this line
|> Seq.iter (printfn "Path to libs: %s")
</code>```

On the other hand you would end up iterating the collection twice which might not be what you want.

A better approach would be to define a function Do (lowercase do being a reserved keyword in F#) which introduces a side effect on iterating the sequence. Rx.NET (Ix) provides such a function in EnumerableEx:

```<code>let Do f xs = Seq.map (fun v -> f v; v) xs
</code>```

and then you can introduce the side effect like so:

```<code>lines
|> Seq.filter isImportLine
|> Do (printfn "Libs found: %s")
|> Seq.map getPathToLibFile // error in this line
|> Seq.iter (printfn "Path to libs: %s")
</code>```

The side effect will be introduced only upon iterating the collection on the last line.

Title: Seq.Map string->string

Body:
all!

What is wrong with this code? I cannot understand what I am doing wrong with Seq.Map.
Here is the error message: The type 'unit' is not compatible with the type 'seq<'a>'

let getPathToLibFile value =
    let regex = new Regex("\"(?<data>[^<]*)\"")
    let matches = regex.Match(value)
    matches.Value

let importAllLibs (lines:string[]) =
    lines
    |> Seq.filter isImportLine
    |> Seq.iter (printfn "Libs found: %s")
    |> Seq.map getPathToLibFile // error in this line
    |> Seq.iter (printfn "Path to libs: %s")

Is there any understandable examples on Seq.Map?

PS Example from wiki (it works):

(* Fibonacci Number formula *)
let rec fib n =
    match n with
    | 0 | 1 -> n
    | _ -> fib (n - 1) + fib (n - 2)

(* Print even fibs *)
[1 .. 10]
|> List.map     fib
|> List.filter  (fun n -> (n % 2) = 0)
|> printlist

Body:
WebSharper includes an operator you can define yourself like this:

let (|!>) a f = f a; a

Allowing you to call a function of type 'a -> unit on the input value returning the same value.

Fixing your code would require but a slight modification:

lines
|> Seq.filter isImportLine
|!> Seq.iter (printfn "Libs found: %s")
|> Seq.map getPathToLibFile // error in this line
|> Seq.iter (printfn "Path to libs: %s")

On the other hand you would end up iterating the collection twice which might not be what you want.

A better approach would be to define a function Do (lowercase do being a reserved keyword in F#) which introduces a side effect on iterating the sequence. Rx.NET (Ix) provides such a function in EnumerableEx:

let Do f xs = Seq.map (fun v -> f v; v) xs

and then you can introduce the side effect like so:

lines
|> Seq.filter isImportLine
|> Do (printfn "Libs found: %s")
|> Seq.map getPathToLibFile // error in this line
|> Seq.iter (printfn "Path to libs: %s")

The side effect will be introduced only upon iterating the collection on the last line.


问:
How to access specific information in json?
I made an authentication method in a WEB API and I'm getting the answer below:

```<code>I/Response
{
"login": "teste@teste.com",
"senha": "12345dxkjs",
"token":"kjqwdjqwdjlqkwjqkwdjqwdjwdqkwjlqjwkdqwjl", ....
}
</code>```

I use the code below to read the information:

```<code>String data = response.body().string();
Log.e("response", data);
</code>```

How can I access only the token that is in the array?
How do I do this using java/android?

答:
Use some JSON library, e.g. org.json to parse the string first.
In your case the code to get the token would like something like this:</p>
```<code>import org.json.*;

try
{
    String data = response.body().string();
    JSONObject jsonData = new JSONObject(data);

    String token = jsonData.getString("token");
    Log.e("response", token);
}
catch (JSONException e)
{
     Log.e("JSON Exception", e);
}
</code>```

Body:
I made an authentication method in a WEB API and I'm getting the answer below:

I/Response
{
"login": "teste@teste.com",
"senha": "12345dxkjs",
"token":"kjqwdjqwdjlqkwjqkwdjqwdjwdqkwjlqjwkdqwjl", ....
}

I use the code below to read the information:

String data = response.body().string();
Log.e("response", data);

How can I access only the token that is in the array?
How do I do this using java/android?

Body:
Use some JSON library, e.g. org.json to parse the string first.
In your case the code to get the token would like something like this:

import org.json.*;

try
{
    String data = response.body().string();
    JSONObject jsonData = new JSONObject(data);

    String token = jsonData.getString("token");
    Log.e("response", token);
}
catch (JSONException e)
{
     Log.e("JSON Exception", e);
}


问:
Uxexpected indent error while executing multiple if or elif using while loop and multiple break
I am writing a code that just takes 5 positive values and if the user enters a null or no value it should give an error please do enter a number I keep getting this indention error what are the rules for indentation in python also its not able to evaluate the null or none value and give the error message "please do enter a number", and if I am using elif statement its also the loop should after taking 5 values which is not happening I am new at programming and need your help

```<code>i=1
while i<5:
 n=int(input("Enter a number  "))
 if n<=0:
     i+=1
     break
print(n)
print("Loop ended , Negative Value Entered")
  if n==None:
     i=1
break
print(n)
print("Loop ended , please do enter a number ")
</code>```

Here is another code with the elif

```<code>i=1
while i<5:
     n=int(input("Enter a number  "))
     if n<=0:
         break
         print(n)
         print("Loop ended , Negative Value Entered")
         i=1
     elif n==None:
             break
             i=1
             print(n)
             print("Loop ended , please do enter a number ")
     else:
             i+=1
</code>```

答:
The structure of your code is wrong. You cannot have blocks of different indentations without having a statement such as while, for etc occuring just before it.

This is how you can correct the program, both syntactically and semantically.

i=1
while i<5:
    n=int(input("Enter a number  "))
    if n<=0:
        print("Loop ended , Negative Value Entered")
        break
    if n==None:
        i=1
        print("Loop ended , please do enter a number ")
        break
print(n)
```

Do note: n here can never be None since python converts it into an integer. If you are trying to catch an "empty input" kind of situation you do not need to worry as python will raise an error and terminate the program if the input is left empty, and hence you wouldn't even need to check for that. Because the line int(input()) will not accept an empty input string.

Also, in your second snippet, the lines after break will not run since break terminates the loop immediately, ignoring any statements after it. So you need to give the break statements at the end of whatever lines you are executing over there.

Body:
I am writing a code that just takes 5 positive values and if the user enters a null or no value it should give an error please do enter a number I keep getting this indention error what are the rules for indentation in python also its not able to evaluate the null or none value and give the error message "please do enter a number", and if I am using elif statement its also the loop should after taking 5 values which is not happening I am new at programming and need your help

i=1
while i<5:
 n=int(input("Enter a number  "))
 if n<=0:
     i+=1
     break
print(n)
print("Loop ended , Negative Value Entered")
  if n==None:
     i=1
break
print(n)
print("Loop ended , please do enter a number ")

Here is another code with the elif

i=1
while i<5:
     n=int(input("Enter a number  "))
     if n<=0:
         break
         print(n)
         print("Loop ended , Negative Value Entered")
         i=1
     elif n==None:
             break
             i=1
             print(n)
             print("Loop ended , please do enter a number ")
     else:
             i+=1

Body:
The structure of your code is wrong. You cannot have blocks of different indentations without having a statement such as while, for etc occuring just before it.

This is how you can correct the program, both syntactically and semantically.

i=1
while i<5:
    n=int(input("Enter a number  "))
    if n<=0:
        print("Loop ended , Negative Value Entered")
        break
    if n==None:
        i=1
        print("Loop ended , please do enter a number ")
        break
print(n)

Do note: n here can never be None since python converts it into an integer. If you are trying to catch an "empty input" kind of situation you do not need to worry as python will raise an error and terminate the program if the input is left empty, and hence you wouldn't even need to check for that. Because the line int(input()) will not accept an empty input string.

Also, in your second snippet, the lines after break will not run since break terminates the loop immediately, ignoring any statements after it. So you need to give the break statements at the end of whatever lines you are executing over there.


问:
Some styles are off in React app after deployment
I created a React app with create-react-app, and it works as expected in development.

However, after deploying the app, some styles don't apply.

I use Material UI, and most of the styling preserves, only a couple patterns that I noticed are off.

Example 1:

Here, the LOGIN button must be an orange outlined button, and the SIGN UP button must be a contained orange button with some margin in between. Here is how it looks in development:

Example 2 - Some margins are not applied:

Here, in between the menu items there must be some margins.

Example 3:

And Here you can see in the dev tools, that my styles are scrapped (for some reason the width: 70% is preserved though) and therefore not applied. Default MUI styling got applied instead.

Tried this on Chrome, Edge, and Safari browsers. All the same.

Tried googling, did not find a helpful answer or an article about the topic.

If you need additional info, please ask, as I don't know what else might be useful to debug.

Any help is appreciated

答: Try adding !important flag to styles that are not overriding.


问:
how to recover mysql password in ubuntu 16.04
Mysql version - mysql  Ver 14.14 Distrib 5.7.18, for Linux (x86_64) using  EditLine wrapper.

I had forgotten my password and tried many commands online.Also the problem is that grant tables command not working in my terminal.

答:
I had tried all the approaches but didn't work for me. The following approach worked. I am hopeful that it will work on different versions of ubuntu.

OS info:

```<code>mysql --version
mysql  Ver 8.0.28-0ubuntu0.20.04.3 for Linux on x86_64 ((Ubuntu))
</code>```

First, stop MySQL service using command

```<code>sudo systemctl stop mysql
</code>```

Other commands didn't work and here how I start the MySQL server without any permission-checking. To do so, run:

```<code>// open the mysql systemd configuration file your default text editor.
// In my case, it is nano editor.
sudo systemctl edit mysql

// Add the following 3 lines
[Service]
ExecStart=
ExecStart=/usr/sbin/mysqld --skip-grant-tables --skip-networking
</code>```

Reload systemd configuration using command:

```<code>sudo systemctl daemon-reload
</code>```

Start MySQL service

```<code>sudo systemctl start mysql
</code>```

Now, connect to MySQL server as root user without password:

```<code>sudo mysql -u root
mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'add-newpassword-here';
</code>```

Revert the modified systemd configuration

```<code>sudo systemctl revert mysql
</code>```

You are all Done.

Body:
I had tried all the approaches but didn't work for me. The following approach worked. I am hopeful that it will work on different versions of ubuntu.

OS info:

mysql --version
mysql  Ver 8.0.28-0ubuntu0.20.04.3 for Linux on x86_64 ((Ubuntu))

First, stop MySQL service using command

sudo systemctl stop mysql

Other commands didn't work and here how I start the MySQL server without any permission-checking. To do so, run:

// open the mysql systemd configuration file your default text editor.
// In my case, it is nano editor.
sudo systemctl edit mysql

// Add the following 3 lines
[Service]
ExecStart=
ExecStart=/usr/sbin/mysqld --skip-grant-tables --skip-networking

Reload systemd configuration using command:

sudo systemctl daemon-reload

Start MySQL service

sudo systemctl start mysql

Now, connect to MySQL server as root user without password:

sudo mysql -u root
mysql> FLUSH PRIVILEGES;
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH caching_sha2_password BY 'add-newpassword-here';

Revert the modified systemd configuration

sudo systemctl revert mysql

You are all Done.


问:
Why do I have undefined in selectedUser?
Why do I have undefined in selectedUser?
After all, I go through the find method through the users array and the first id of the users array should be written to selectedUser</p>
```<code>function App() {
const [selectedUserId, setSelectedUserId] = useState(null)
const [users,setUsers] = useState([])
const selectedUser = users.find(u => u.id === selectedUserId)
console.log(users)
console.log(selectedUser)

useAsyncEffect(async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const data = await res.json()
  setUsers(data)
}, [])

const onUserClick = (userId) => {
  setSelectedUserId(userId)
}

return (
  <div>
  { selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user=
 {selectedUser}  />
  }
  </div>
)
}
</code>```

答:
You can use a loading state to determine when the async function is done and only then you can set the selected user. Otherwise, it remains set to 'null' when the 'return' is rendered.

Below is pseudo code.

```<code> function App() {
    const [selectedUserId, setSelectedUserId] = useState(null)
    const [users,setUsers] = useState([])
    const selectedUser = users.find(u => u.id === selectedUserId)
    const [loading, setLoading] = useState(false)

    console.log(users)
    console.log(selectedUser)

    useAsyncEffect(async () => {
      setLoading(true)
      const res = await fetch('https://jsonplaceholder.typicode.com/users')
      const data = await res.json()
      setUsers(data)
      setLoading(false)
    }, [])

    const onUserClick = (userId) => {
      setSelectedUserId(userId)
    }
   if (loading){
      return "Loading..."
      // you can use a nicer loader component here
   }

    return (
      <div>
      { selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user=
     {selectedUser}  />
      }
      </div>
    )
    }
</code>```

Body:
Why do I have undefined in selectedUser?
After all, I go through the find method through the users array and the first id of the users array should be written to selectedUser

function App() {
const [selectedUserId, setSelectedUserId] = useState(null)
const [users,setUsers] = useState([])
const selectedUser = users.find(u => u.id === selectedUserId)
console.log(users)
console.log(selectedUser)

useAsyncEffect(async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users')
  const data = await res.json()
  setUsers(data)
}, [])

const onUserClick = (userId) => {
  setSelectedUserId(userId)
}

return (

  { selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user=
 {selectedUser}  />
  }

)
}

Body:
You can use a loading state to determine when the async function is done and only then you can set the selected user. Otherwise, it remains set to 'null' when the 'return' is rendered.

Below is pseudo code.

 function App() {
    const [selectedUserId, setSelectedUserId] = useState(null)
    const [users,setUsers] = useState([])
    const selectedUser = users.find(u => u.id === selectedUserId)
    const [loading, setLoading] = useState(false)

    console.log(users)
    console.log(selectedUser)

    useAsyncEffect(async () => {
      setLoading(true)
      const res = await fetch('https://jsonplaceholder.typicode.com/users')
      const data = await res.json()
      setUsers(data)
      setLoading(false)
    }, [])

    const onUserClick = (userId) => {
      setSelectedUserId(userId)
    }
   if (loading){
      return "Loading..."
      // you can use a nicer loader component here
   }

    return (
      <div>
      { selectedUser ? <ListUsers users={users} onUserClick={onUserClick} /> : <Profile user=
     {selectedUser}  />
      }
      </div>
    )
    }


问:
Shortcut to turn a ONE element dict into ONE tuple in Python
There are dozens of questions on turning a Python dict with some number of elements into a list of tuples. I am looking for a shortcut to turn a one element dict into a tuple.

Ideally, it would:

Be idiomatic and simple (ie, not a subclass of dict, not a function, etc).

Throw an error if there are more that one element in the dict.

Support multiple assignment by tuple unpacking.

Not destroy the dict.

I am looking for a shortcut to do this (that is not destructive to the dict):

```<code>k,v=unpack_this({'unknown_key':'some value'})
</code>```

* does not work here.

I have come up with these that work:

```<code>k,v=next(iter(di.items()))   # have to call 'iter' since 'dict_items' is not
</code>```

Or:

```<code>k,v=(next(((k,v) for k,v in di.items())))
</code>```

Or even:

```<code>k,v=next(zip(di.keys(), di.values()))
</code>```

Finally, the best I can come up with:

```<code>k,v=list(di.items())[0]      # probably the best...
</code>```

Which can be wrapped into a function if I want a length check:

```<code>def f(di):
    if (len(di)==1): return list(di.items())[0]
    raise ValueError(f'Too many items to unpack. Expected 2, got {len(di)*2}')
</code>```

These methods seem super clumsy and none throw an error if there is more than one element.

Is there an idiomatic shortcut that I am missing?

答:
Why not :</p>
```<code>next(iter(d.items())) if len(d)==1 else (None,None)
</code>```

Body:
There are dozens of questions on turning a Python dict with some number of elements into a list of tuples. I am looking for a shortcut to turn a one element dict into a tuple.

Ideally, it would:

Be idiomatic and simple (ie, not a subclass of dict, not a function, etc).

Throw an error if there are more that one element in the dict.

Support multiple assignment by tuple unpacking.

Not destroy the dict.

I am looking for a shortcut to do this (that is not destructive to the dict):

k,v=unpack_this({'unknown_key':'some value'})

* does not work here.

I have come up with these that work:

k,v=next(iter(di.items()))   # have to call 'iter' since 'dict_items' is not

Or:

k,v=(next(((k,v) for k,v in di.items())))

Or even:

k,v=next(zip(di.keys(), di.values()))

Finally, the best I can come up with:

k,v=list(di.items())[0]      # probably the best...

Which can be wrapped into a function if I want a length check:

def f(di):
    if (len(di)==1): return list(di.items())[0]
    raise ValueError(f'Too many items to unpack. Expected 2, got {len(di)*2}')

These methods seem super clumsy and none throw an error if there is more than one element.

Is there an idiomatic shortcut that I am missing?

Body:
Why not :

next(iter(d.items())) if len(d)==1 else (None,None)


问:
Ball not bouncing back in Kivy python
This is the .py file:

```<code>from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import Clock
from kivy.graphics import Ellipse

class Bounce(Widget):

    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.ball_size=100
        with self.canvas:
            self.ball=Ellipse(size=(self.ball_size,self.ball_size),pos=(self.center_x,self.center_y))
        Clock.schedule_interval(self.update,1/50)

    def update(self,dt):
        self.vx=1
        self.vy=3
        x,y=self.ball.pos
        x+=self.vx
        y+=self.vy
        if self.height<self.ball_size+y:
            self.y=-self.y
            y=self.height-self.ball_size
        self.ball.pos=(x,y)

    def on_size(self,*args):
        x=self.center_x-self.ball_size
        y=self.center_y-self.ball_size
        self.ball.pos=(x,y)

class GameApp(App):
    def build(self):
        return Bounce()

GameApp().run()
</code>```

This code should return a ball going from the centre to the top and then bouncing back one time but it's not bouncing back.

答:
You just need your code to change the self.vy to -3 to start moving the ball down instead of up. However, your update() method resets self.vy every time it is called. So, the fix is to remove the resetting of self.vx and self.vy from the update() method, and to set self.vy to -3 when you want the direction to change. Here is a modified version of your Bounce widget that does that:

```<code>class Bounce(Widget):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # initialize ball velocity
        self.vx = 1
        self.vy = 3

        self.ball_size = 100
        with self.canvas:
            self.ball = Ellipse(size=(self.ball_size, self.ball_size), pos=(self.center_x, self.center_y))
        Clock.schedule_interval(self.update, 1 / 50)

    def update(self, dt):
        x, y = self.ball.pos
        x += self.vx
        y += self.vy
        if self.height < self.ball_size + y:
            self.vy = -self.vy  # change direction of ball
            y = self.height - self.ball_size
        self.ball.pos = (x, y)
</code>```

Title: Ball not bouncing back in Kivy python

Body:
This is the .py file:

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import Clock
from kivy.graphics import Ellipse

class Bounce(Widget):

    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.ball_size=100
        with self.canvas:
            self.ball=Ellipse(size=(self.ball_size,self.ball_size),pos=(self.center_x,self.center_y))
        Clock.schedule_interval(self.update,1/50)

    def update(self,dt):
        self.vx=1
        self.vy=3
        x,y=self.ball.pos
        x+=self.vx
        y+=self.vy
        if self.height<self.ball_size+y:
            self.y=-self.y
            y=self.height-self.ball_size
        self.ball.pos=(x,y)

    def on_size(self,*args):
        x=self.center_x-self.ball_size
        y=self.center_y-self.ball_size
        self.ball.pos=(x,y)

class GameApp(App):
    def build(self):
        return Bounce()

GameApp().run()

This code should return a ball going from the centre to the top and then bouncing back one time but it's not bouncing back.

Body:
You just need your code to change the self.vy to -3 to start moving the ball down instead of up. However, your update() method resets self.vy every time it is called. So, the fix is to remove the resetting of self.vx and self.vy from the update() method, and to set self.vy to -3 when you want the direction to change. Here is a modified version of your Bounce widget that does that:

class Bounce(Widget):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # initialize ball velocity
        self.vx = 1
        self.vy = 3

        self.ball_size = 100
        with self.canvas:
            self.ball = Ellipse(size=(self.ball_size, self.ball_size), pos=(self.center_x, self.center_y))
        Clock.schedule_interval(self.update, 1 / 50)

    def update(self, dt):
        x, y = self.ball.pos
        x += self.vx
        y += self.vy
        if self.height < self.ball_size + y:
            self.vy = -self.vy  # change direction of ball
            y = self.height - self.ball_size
        self.ball.pos = (x, y)


问:
Prevent duplicate messages
Tech stack - Python, Rabbitmq, Elasticsearch, Heroku

I have one application which adds content in the app based on a certain schedule and when the content is added, an email needs to be triggered to some users based on some criteria ( can be around 1million users)

The design I have decided is that first application(producer) will publish the content and then put a message in Rabbitmq(message broker) containing user id and email address for each user who is supposed to get the email, so basically adding around 1mn messages to  Rabbitmq and then the email will be sent by email application(consumer)

My question is around the producer application.It is going to get a list of user ids from elasticsearch and start adding them to the queue using a for loop, but if for some reason this application goes down(like in case of new deployment), then only few users will be added to the queue and when the application comes back it will again start queueing and we might end up with duplicate emails to the same users.
Is there a standard way to avoid this.Seems like a very common issue.

I am thinking of maintaining the message acknowledgement(for each user for given content)from consumer app within my producer app database.But it feels like that it might lead to records explosion in my PostgreSQL database after a few email sends.Each content can be followed by email trigger to around 1million user.

答:
You definitely want to achieve full-consistency and you might need to extend your stack with Database(Persistent-Storage) supporting a fetch/select with Synchronization.

As a developer of "SWC-DB", I welcome you try out the latest SWC-DB release resolves the issues #1 and #2 that make the consistency possible. There is an example of priority-queue queue-example.cc (other languages can be implemented with the specific thrift-client)
You might want to note the .set_opt__deleting() in the "queue-example.cc"'s scan-specs:

  SWC::DB::Specs::Interval intval;
  intval.set_opt__deleting();
```

Although, I can see other problem of "duplicate emails" which can happen as well when an email has already been sent and a new task arrive for the same. As @levi-ramsey mentioned to track the processed-state by the consumer.
In such case, the SELECT can be and should be with an UPDATE=(ns+3d,"SET_A_VALUE_AS_PROCESSED") specifications, and in such case (of to many records remain in the DB) the Schema of the Column can be set with a TTL(lets say 3-days, so yet processed won't be deleted as well).
Whereas, the Interval Scan Specs to require the spec for value with other-than (-ne) "SET_A_VALUE_AS_PROCESSED" for the records of select-match. There is the SWC-DB
Condition-Value-Expression syntax explains the use with SQL.

Title: Prevent duplicate messages

Body:
You definitely want to achieve full-consistency and you might need to extend your stack with Database(Persistent-Storage) supporting a fetch/select with Synchronization.

As a developer of "SWC-DB", I welcome you try out the latest SWC-DB release resolves the issues #1 and #2 that make the consistency possible. There is an example of priority-queue queue-example.cc (other languages can be implemented with the specific thrift-client)
You might want to note the .set_opt__deleting() in the "queue-example.cc"'s scan-specs:

  SWC::DB::Specs::Interval intval;
  intval.set_opt__deleting();

Although, I can see other problem of "duplicate emails" which can happen as well when an email has already been sent and a new task arrive for the same. As @levi-ramsey mentioned to track the processed-state by the consumer.
In such case, the SELECT can be and should be with an UPDATE=(ns+3d,"SET_A_VALUE_AS_PROCESSED") specifications, and in such case (of to many records remain in the DB) the Schema of the Column can be set with a TTL(lets say 3-days, so yet processed won't be deleted as well).
Whereas, the Interval Scan Specs to require the spec for value with other-than (-ne) "SET_A_VALUE_AS_PROCESSED" for the records of select-match. There is the SWC-DB
Condition-Value-Expression syntax explains the use with SQL.


问:
How to poll asyncBatchAnnotateFilesAsync (Vision API) using getMetadata() - Java
I am parsing a large PDF using Google Vision API asyncBatchAnnotateFilesAsync using Java
Now I want to poll the request every 1 second to check the current status of the Async annotation request using getMetadata() method for the long-running operation Async call.

If I print(response.GetMetadat()), I get this output :
[status=PENDING, info=[inputFuture=[com.google.api.core.AbstractApiFuture$InternalSettableFuture@ac76b42[status=PENDING]], function=[com.google.api.core.ApiFutures$ApiFunctionToGuavaFunction@268aa98c]]]

But I want to only capture status (status=PENDING) part of getMetadata(). I am not sure what variable datatype should I declare in Java to capture output of getMetadata() so I could parse it to get just "Status"

答:
OperationFuture.getMetadata() offers the isDone() method to check for the completion of the batch job. The method returns  (Boolean) true if the job is completed, false if the job is running. The job completion may be due to normal termination, an exception, or cancellation. Refer to the below code sample.

while(!response.getMetadata().isDone()){
    System.out.println("In Progress...");
    TimeUnit.SECONDS.sleep(1); // One second delay
}
```
<p>However, if you want to parse the returned protobuf message, the <code>toString()</code> method can be used. The output of <code>response.getMetadata().toString()</code> is a string that can be checked for the presence of <code>PENDING</code> as a substring.</p>
<pre class="lang-java prettyprint-override"><code>while(response.getMetadata().toString().contains("PENDING")) // Checking if the job is in the pending state.
{
    System.out.println("In Progress...");
    TimeUnit.SECONDS.sleep(1); // One second delay
}

if(response.getMetadata().toString().contains("SUCCESS"))
{
    System.out.println("\nProcess Done!");
}

if(response.getMetadata().toString().contains("FAILURE"))
{
    System.out.println("\nProcess Failed!");
}
</code>```

Body:
OperationFuture.getMetadata() offers the isDone() method to check for the completion of the batch job. The method returns  (Boolean) true if the job is completed, false if the job is running. The job completion may be due to normal termination, an exception, or cancellation. Refer to the below code sample.

while(!response.getMetadata().isDone()){
    System.out.println("In Progress...");
    TimeUnit.SECONDS.sleep(1); // One second delay
}

However, if you want to parse the returned protobuf message, the toString() method can be used. The output of response.getMetadata().toString() is a string that can be checked for the presence of PENDING as a substring.

while(response.getMetadata().toString().contains("PENDING")) // Checking if the job is in the pending state.
{
    System.out.println("In Progress...");
    TimeUnit.SECONDS.sleep(1); // One second delay
}

if(response.getMetadata().toString().contains("SUCCESS"))
{
    System.out.println("\nProcess Done!");
}

if(response.getMetadata().toString().contains("FAILURE"))
{
    System.out.println("\nProcess Failed!");
}


问:
(Unity) Rotate parent object by script like in editor
I have gameobjects inside a parent game object. When I rotate the parent in axis Y with the editor using the tool "E", it rotates correctly, and I can see how it change also X and Z position to rotate centered.

When I do it by script, it only change the rotation Y value and it creates some strange efect with the static camera pointing at it.

I have tried:

```<code>GameObject parentobject;
Transform transf;
Vector3 pivot;
</code>```

Option 1:

```<code>Update()
{
    parentobject.transform.Rotate(0,Time.deltaTime*50f,0);
}
</code>```

Option 2:

```<code>Update()
{
    Vector3 axisrotate= new Vector3(0, 1, 0);
    parentobject.transform.Rotate(axisrotate,1);
}
</code>```

Option 3:

```<code>Start()
{
    bound.center = parentobject.transform.position;
    transf = parentobject.transform.root.GetComponentInChildren<Transform>();
    bound.Encapsulate(transf.position);
    pivot = bound.center;
}
Update()
{
    transform.root.RotateAround(pivot, Vector3.up, Time.deltaTime * 50)
}
</code>```

But the result is always the same.

Thanks.

答: I have solve it with "transform.RotateAround" But the axis where do you want to rotate at, it can not be the same object. So I have create an empty object in the center of the object I wanted to rotate and use it as a reference.</p>

Body:
I have gameobjects inside a parent game object. When I rotate the parent in axis Y with the editor using the tool "E", it rotates correctly, and I can see how it change also X and Z position to rotate centered.

When I do it by script, it only change the rotation Y value and it creates some strange efect with the static camera pointing at it.

I have tried:

GameObject parentobject;
Transform transf;
Vector3 pivot;

Option 1:

Update()
{
    parentobject.transform.Rotate(0,Time.deltaTime*50f,0);
}

Option 2:

Update()
{
    Vector3 axisrotate= new Vector3(0, 1, 0);
    parentobject.transform.Rotate(axisrotate,1);
}

Option 3:

Start()
{
    bound.center = parentobject.transform.position;
    transf = parentobject.transform.root.GetComponentInChildren<Transform>();
    bound.Encapsulate(transf.position);
    pivot = bound.center;
}
Update()
{
    transform.root.RotateAround(pivot, Vector3.up, Time.deltaTime * 50)
}

But the result is always the same.

Thanks.


问:
I set android:exported but I am still getting error: android:exported needs to be explicitly specified for <receiver>
I am moving from SDK version 30 to 31 and I add android:exported in intent-filter but still I am getting this error:

Merging Errors: Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.mycompany.webviewapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>

        <activity android:name="com.mycompany.webviewapp.SplashActivity"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.mycompany.webviewapp.MainActivity"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER"/>
                <action android:name="android.intent.action.VIEW"></action>
            </intent-filter>

        </activity>

        <service android:name="com.mycompany.webviewapp.FCM.MyFirebaseMessagingService">

        </service>

        <meta-data android:name="applovin.sdk.key"
            android:value="sdk api here"/>

    </application>

</manifest>
</code>```

答:
The reason is because some of the dependency libraries that you're using have elements which do not have "android:exported" attribute.

You need to do this:

Lower the version in your gradle to 30 and sync and build.

Go to your AndroidManifest.xml file and click on "Merged Manifest".

Find items such as Activity, Receiver, Service, etc that don't have "android:exported" attribute.

Then add them to your AndroidManifest.xml file in this way.

```<code><activity
    android:name="SomeActivity"
    android:exported="false"
    tools:node="merge"
    tools:replace="android:exported" />
</code>```

Now you can increase your version to 31.

Body:
I am moving from SDK version 30 to 31 and I add android:exported in intent-filter but still I am getting this error:

Merging Errors: Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.mycompany.webviewapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:name=".App"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-3940256099942544~3347511713"/>

        <activity android:name="com.mycompany.webviewapp.SplashActivity"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.mycompany.webviewapp.MainActivity"
            android:exported="true"
            android:screenOrientation="portrait">
            <intent-filter>
                <category android:name="android.intent.category.LAUNCHER"/>
                <action android:name="android.intent.action.VIEW"></action>
            </intent-filter>

        </activity>

        <service android:name="com.mycompany.webviewapp.FCM.MyFirebaseMessagingService">

        </service>

        <meta-data android:name="applovin.sdk.key"
            android:value="sdk api here"/>

    </application>

</manifest>

Body:
The reason is because some of the dependency libraries that you're using have elements which do not have "android:exported" attribute.

You need to do this:

Lower the version in your gradle to 30 and sync and build.

Go to your AndroidManifest.xml file and click on "Merged Manifest".

Find items such as Activity, Receiver, Service, etc that don't have "android:exported" attribute.

Then add them to your AndroidManifest.xml file in this way.

<activity
    android:name="SomeActivity"
    android:exported="false"
    tools:node="merge"
    tools:replace="android:exported" />

Now you can increase your version to 31.


问:
Delete duplicate pandas
I have a Pandas dataframe

```<code>ID,col_1,col_2,col_3,PostCode,City,Country
22,Apart 342,The abc,xyz,X01909,London,UK
33,Apt 342,xyz,The abc,X01909,London,UK
41,Apt 342,The abc,xyz,X01909,London,UK
</code>```

Above records are duplicates and one column value is present in other column, I need to delete these duplicates on a very large duplicates.

I have tried df=df.drop_duplicates(keep='first')

but it doesn't consider mis spelled data

More Sample

```<code>ID,col_1,col_2,col_3,PostCode,City,Country
1,Home 25,pearse strret,near spire, 4892,Manchester,UK
2,Pearse,Home no 25,near spire,4892,Manchester,UK
3,Home 25,Pearse street,near spire,4892,Manchester,UK
</code>```

答:
Pandas drop_duplicates can only perform exact comparisons.
So if you compare The abc, xyz and xyz, The abc it will see them as non-duplicates. Same goes for capitalization ("the abc" and "The Abc") and misspellings.

The presence of misspelling makes this virtually impossible to solve this perfectly.

If you want to use drop_duplicates I would suggest to try and clean the data as much as you can:

lowercase everything

create/get a dictionary of abbreviations for your field and expand them (e.g., replace "apt" with "apartment", "no" with "number", ...)

create a new column, col_4, that somehow combines the data of col_1, col_2 and col_3. This helps in case the information is the same, but switched between columns. (you could concatenate everything, split by word and sort alphabetically...)

After this, you can try and use df.drop_duplicates(keep="first", subset=<list-of-columns-to-check-for-duplicates>).

Of course, it will not mark all duplicates (performance depends on how good you cleaned / normalized the text), but it will help out.

If the dataset is not awfully big, I would suggest to look into fuzzy string matching (https://pypi.org/project/fuzzywuzzy/) and manually compare each pair of samples. You can compare each pair of (cleaned) data, and get a similarity score. You can assume two places are duplicates if the score is close to 100.

Quick and dirty example

from fuzzywuzzy import fuzz

# without even cleaning the texts
D="Home 25,pearse strret,near spire"
E="Pearse,Home no 25,near spire"
F="Home 25,Pearse street,near spire"

print(fuzz.token_set_ratio(D,E), fuzz.token_set_ratio(D,F), fuzz.token_set_ratio(E,F))
# (94, 97, 94)
# all similarity ratios are over 90: duplicates

A="Apart 342,The abc,xyz"
print(fuzz.token_set_ratio(A,E))
# 24
# similarity score low: not duplicate
```

Title: Delete duplicate pandas

Body:
I have a Pandas dataframe

ID,col_1,col_2,col_3,PostCode,City,Country
22,Apart 342,The abc,xyz,X01909,London,UK
33,Apt 342,xyz,The abc,X01909,London,UK
41,Apt 342,The abc,xyz,X01909,London,UK

Above records are duplicates and one column value is present in other column, I need to delete these duplicates on a very large duplicates.

I have tried df=df.drop_duplicates(keep='first')

but it doesn't consider mis spelled data

More Sample

ID,col_1,col_2,col_3,PostCode,City,Country
1,Home 25,pearse strret,near spire, 4892,Manchester,UK
2,Pearse,Home no 25,near spire,4892,Manchester,UK
3,Home 25,Pearse street,near spire,4892,Manchester,UK


问:
Why is rdflib so slow?
I have a large rdf file:

size: 470MB

number of lines: almost 6 million

unique triple subjects: about 650,000

triple amount: about 4,200,000

I loaded the rdf definition into the berkeley db backend of rdflib via:

```<code>graph = rdflib.Graph("Sleepycat")
graph.open("store", create=True)
graph.parse("authorities-geografikum_lds.rdf")
</code>```

It took many hours to complete on my notebook. The computer isn't really powerful (Intel B980 CPU, 4GB of RAM, no SSD) and the definition is large - but still, many hours for this task seems rather long. Maybe it is partly due to indexing / optimizing the data structures?

What is really irritating is the time it takes for the following queries to complete:

```<code>SELECT (COUNT(DISTINCT ?s) as ?c)
WHERE {
    ?s ?p ?o
}
</code>```

(Result: 667,445)

took over 20 minutes and

```<code>SELECT (COUNT(?s) as ?c)
WHERE {
    ?s ?p ?o
}
</code>```

(Result: 4,197,399)

took over 25 minutes.

I my experience, a Relational DBMS filled with comparable data would finish a corresponding query in a small fraction of the time given appropriate indexing.

So my questions are:

Why is rdflib so slow (especially for queries)?

Can I tune / optimize the database, like I can with indexes in a RDBMS?

Is another (free and "compact") triple store better suited for data of this size, performance-wise?

答:
I experienced a similar slow behavior of RDFLIB. For me, a possible solution lay in changing the underyling graph storage to Oxrdflib, which improved the speed of the SPARQL-query drastically.

see: https://pypi.org/project/oxrdflib/

Title: Why is rdflib so slow?

Body:
I have a large rdf file:

size: 470MB

number of lines: almost 6 million

unique triple subjects: about 650,000

triple amount: about 4,200,000

I loaded the rdf definition into the berkeley db backend of rdflib via:

graph = rdflib.Graph("Sleepycat")
graph.open("store", create=True)
graph.parse("authorities-geografikum_lds.rdf")

It took many hours to complete on my notebook. The computer isn't really powerful (Intel B980 CPU, 4GB of RAM, no SSD) and the definition is large - but still, many hours for this task seems rather long. Maybe it is partly due to indexing / optimizing the data structures?

What is really irritating is the time it takes for the following queries to complete:

SELECT (COUNT(DISTINCT ?s) as ?c)
WHERE {
    ?s ?p ?o
}

(Result: 667,445)

took over 20 minutes and

SELECT (COUNT(?s) as ?c)
WHERE {
    ?s ?p ?o
}

(Result: 4,197,399)

took over 25 minutes.

I my experience, a Relational DBMS filled with comparable data would finish a corresponding query in a small fraction of the time given appropriate indexing.

So my questions are:

Why is rdflib so slow (especially for queries)?

Can I tune / optimize the database, like I can with indexes in a RDBMS?

Is another (free and "compact") triple store better suited for data of this size, performance-wise?


问:
Regular expression to return string split up respecting nested parentheses
I know many answers exist to the question on how to split up a string respecting parenthesis, but they never do so recursively.
Looking at the string 1 2 3 (test 0, test 0) (test (0 test) 0):

Regex \s(?![^\(]*\)) returns "1", "2", "3", "(test 0, test 0)", "(test", "(0 test) 0)"

The regex I'm looking for would return either

"1", "2", "3", "(test 0, test 0)", "(test (0 test)0)"

or

"1", "2", "3", "test 0, test 0", "test (0 test)0"

which would let me recursively use it on the results again until no parentheses remain.

Ideally it would also respect escaped parentheses, but I myself am not this advanced in regex knowing only the basics.

Does anyone have an idea on how to take on this?

答:
Alternatively, you can use pyparsing as well.

import pyparsing as pp

pattern = pp.ZeroOrMore(pp.Regex(r'\S+') ^ pp.original_text_for(pp.nested_expr('(', ')')))

# Tests
string = '1 2 3 (test 0, test 0) (test (0 test) 0)'
result = pattern.parse_string(string).as_list()
answer = ['1', '2', '3', '(test 0, test 0)', '(test (0 test) 0)']
assert result == answer

string = ''
result = pattern.parse_string(string).as_list()
answer = []
assert result == answer

string = 'a'
result = pattern.parse_string(string).as_list()
answer = ['a']
assert result == answer

string = ' a (1) ! '
result = pattern.parse_string(string).as_list()
answer = ['a', '(1)', '!']
assert result == answer

string = ' a (b) cd (e f) g hi (j (k l) m) (o p (qr (s t) u v) w (x y) z)'
result = pattern.parse_string(string).as_list()
answer = ['a', '(b)', 'cd', '(e f)', 'g', 'hi', '(j (k l) m)', '(o p (qr (s t) u v) w (x y) z)']
assert result == answer
```
<p>* <code>pyparsing</code> can be installed by <code>pip install pyparsing</code></p>
<p>In addition, you can directly parse all the nested parentheses at once:</p>
<pre class="lang-py prettyprint-override"><code>pattern = pp.ZeroOrMore(pp.Regex(r'\S+') ^ pp.nested_expr('(', ')'))

string = '1 2 3 (test 0, test 0) (test (0 test) 0)'
result = pattern.parse_string(string).as_list()
answer = ['1', '2', '3', ['test', '0,', 'test', '0'], ['test', ['0', 'test'], '0']]
assert result == answer
</code>```

* Whitespace is a delimiter in this case.

Note:

If a pair of parentheses gets broken inside () (for example a(b(c), a(b)c), etc), an unexpected result is obtained or IndexError is raised. So be careful to use. (See: Python extract string in a phrase)

Body:
Alternatively, you can use pyparsing as well.

import pyparsing as pp

pattern = pp.ZeroOrMore(pp.Regex(r'\S+') ^ pp.original_text_for(pp.nested_expr('(', ')')))

# Tests
string = '1 2 3 (test 0, test 0) (test (0 test) 0)'
result = pattern.parse_string(string).as_list()
answer = ['1', '2', '3', '(test 0, test 0)', '(test (0 test) 0)']
assert result == answer

string = ''
result = pattern.parse_string(string).as_list()
answer = []
assert result == answer

string = 'a'
result = pattern.parse_string(string).as_list()
answer = ['a']
assert result == answer

string = ' a (1) ! '
result = pattern.parse_string(string).as_list()
answer = ['a', '(1)', '!']
assert result == answer

string = ' a (b) cd (e f) g hi (j (k l) m) (o p (qr (s t) u v) w (x y) z)'
result = pattern.parse_string(string).as_list()
answer = ['a', '(b)', 'cd', '(e f)', 'g', 'hi', '(j (k l) m)', '(o p (qr (s t) u v) w (x y) z)']
assert result == answer

* pyparsing can be installed by pip install pyparsing

In addition, you can directly parse all the nested parentheses at once:

pattern = pp.ZeroOrMore(pp.Regex(r'\S+') ^ pp.nested_expr('(', ')'))

string = '1 2 3 (test 0, test 0) (test (0 test) 0)'
result = pattern.parse_string(string).as_list()
answer = ['1', '2', '3', ['test', '0,', 'test', '0'], ['test', ['0', 'test'], '0']]
assert result == answer

* Whitespace is a delimiter in this case.

Note:

If a pair of parentheses gets broken inside () (for example a(b(c), a(b)c), etc), an unexpected result is obtained or IndexError is raised. So be careful to use. (See: Python extract string in a phrase)


问:
sed uinsg dynamic generated string replacement
Create a file a.tsv with two lines

```<code>echo aa bbb ccc ddd >a.tsv
echo xxxxxxxaa bbb ccc ddd >>a.tsv
</code>```

replace each line with dynamic generated string in a shell script a.sh

```<code>#!/bin/bash
#get line number
l1=$1
l2=$(expr $1 + 1)
#input file name
fn=$2
#get string in l1 line
vv="{${l1},${l1}p;${l2}q}"

v1=$(sed -n ${vv} $fn )
echo $v1
#cut off 6 chars from the end of string v1
v2=${v1::-6}
echo $v2
#replace l1 line v1 with new line v2
vb="{s|${v1}|${v2}|g }"
echo $vb

sed -i -r  '$vb'  $fn
</code>```

when I run it as:

```<code>./a.sh 1 a.tsv
</code>```

But I get those output:

What is wrong?

```<code>aa bbb ccc ddd
aa bbb c
{s|aa bbb ccc ddd|aa bbb c|g }
sed: -e expression #1, char 3: expected newer version of sed
</code>```

答:
The output of echo aa bbb ccc ddd >a.tsv is not a TSV (Tab-Separated Values) so don't name it a.tsv as that's misleading, use a.txt if you want it to have a suffix.

You can't easily do what you're trying to do robustly using sed since sed doesn't understand literal strings, see is-it-possible-to-escape-regex-metacharacters-reliably-with-sed. You should use a tool that does have literal string functions such as awk instead.

If I understand your code correctly it seems like this is what you're trying to do:

```<code>$ cat a.txt
aa bbb ccc ddd
xxxxxxxaa bbb ccc ddd
</code>```

```<code>$ cat a.sh
#!/usr/bin/env bash

awk -i inplace -v lineNr="$1" '
    NR == lineNr {
        $0 = substr($0,1,length()-6)
    }
    { print }
' "$2"
</code>```

```<code>$ ./a.sh 1 a.txt
</code>```

```<code>$ cat a.txt
aa bbb c
xxxxxxxaa bbb ccc ddd
</code>```

The above is using GNU awk for -i inplace, just like you were using GNU sed for -i (and -r), but unlike a sed solution, it'll work for any characters in the input.

Body:
Create a file a.tsv with two lines

echo aa bbb ccc ddd >a.tsv
echo xxxxxxxaa bbb ccc ddd >>a.tsv

replace each line with dynamic generated string in a shell script a.sh

#!/bin/bash
#get line number
l1=$1
l2=$(expr $1 + 1)
#input file name
fn=$2
#get string in l1 line
vv="{${l1},${l1}p;${l2}q}"

v1=$(sed -n ${vv} $fn )
echo $v1
#cut off 6 chars from the end of string v1
v2=${v1::-6}
echo $v2
#replace l1 line v1 with new line v2
vb="{s|${v1}|${v2}|g }"
echo $vb

sed -i -r  '$vb'  $fn

when I run it as:

./a.sh 1 a.tsv

But I get those output:

What is wrong?

aa bbb ccc ddd
aa bbb c
{s|aa bbb ccc ddd|aa bbb c|g }
sed: -e expression #1, char 3: expected newer version of sed

Body:
The output of echo aa bbb ccc ddd >a.tsv is not a TSV (Tab-Separated Values) so don't name it a.tsv as that's misleading, use a.txt if you want it to have a suffix.

You can't easily do what you're trying to do robustly using sed since sed doesn't understand literal strings, see is-it-possible-to-escape-regex-metacharacters-reliably-with-sed. You should use a tool that does have literal string functions such as awk instead.

If I understand your code correctly it seems like this is what you're trying to do:

$ cat a.txt
aa bbb ccc ddd
xxxxxxxaa bbb ccc ddd

$ cat a.sh
#!/usr/bin/env bash

awk -i inplace -v lineNr="$1" '
    NR == lineNr {
        $0 = substr($0,1,length()-6)
    }
    { print }
' "$2"

$ ./a.sh 1 a.txt

$ cat a.txt
aa bbb c
xxxxxxxaa bbb ccc ddd

The above is using GNU awk for -i inplace, just like you were using GNU sed for -i (and -r), but unlike a sed solution, it'll work for any characters in the input.


问:
Add CSS attributes to element with JavaScript
I want to add CSS attributes to my element, but my current solution loses all previous attributes that had an impact on the element.

function checkNr(id) {
  var value = document.getElementById(id).value;
  if (parseFloat(value) == NaN) {
    document.getElementById(id).setAttribute("style", "border:2px solid red; background-color: rgb(255, 125, 115);");
  }
  else {
    document.getElementById(id).setAttribute("style", "border:default; background-color: rgb(255, 255, 255);");
  }
}
```
<p>Before using this method the element already had the attributes:</p>
```float: left;
width: 50px;
```

Afterwards, the element loses these attributes, leaving only the specific attributes from the JavaScript method. So, I want to add attributes without replacing them.

答:
Setting the style attribute of the element directly will overwrite any previous value:

element.setAttribute("style", "border: 2px solid red; /* ... */")
```
<pre class="lang-html prettyprint-override"><code><div id="element" style="float: right; /* ... */">...</div>
<!-- becomes -->
<div id="element" style="border:; 2px solid red; /* ... */">...</div>
</code>```

Instead, set one property at a time using the element.style.property = value syntax:

const checkNr = id => {
  const element = document.getElementById(id)
  const isNotNum = isNaN(parseFloat(element.value))
  element.style.background = `rgb(255, ${isNotNum ? "125, 115" : "255, 255"})`
  element.style.border = isNotNum ? "2px solid red" : "default"
}
```
<p>Or, even better, add a conditional CSS class:</p>
<pre class="lang-javascript prettyprint-override"><code>const checkNr = id => {
  const element = document.getElementById(id)
  const isNotNum = isNaN(parseFloat(element.value))
  element.classList.add(isNotNum ? "not-number" : "is-number");
}
</code>```

.not-number {
  background-color: rgb(255, 125, 115);
  border: 2px solid red;
}
.is-number {
  background-color: rgb(255, 255, 255);
  border: default;
}
```

Body:
I want to add CSS attributes to my element, but my current solution loses all previous attributes that had an impact on the element.

function checkNr(id) {
  var value = document.getElementById(id).value;
  if (parseFloat(value) == NaN) {
    document.getElementById(id).setAttribute("style", "border:2px solid red; background-color: rgb(255, 125, 115);");
  }
  else {
    document.getElementById(id).setAttribute("style", "border:default; background-color: rgb(255, 255, 255);");
  }
}

Before using this method the element already had the attributes:

float: left;
width: 50px;

Afterwards, the element loses these attributes, leaving only the specific attributes from the JavaScript method. So, I want to add attributes without replacing them.

Body:
Setting the style attribute of the element directly will overwrite any previous value:

element.setAttribute("style", "border: 2px solid red; /* ... */")

<div id="element" style="float: right; /* ... */">...</div>
<!-- becomes -->
<div id="element" style="border:; 2px solid red; /* ... */">...</div>

Instead, set one property at a time using the element.style.property = value syntax:

const checkNr = id => {
  const element = document.getElementById(id)
  const isNotNum = isNaN(parseFloat(element.value))
  element.style.background = `rgb(255, ${isNotNum ? "125, 115" : "255, 255"})`
  element.style.border = isNotNum ? "2px solid red" : "default"
}

Or, even better, add a conditional CSS class:

const checkNr = id => {
  const element = document.getElementById(id)
  const isNotNum = isNaN(parseFloat(element.value))
  element.classList.add(isNotNum ? "not-number" : "is-number");
}

.not-number {
  background-color: rgb(255, 125, 115);
  border: 2px solid red;
}
.is-number {
  background-color: rgb(255, 255, 255);
  border: default;
}


答:
There are two issues with both your code blocks:

Indentation

Code after break. After break python will exit the while loop and not execute the print statements.

See the code blocks below:

```<code>i=1
while i<5:
    n=int(input("Enter a number  "))
    if n<=0:
        i+=1
        print(n)
        print("Loop ended , Negative Value Entered")
        break
    if n==None:
        i=1
        print(n)
        print("Loop ended , please do enter a number ")
        break

</code>```
```<code>i=1
while i<5:
    n=int(input("Enter a number  "))
    if n<=0:
        print(n)
        print("Loop ended , Negative Value Entered")
        i=1
        break
    elif n==None:
        i=1
        print(n)
        print("Loop ended , please do enter a number ")
        break
    else:
        i+=1

</code>```

Title: Uxexpected indent error while executing multiple if or elif using while loop and multiple break

Body:
I am writing a code that just takes 5 positive values and if the user enters a null or no value it should give an error please do enter a number I keep getting this indention error what are the rules for indentation in python also its not able to evaluate the null or none value and give the error message "please do enter a number", and if I am using elif statement its also the loop should after taking 5 values which is not happening I am new at programming and need your help

i=1
while i<5:
 n=int(input("Enter a number  "))
 if n<=0:
     i+=1
     break
print(n)
print("Loop ended , Negative Value Entered")
  if n==None:
     i=1
break
print(n)
print("Loop ended , please do enter a number ")

Here is another code with the elif

i=1
while i<5:
     n=int(input("Enter a number  "))
     if n<=0:
         break
         print(n)
         print("Loop ended , Negative Value Entered")
         i=1
     elif n==None:
             break
             i=1
             print(n)
             print("Loop ended , please do enter a number ")
     else:
             i+=1

Body:
There are two issues with both your code blocks:

Indentation

Code after break. After break python will exit the while loop and not execute the print statements.

See the code blocks below:

i=1
while i<5:
    n=int(input("Enter a number  "))
    if n<=0:
        i+=1
        print(n)
        print("Loop ended , Negative Value Entered")
        break
    if n==None:
        i=1
        print(n)
        print("Loop ended , please do enter a number ")
        break

i=1
while i<5:
    n=int(input("Enter a number  "))
    if n<=0:
        print(n)
        print("Loop ended , Negative Value Entered")
        i=1
        break
    elif n==None:
        i=1
        print(n)
        print("Loop ended , please do enter a number ")
        break
    else:
        i+=1


问:
Add various noise types to image when using tf.data.dataset
I have been using the function mentioned here to add different types of noise (Gauss, salt and pepper, etc) to an image.

However, I am trying to build an input pipeline using tf.data.Dataset.
I think I have figured out how to add Gaussian and Poisson noise:

@tf.function
def load_images(imagePath):
   label = tf.io.read_file(base_path + "/clean/" + imagePath)
   label = tf.image.decode_jpeg(label, channels=3)
   label = tf.image.convert_image_dtype(label, dtype=tf.float32)

   image=label+tf.random.normal(shape=tf.shape(label),mean=0,stddev=0.1**0.5) #Add Gauss noise
   #image=label+tf.random.poisson(shape=tf.shape(label),lam=0.3) #Add Poisson noise

   return (image, label)
```

How could I add salt & pepper and speckle noise, as well?

答:
Here's a way to do the random salt and pepper augmentation:

```<code>from sklearn.datasets import load_sample_image
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

china = load_sample_image('china.jpg')[None, ...].astype(np.float32) / 255

def salt_and_pepper(image, prob_salt=0.1, prob_pepper=0.1):
    random_values = tf.random.uniform(shape=image[0, ..., -1:].shape)
    image = tf.where(random_values < prob_salt, 1., image)
    image = tf.where(1 - random_values < prob_pepper, 0., image)
    return image

ds = tf.data.Dataset.from_tensor_slices(china).batch(1).map(salt_and_pepper)

result_image = next(iter(ds))

plt.imshow(result_image[0])
plt.show()
</code>```

Body:
I have been using the function mentioned here to add different types of noise (Gauss, salt and pepper, etc) to an image.

However, I am trying to build an input pipeline using tf.data.Dataset.
I think I have figured out how to add Gaussian and Poisson noise:

@tf.function
def load_images(imagePath):
   label = tf.io.read_file(base_path + "/clean/" + imagePath)
   label = tf.image.decode_jpeg(label, channels=3)
   label = tf.image.convert_image_dtype(label, dtype=tf.float32)

   image=label+tf.random.normal(shape=tf.shape(label),mean=0,stddev=0.1**0.5) #Add Gauss noise
   #image=label+tf.random.poisson(shape=tf.shape(label),lam=0.3) #Add Poisson noise

   return (image, label)

How could I add salt & pepper and speckle noise, as well?

Body:
Here's a way to do the random salt and pepper augmentation:

from sklearn.datasets import load_sample_image
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

china = load_sample_image('china.jpg')[None, ...].astype(np.float32) / 255

def salt_and_pepper(image, prob_salt=0.1, prob_pepper=0.1):
    random_values = tf.random.uniform(shape=image[0, ..., -1:].shape)
    image = tf.where(random_values < prob_salt, 1., image)
    image = tf.where(1 - random_values < prob_pepper, 0., image)
    return image

ds = tf.data.Dataset.from_tensor_slices(china).batch(1).map(salt_and_pepper)

result_image = next(iter(ds))

plt.imshow(result_image[0])
plt.show()


问:
Vue.js and vue-moment: "Failed to resolve filter: moment"
Trying to use vue-moment. The simplest possible example from the documentation doesn't work: https://jsfiddle.net/rjcpz9wt/

```<code><span>{{ new Date() | moment "dddd, MMMM Do YYYY" }}</span>
</code>```

Gives:

```<code>[Vue warn]: Failed to resolve filter: moment
</code>```

What is going on?

答:
My answer may be too late but still useful for others who are facing this problem right now.

But right still working at the same way:

```<code>import moment from 'moment';
const covertDateToString = value =>
moment(String(value)).format('MM/DD/YYYY');
export default {
  filters: {
data: covertDateToString,
  },....
}
</code>```

This is the way to do it.

```<code> <ul>
     <li v-for="person in people" v-bind:key="person.id">
     {{person.name}}{{person.dob | data}}
   </li>
   </ul>
</code>```

Body:
Trying to use vue-moment. The simplest possible example from the documentation doesn't work: https://jsfiddle.net/rjcpz9wt/

{{ new Date() | moment "dddd, MMMM Do YYYY" }}

Gives:

[Vue warn]: Failed to resolve filter: moment

What is going on?

Body:
My answer may be too late but still useful for others who are facing this problem right now.

But right still working at the same way:

import moment from 'moment';
const covertDateToString = value =>
moment(String(value)).format('MM/DD/YYYY');
export default {
  filters: {
data: covertDateToString,
  },....
}

This is the way to do it.

 <ul>
     <li v-for="person in people" v-bind:key="person.id">
     {{person.name}}{{person.dob | data}}
   </li>
   </ul>


问:
jQuery .click() event for multiple div's
I have some search results that I'm outputting that are of this form:

```<code>  <div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
</code>```

There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?

Here's how I'm getting the HTML from above:

```<code>$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;

var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
</code>```

I tried

```<code> $('div').click(function(){
    alert(this.id);
});
</code>```

and the alert says "searchresults" (no quotes).

答:
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.

```<code>$("#searchresults").delegate("div", "click", function() {
    console.log(this.id);
});
</code>```

See .delegate

Body:
I have some search results that I'm outputting that are of this form:

There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?

Here's how I'm getting the HTML from above:

$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;

var search_results="

";
$("#searchresults").append($(search_results));

I tried

 $('div').click(function(){
    alert(this.id);
});

and the alert says "searchresults" (no quotes).

Body:
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.

$("#searchresults").delegate("div", "click", function() {
    console.log(this.id);
});

See .delegate


问:
How this @OneToMany relationship should look like when using Map?
I have Order and Dish Entities. Order contains a map of Dish-Integer ( dish and how many times it was ordered ).

But I can't figure out what to write above map when I have a key as an Entity. How join column should look like.

```<code>    @Entity

        public class Order {
        @OneToMany(
                mappedBy = "order",
               cascade = CascadeType.ALL,
                orphanRemoval = true)
            private Map<Dish, Integer> dishesQuantity = new HashMap<>();
    }
        @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    public class Dish {
        private Order order;
}
</code>```

P.S. I would also appreciate it if you could tell me what happens if I skip annotating the join column.

答:
try this

```<code>    public class Order {
    @OneToMany(
                mappedBy = "order",
                cascade = CascadeType.ALL,
                orphanRemoval = true)
    private Map<Dish, Integer> dishesQuantity = new HashMap<>();
    }

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name ="dishes_quantity")
    public class Dish {
        private Order order;
    }

</code>```

As I know to use @JoinColumnis mapping foreign key. To use @JoinColumn annotation you can set foriegnkey name. If you don't use it. It will be automapping with Entity_ID of opposite entity field.
But I usually set @JoinColumn(name ='') to mapping field clearly.

Body:
I have Order and Dish Entities. Order contains a map of Dish-Integer ( dish and how many times it was ordered ).

But I can't figure out what to write above map when I have a key as an Entity. How join column should look like.

    @Entity

        public class Order {
        @OneToMany(
                mappedBy = "order",
               cascade = CascadeType.ALL,
                orphanRemoval = true)
            private Map<Dish, Integer> dishesQuantity = new HashMap<>();
    }
        @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    public class Dish {
        private Order order;
}

P.S. I would also appreciate it if you could tell me what happens if I skip annotating the join column.

Body:
try this

    public class Order {
    @OneToMany(
                mappedBy = "order",
                cascade = CascadeType.ALL,
                orphanRemoval = true)
    private Map<Dish, Integer> dishesQuantity = new HashMap<>();
    }

    @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name ="dishes_quantity")
    public class Dish {
        private Order order;
    }

As I know to use @JoinColumnis mapping foreign key. To use @JoinColumn annotation you can set foriegnkey name. If you don't use it. It will be automapping with Entity_ID of opposite entity field.
But I usually set @JoinColumn(name ='') to mapping field clearly.


问:
I am getting error while converting my next js project to docker
I'm trying to convert my Next js project to Docker. The Dockerfile I got from the next js github page worked fine for me and I got a build successfully.

```<code># Install dependencies only when needed
FROM node:16-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile

# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN yarn build

# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
# COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
# ENV NEXT_TELEMETRY_DISABLED 1

CMD ["node", "server.js"]
</code>```

I wrote this later.

```<code>docker run -p 3000:3000 imagename
</code>```

Then I faced such error and I can't solve it.

```<code>node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module '/app/server.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}
</code>```

I searched a lot on the internet but couldn't find much. What do you think I should do?

答:
```<code>FROM node:14-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json ./
RUN npm install --frozen-lockfile
RUN npm i next@12.0.8-canary.7

# Rebuild the source code only when needed
FROM node:14-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN yarn build

# Production image, copy all the files and run next
FROM node:14-alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# You only need to copy next.config.js if you are NOT using the default configuration
COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/.env ./

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
# ENV NEXT_TELEMETRY_DISABLED 1

CMD ["node", "server.js"]
</code>```

Solved my problem this is the new Dockerfile and it works for me.

Body:
I'm trying to convert my Next js project to Docker. The Dockerfile I got from the next js github page worked fine for me and I got a build successfully.

# Install dependencies only when needed
FROM node:16-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile

# Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN yarn build

# Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# You only need to copy next.config.js if you are NOT using the default configuration
# COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
# COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
# ENV NEXT_TELEMETRY_DISABLED 1

CMD ["node", "server.js"]

I wrote this later.

docker run -p 3000:3000 imagename

Then I faced such error and I can't solve it.

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module '/app/server.js'
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

I searched a lot on the internet but couldn't find much. What do you think I should do?

Body:
FROM node:14-alpine AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app
COPY package.json ./
RUN npm install --frozen-lockfile
RUN npm i next@12.0.8-canary.7

# Rebuild the source code only when needed
FROM node:14-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN yarn build

# Production image, copy all the files and run next
FROM node:14-alpine AS runner
WORKDIR /app

ENV NODE_ENV production

RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001

# You only need to copy next.config.js if you are NOT using the default configuration
COPY --from=builder /app/next.config.js ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/.env ./

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry.
# ENV NEXT_TELEMETRY_DISABLED 1

CMD ["node", "server.js"]

Solved my problem this is the new Dockerfile and it works for me.


问:
Are the Metal command line tools available without Xcode?
I have installed the Xcode Command Line Tools with xcode-select --install and they have been working fine for me. I am now trying to use Metal, and get this error:

```<code>xcrun: error: unable to find utility "metal", not a developer tool or in PATH
</code>```

The macOS SDK appears to be present at /Library/Developer/CommandLineTools/SDKs/MacOSX10.13.sdk but I can't find a metal utility either there on anyway else in the tools' directory.

An issue was filed with gfx-rs and put down to environment misconfiguration. It doesn't really look like this was the case, since the resolution was to point away from the Command Line Tools at the full application. An more knowledgeable issue was filed with Unreal Engine which implies that this is not possible with a CLI-only install.

Is it possible to use Metal without a full Xcode install?

答:
I've downloaded Xcode. Then I moved all special tools to CommandLineTools.
After that I threw Xcode into trash. For now everything seems to work fine.

Body:
I have installed the Xcode Command Line Tools with xcode-select --install and they have been working fine for me. I am now trying to use Metal, and get this error:

xcrun: error: unable to find utility "metal", not a developer tool or in PATH

The macOS SDK appears to be present at /Library/Developer/CommandLineTools/SDKs/MacOSX10.13.sdk but I can't find a metal utility either there on anyway else in the tools' directory.

An issue was filed with gfx-rs and put down to environment misconfiguration. It doesn't really look like this was the case, since the resolution was to point away from the Command Line Tools at the full application. An more knowledgeable issue was filed with Unreal Engine which implies that this is not possible with a CLI-only install.

Is it possible to use Metal without a full Xcode install?


问:
Alternative to exporting to csv export
I need an alternative to exporting to a csv file.  Basically, the requirement is to be able to allow the user to edit any amount of data from the database.  Currently, the option is to export the data to csv and then the user can update them in Microsoft Excel.  Thus, one can edit it without actually needing to have our web application installed.  However, we are trying to avoid this approach due to some issues we encountered with working with CSV on Excel.  Can someone recommend an alternative solution?    </p>

答:
Most programming languages have libraries to allow you to import/export excel directly which avoids many of these issues.  This means you won't have to tell you users to do special Save As when saving their files.

Java: http://poi.apache.org

Ruby: http://spreadsheet.rubyforge.org or http://roo.rubyforge.org

Google can provide options for other languages.

Title: Alternative to exporting to csv export


问:
Implement the Selenium library Python for a website backend
Is it possible to implement selenium in a code of a backend of a website we’re building.

I am building a website that scraps data from several websites using Python as a backend so I would like to know

答:
scrape the data and store it in a database. And then display that scraped data from the database.
Run scraping in a scheduled way to update your data.</p>