问:
Getting below error when i am installing robot framework-appiumlibrary
```<code>D:\Users\SBhagyad>pip install robotframework-appiumlibrary
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting robotframework-appiumlibrary
  Using cached robotframework_appiumlibrary-1.5.0.6-py2.py3-none-any.whl (33 kB)
Requirement already satisfied: robotframework>=2.6.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (3.1.2)
Requirement already satisfied: six>=1.10.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (1.14.0)
Collecting Appium-Python-Client>=0.28
  Using cached Appium-Python-Client-1.0.1.tar.gz (51 kB)
    ERROR: Command errored out with exit status 1:
     command: 'c:\python27\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"'; __file__='"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'd:\users\sbhagyad\appdata\local\temp\1\pip-pip-egg-info-dvpaun'
         cwd: d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\setup.py", line 19, in <module>
        from appium.common.helper import library_version
      File "appium\common\helper.py", line 20
        def extract_const_attributes(cls: type) -> Dict[str, Any]:
                                        ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
</code>```

Error

Getting Error when i am trying to install robot framework-appiumlibrary CMD
Please help to provide any solution for this
I am Using Python 2.7 and Robot Framework 3.1.2 (Python 2.7.16 on win32)

答:
I would suggest making a report on the AppiumLibrary github, as Python 2.7 should still be fully supported. This is a very big issue afterall.

UPDATE: The issue lies in the appium-python-client dependency, which is no longer supported on Python2. Currently the only feasible option is to update to Python3 and tell the devs that this is an issue. Alternatively you can look to install an older version that is workable for Python2, if that is even possible.

Body:
D:\Users\SBhagyad>pip install robotframework-appiumlibrary
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Collecting robotframework-appiumlibrary
  Using cached robotframework_appiumlibrary-1.5.0.6-py2.py3-none-any.whl (33 kB)
Requirement already satisfied: robotframework>=2.6.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (3.1.2)
Requirement already satisfied: six>=1.10.0 in c:\python27\lib\site-packages (from robotframework-appiumlibrary) (1.14.0)
Collecting Appium-Python-Client>=0.28
  Using cached Appium-Python-Client-1.0.1.tar.gz (51 kB)
    ERROR: Command errored out with exit status 1:
     command: 'c:\python27\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"'; __file__='"'"'d:\\users\\sbhagyad\\appdata\\local\\temp\\1\\pip-install-qb7jnj\\Appium-Python-Client\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'd:\users\sbhagyad\appdata\local\temp\1\pip-pip-egg-info-dvpaun'
         cwd: d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\
    Complete output (8 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "d:\users\sbhagyad\appdata\local\temp\1\pip-install-qb7jnj\Appium-Python-Client\setup.py", line 19, in <module>
        from appium.common.helper import library_version
      File "appium\common\helper.py", line 20
        def extract_const_attributes(cls: type) -> Dict[str, Any]:
                                        ^
    SyntaxError: invalid syntax
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

Error

Getting Error when i am trying to install robot framework-appiumlibrary CMD
Please help to provide any solution for this
I am Using Python 2.7 and Robot Framework 3.1.2 (Python 2.7.16 on win32)


来源: stackexchange

问:
Custom push animation broking default interactive pop animation
Inside my navigation controller delegate I have following code:

```<code>- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC {
    if ([toVC isKindOfClass:[ParentViewController class]]) {
        if (operation == UINavigationControllerOperationPush) {
            return [(ParentViewController *)toVC pushAnimator];
        }
    }
    return nil;
}
</code>```

Push animator is implemented as following (some view controllers override it to implement custom transition):

```<code>- (id<UIViewControllerAnimatedTransitioning>)pushAnimator {
    return nil;
}
</code>```

But after this default interactive pop animation is broken (but according to documentation if this method returns nil default animation will be used) even if I don't use custom transition for selected view controller.

How can I bring interactive pop gesture, but with custom push animations for some screens?

答:
Just implement UIGestureRecognizerDelegate on view controller (or anything actually), and do

navigationController?.interactivePopGestureRecognizer?.delegate = self
```

<p>it seems like you don't even have to implement anything, however you may want to try something like</p>

<pre class="lang-swift prettyprint-override"><code>func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    return navigationController?.viewControllers.count ?? 0 > 1
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Inside my navigation controller delegate I have following code:

- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                   animationControllerForOperation:(UINavigationControllerOperation)operation
                                                fromViewController:(UIViewController *)fromVC
                                                  toViewController:(UIViewController *)toVC {
    if ([toVC isKindOfClass:[ParentViewController class]]) {
        if (operation == UINavigationControllerOperationPush) {
            return [(ParentViewController *)toVC pushAnimator];
        }
    }
    return nil;
}

Push animator is implemented as following (some view controllers override it to implement custom transition):

- (id<UIViewControllerAnimatedTransitioning>)pushAnimator {
    return nil;
}

But after this default interactive pop animation is broken (but according to documentation if this method returns nil default animation will be used) even if I don't use custom transition for selected view controller.

How can I bring interactive pop gesture, but with custom push animations for some screens?

Body:
Just implement UIGestureRecognizerDelegate on view controller (or anything actually), and do

navigationController?.interactivePopGestureRecognizer?.delegate = self

it seems like you don't even have to implement anything, however you may want to try something like

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
    return navigationController?.viewControllers.count ?? 0 > 1
}

ContentLicense: CC BY-SA 4.0


问:
bash how to link multilines to command?
I would like to do something like that inside the script

```<code>readonly refScript="./libs/refScript.sh"
readonly config=$(cat myConfig.txt) #multiline config file

readonly exec="$refScript $config"

$($exec "$1" "$2" "$3" "$4") #exec has problem because $config is multiline
</code>```

I would like to do something like $($exec "$1" "$2" "$3" "$4") instead of and doing $("$refScript" "$config" "$1" "$2" "$3" "$4"). How to do this?

答:
As usuall, use bash arrays.</p>

```<code>refScript="./libs/refScript.sh"
config=$(<myConfig.txt)
exec=("$refScript" "$config")
"${exec[@]}" "$1" "$2" "$3" "$4"
</code>```

Title: bash how to link multilines to command?

Body:
I would like to do something like that inside the script

readonly refScript="./libs/refScript.sh"
readonly config=$(cat myConfig.txt) #multiline config file

readonly exec="$refScript $config"

$($exec "$1" "$2" "$3" "$4") #exec has problem because $config is multiline

I would like to do something like $($exec "$1" "$2" "$3" "$4") instead of and doing $("$refScript" "$config" "$1" "$2" "$3" "$4"). How to do this?

Body:
As usuall, use bash arrays.

refScript="./libs/refScript.sh"
config=$(<myConfig.txt)
exec=("$refScript" "$config")
"${exec[@]}" "$1" "$2" "$3" "$4"


问:
WSO2 API Manger Analytics : Does the analytics platform support third party APIs for monitoring?
Does WSO2 APIM Analytics allow to configure third party APIs for Monitoring and Analytics ?

Like, I've APIs developed in spring-boot. Is there any way to configure these APIs to WSO2 APIM Analytics server, so that I can do performance monitoring and analytics?

Any help appreciated. Thanks.

答:
By default WSO2 doesn't have support for this. But you will be able to get this done by customizing Stream Processor's events to support the third party APIs' OAuth App and API specific info.

Basically this is not supported OOTB and you have to customize WSO2's Analytics event streams, data bases, etc to get this done.


问:
remove last item from array and rerender in react failed
I want to remove last item from array and rerender but I seem can't get it to work without using filter. But in my case I don't think filter is needed because I will always take away last item hence I use pop()

```<code>const CustomInput = (): JSX.Element => {
  const [inputValue, setInputValue] = useState<string>("");
  const [items, setitems] = useState<string[]>(['1', '2']);

  const handleKeyDown = (e: any) => {

    if (items.length && e.keyCode === 8 && inputValue === "") {
      const newitems = items;
      newitems.pop();

      /* what is wrong here */
      console.log('newitems', newitems)

      setitems(newitems);
    }
  };

  const handleChange = (e: React.SyntheticEvent<HTMLInputElement>) => {
    const target = e.target as HTMLInputElement;
    setInputValue(target.value);
  };

  return (
    <div>
      {items.map((oo, index) => (
        <div >
          <span>
            {oo}
          </span>
        </div>
      ))}
      <input
        autoFocus
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        onChange={handleChange}
      />
    </div>
  );
};
</code>```

https://stackblitz.com/edit/react-ts-hxzcpt

What's wrong?

答:
You are mutating state directly.
here is a solution.</p>

```<code>const newitems = [...items];
newitems.pop();
</code>```

Body:
I want to remove last item from array and rerender but I seem can't get it to work without using filter. But in my case I don't think filter is needed because I will always take away last item hence I use pop()

const CustomInput = (): JSX.Element => {
  const [inputValue, setInputValue] = useState<string>("");
  const [items, setitems] = useState<string[]>(['1', '2']);

  const handleKeyDown = (e: any) => {

    if (items.length && e.keyCode === 8 && inputValue === "") {
      const newitems = items;
      newitems.pop();

      /* what is wrong here */
      console.log('newitems', newitems)

      setitems(newitems);
    }
  };

  const handleChange = (e: React.SyntheticEvent<HTMLInputElement>) => {
    const target = e.target as HTMLInputElement;
    setInputValue(target.value);
  };

  return (

      {items.map((oo, index) => (

            {oo}

      ))}
      <input
        autoFocus
        type="text"
        value={inputValue}
        onKeyDown={handleKeyDown}
        onChange={handleChange}
      />

  );
};

https://stackblitz.com/edit/react-ts-hxzcpt

What's wrong?

Body:
You are mutating state directly.
here is a solution.

const newitems = [...items];
newitems.pop();


问:
how to prevent recyclerView auto scroll?
I have a recyclerView with chat message and open it will scroll to the latest position,but i update item's height in onBindViewHolder and recyclerView will auto scroll to incorrect position,how to pin item position after update item's height?</p>

答:
if you want scroll to last item use lm.setStackFromEnd(true);

use below code:

```<code>LinearLayoutManager llm = new LinearLayoutManager(getContext());
llm.setStackFromEnd(true);
recyclerView.setLayoutManager(llm);
</code>```

Body:
if you want scroll to last item use lm.setStackFromEnd(true);

use below code:

LinearLayoutManager llm = new LinearLayoutManager(getContext());
llm.setStackFromEnd(true);
recyclerView.setLayoutManager(llm);


问:
Unable To Read JSON From File
Below error while reading JSON from file

```<code>"Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING
 at line 1 column 1 path $
        at com.google.gson.Gson.fromJson(Gson.java:826)
        at com.google.gson.Gson.fromJson(Gson.java:779)
        at com.google.gson.Gson.fromJson(Gson.java:728)
        at resources.ReadJsonFile.getjsondata(ReadJsonFile.java:50)
        at resources.ReadJsonFile.main(ReadJsonFile.java:30)
     Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
        at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.Gson.fromJson(Gson.java:814)
        ... 4 more"
</code>```

Below is my code

```<code>public class ReadJsonFile < T > {

    public static void main(String[] args) {
        ReadJsonFile read = new ReadJsonFile();
        read.getjsondata("src/test/resource/testdataresource/addplacerequest.json",
            Addbook.class);
    }
    public List < T > getjsondata(String filepath, Class < T > typeofT) {

        //filepath= "src/test/resource/testdataresource/addplacerequest.json";
        Gson gson = new Gson();;
        BufferedReader bufferReader = null;
        try {

            bufferReader = new BufferedReader(new FileReader(filepath));

            Type ListType = new TypeToken < ArrayList < T >> () {}.getType();
            /
            List < T > arraylist = gson.fromJson(filepath, ListType);
            Iterator iter = arraylist.iterator();
            while (iter.hasNext()) {
                System.out.println(iter.next());
            }
            return (arraylist);

        } catch (FileNotFoundException e) {
            throw new RuntimeException("Json file not found at path : " + filepath);
        } finally {
            try {
                if (bufferReader != null) bufferReader.close();
            } catch (IOException ignore) {}
        }
    }

}
</code>```

Pojo class :

```<code>public class Addbook {

    public String name;
    public int isbn;
    public String aisle;
    public String author;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getIsbn() {
        return isbn;
    }
    public void setIsbn(int isbn) {
        this.isbn = isbn;
    }
    public String getAisle() {
        return aisle;
    }
    public void setAisle(String aisle) {
        this.aisle = aisle;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Addbook [name=" + name + ",isbn=" + isbn + ",aisle=" + aisle + ",authur=" + author + "]";
    }

}
</code>```

JSON :

```<code>[{
        "name": "The King",
        "isbn": 67786,
        "aisle": "hfhdh",
        "author": "Biju"
    },
    {
        "name": "The King",
        "isbn": 67786,
        "aisle": "hfhdh",
        "author": "Biju"
    }
]
</code>```

答:
A small change in code,
Instead of </p>

```<code>List<T> arraylist = gson.fromJson(filepath, ListType);
</code>```

<p>Use </p>

```<code>List<T> arraylist = gson.fromJson(bufferReader, ListType);

</code>```

Title: Unable To Read JSON From File

Body:
Below error while reading JSON from file

"Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING
 at line 1 column 1 path $
        at com.google.gson.Gson.fromJson(Gson.java:826)
        at com.google.gson.Gson.fromJson(Gson.java:779)
        at com.google.gson.Gson.fromJson(Gson.java:728)
        at resources.ReadJsonFile.getjsondata(ReadJsonFile.java:50)
        at resources.ReadJsonFile.main(ReadJsonFile.java:30)
     Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
        at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.Gson.fromJson(Gson.java:814)
        ... 4 more"

Below is my code

public class ReadJsonFile < T > {

    public static void main(String[] args) {
        ReadJsonFile read = new ReadJsonFile();
        read.getjsondata("src/test/resource/testdataresource/addplacerequest.json",
            Addbook.class);
    }
    public List < T > getjsondata(String filepath, Class < T > typeofT) {

        //filepath= "src/test/resource/testdataresource/addplacerequest.json";
        Gson gson = new Gson();;
        BufferedReader bufferReader = null;
        try {

            bufferReader = new BufferedReader(new FileReader(filepath));

            Type ListType = new TypeToken < ArrayList < T >> () {}.getType();
            /
            List < T > arraylist = gson.fromJson(filepath, ListType);
            Iterator iter = arraylist.iterator();
            while (iter.hasNext()) {
                System.out.println(iter.next());
            }
            return (arraylist);

        } catch (FileNotFoundException e) {
            throw new RuntimeException("Json file not found at path : " + filepath);
        } finally {
            try {
                if (bufferReader != null) bufferReader.close();
            } catch (IOException ignore) {}
        }
    }

}

Pojo class :

public class Addbook {

    public String name;
    public int isbn;
    public String aisle;
    public String author;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getIsbn() {
        return isbn;
    }
    public void setIsbn(int isbn) {
        this.isbn = isbn;
    }
    public String getAisle() {
        return aisle;
    }
    public void setAisle(String aisle) {
        this.aisle = aisle;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }

    @Override
    public String toString() {
        return "Addbook [name=" + name + ",isbn=" + isbn + ",aisle=" + aisle + ",authur=" + author + "]";
    }

}

JSON :

[{
        "name": "The King",
        "isbn": 67786,
        "aisle": "hfhdh",
        "author": "Biju"
    },
    {
        "name": "The King",
        "isbn": 67786,
        "aisle": "hfhdh",
        "author": "Biju"
    }
]

Body:
A small change in code,
Instead of

List<T> arraylist = gson.fromJson(filepath, ListType);

Use

List<T> arraylist = gson.fromJson(bufferReader, ListType);


答:
array::slice

You are mutating and saving the same state array reference back into state, which react sees as a "non-op", i.e. the array reference is the same so it bails on re-rendering it. You can use slice to copy the 0th through second to last elements into a new array reference, basically slicing "off" the last element each callback invocation.

```<code>const handleKeyDown = (e: any) => {

  if (items.length && e.keyCode === 8 && inputValue === "") {
    setitems(items.slice(0, -1)); // index 0 to last - 1
  }
};
</code>```

Title: remove last item from array and rerender in react failed

Body:
array::slice

You are mutating and saving the same state array reference back into state, which react sees as a "non-op", i.e. the array reference is the same so it bails on re-rendering it. You can use slice to copy the 0th through second to last elements into a new array reference, basically slicing "off" the last element each callback invocation.

const handleKeyDown = (e: any) => {

  if (items.length && e.keyCode === 8 && inputValue === "") {
    setitems(items.slice(0, -1)); // index 0 to last - 1
  }
};


问:
Get threadGroup using thread id or name
Is there a way to get threadGroup information by passing/using thread id or name? Problem is, I can not use currentThread() method. I want to get threadGroup information of specific threads.

答:
You can use Thread.getAllStackTraces() to get a list of all threads. With the keys from that Map you can find the thread you want. After that you can simply call getThreadGroup() to get the thread group. Check the following example:

```<code>Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) {
    Thread t = entry.getKey();
    ThreadGroup group = t.getThreadGroup();
    System.out.println(t+" with group: "+group);
}
</code>```

This will generate an output like this:

Thread[main,5,main] with group: java.lang.ThreadGroup[name=main,maxpri=10]
Thread[Finalizer,8,system] with group: java.lang.ThreadGroup[name=system,maxpri=10]
Thread[Reference Handler,10,system] with group: java.lang.ThreadGroup[name=system,maxpri=10]
Thread[Signal Dispatcher,9,system] with group: java.lang.ThreadGroup[name=system,maxpri=10]
```

Title: Get threadGroup using thread id or name

Body:
You can use Thread.getAllStackTraces() to get a list of all threads. With the keys from that Map you can find the thread you want. After that you can simply call getThreadGroup() to get the thread group. Check the following example:

Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
for (Map.Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) {
    Thread t = entry.getKey();
    ThreadGroup group = t.getThreadGroup();
    System.out.println(t+" with group: "+group);
}

This will generate an output like this:

Thread[main,5,main] with group: java.lang.ThreadGroup[name=main,maxpri=10]
Thread[Finalizer,8,system] with group: java.lang.ThreadGroup[name=system,maxpri=10]
Thread[Reference Handler,10,system] with group: java.lang.ThreadGroup[name=system,maxpri=10]
Thread[Signal Dispatcher,9,system] with group: java.lang.ThreadGroup[name=system,maxpri=10]


问:
Change variable value of the already running program
I think it is impossible, but I should try.

I have a program, that is doing a physical simulation and recording frames to files. It is recording until the breakup value is not achieved, like:

```<code>int counter=0; //global variable

void SomeFunction()
{
...
if(counter == 400) //written exactly by this way, i.e. 400 is not a variable, just a number
PostQuitMessage(0);
else
MakeScreenshot();

counter++;
...
}
</code>```

The problem is that I forgot to change if(counter == 400) to if(counter == 1000) and now program will be finished with 400 frames, although I need exactly 1000.

I can’t just recompile the program because calculations are very heavy and the program is already running for 2 days, I can’t wait.

It is very important for me, is there any way to change the if statement, or exactly the variable value during the program running?

The only hope I have, is, as far as I remember there was programs that could like change money/health/another stuff in games, and there user exactly could search a variable by value, and change it

Currently it is on about 200-300 frame, I have so little time to fix it.

答:
You can use the Windows functions ReadProcessMemory and WriteProcessMemory.

But you need to determine the position of the value 400. Looking for the value in the running program can be done with the above functions. Depending on the size of the constant, it should be either a USHORT or an UINT.

So you can use the following steps:

Look for the value in a second instance

Isolate the surrounding OpCode sequence.

For example, a cmp xxx, 400

Look for this OpCode sequence in the running executable to find the unique location and replace the crucial value by 1000.

This can be called "hot-patch". It's how simple in-memory cheats do work and requires root privileges.

Body:
I think it is impossible, but I should try.

I have a program, that is doing a physical simulation and recording frames to files. It is recording until the breakup value is not achieved, like:

int counter=0; //global variable

void SomeFunction()
{
...
if(counter == 400) //written exactly by this way, i.e. 400 is not a variable, just a number
PostQuitMessage(0);
else
MakeScreenshot();

counter++;
...
}

The problem is that I forgot to change if(counter == 400) to if(counter == 1000) and now program will be finished with 400 frames, although I need exactly 1000.

I can’t just recompile the program because calculations are very heavy and the program is already running for 2 days, I can’t wait.

It is very important for me, is there any way to change the if statement, or exactly the variable value during the program running?

The only hope I have, is, as far as I remember there was programs that could like change money/health/another stuff in games, and there user exactly could search a variable by value, and change it

Currently it is on about 200-300 frame, I have so little time to fix it.


问:
Quill Content not displaying when called through Show/Hide Buttons
I have an initialized quill with all its components and CSS.
My problem is, I have an edit button on my page to load MySQL contents. When the user clicks the edit button the content should be available for user editing. I use quill for this purpose. Quill perfectly initialized and displaying the edit space and toolbar.

But not showing the contents inside the edit space. I have called the content through div as required and not through textarea, but for some reason, the content is not displayed. I don't know why?

Could anyone please help me figure out the reasons and a possible resolution.

```<code><div style="height: 150px;" class="mb-0" data-toggle="quill" data-quill-placeholder="Enter description"> <div><h1>Hello World!</h1> <p>Some initial <strong>bold</strong> text</p> <p><br></p></div> </div>

<script> var editor = new Quill('[data-toggle="quill"]', { modules: { syntax: true, toolbar: true, theme: 'snow' }, placeholder: 'Compose an epic...', theme: 'snow' }); </script>
</code>```

My Codepen

答:
So, I figured the bug in my code.

I removed syntax: true, and added $(document).ready(function () {}); to the quill function. Its now working.

Body:
I have an initialized quill with all its components and CSS.
My problem is, I have an edit button on my page to load MySQL contents. When the user clicks the edit button the content should be available for user editing. I use quill for this purpose. Quill perfectly initialized and displaying the edit space and toolbar.

But not showing the contents inside the edit space. I have called the content through div as required and not through textarea, but for some reason, the content is not displayed. I don't know why?

Could anyone please help me figure out the reasons and a possible resolution.

Hello World!

Some initial bold text

My Codepen


问:
std::async with non static member functions
I am trying to evaluate a part of my code asynchronously

```<code>#include <stdio.h>
#include <string>
#include <memory>
#include <future>
#include <map>

namespace IG
{
    typedef std::map<uint, std::string> CadDef;

    class FooFoo
    {
        CadDef foo()
        {
            CadDef cdef{};
            cdef[1] = "aa";
            return cdef;
        }
    };
}

int main()
{
    auto ptr = std::make_unique<IG::FooFoo>();
    std::future<IG::CadDef> resFut = std::async(ptr->foo);
    auto res = resFut.get();
    return 0;
}
</code>```

But the code doesn't compile -
(On gcc)

```<code>error: invalid use of non-static member function ‘IG::CadDef IG::FooFoo::foo()’
</code>```

(on msvc -- my main program, from where I abstracted the minimal example)

```<code>error C3867: 'IG::FooFoo::foo': non-standard syntax; use '&' to create a pointer to member
error C2672: 'std::async': no matching overloaded function found
error C2780: 'std::future<_Invoke_traits<void,decay<_Ty>::type,decay<_ArgTypes>::type...>::type> std::async(std::launch,_Fty &&,_ArgTypes &&...)': expects 3 arguments - 1 provided
</code>```

Seems like MSVC is complaining that I have not used ptr->foo() but I am not sure.

What am I doing wrong?

答:
You can use a lambda like following, using a policy*

```<code>auto handle = std::async(std::launch::async, [&ptr](){
        return ptr->foo(); // Ofcourse make foo public in your snippet
});

auto res = handle.get();
</code>```

*Not necessarily required

Body:
I am trying to evaluate a part of my code asynchronously

#include <stdio.h>
#include <string>
#include <memory>
#include <future>
#include <map>

namespace IG
{
    typedef std::map<uint, std::string> CadDef;

    class FooFoo
    {
        CadDef foo()
        {
            CadDef cdef{};
            cdef[1] = "aa";
            return cdef;
        }
    };
}

int main()
{
    auto ptr = std::make_unique<IG::FooFoo>();
    std::future<IG::CadDef> resFut = std::async(ptr->foo);
    auto res = resFut.get();
    return 0;
}

But the code doesn't compile -
(On gcc)

error: invalid use of non-static member function ‘IG::CadDef IG::FooFoo::foo()’

(on msvc -- my main program, from where I abstracted the minimal example)

error C3867: 'IG::FooFoo::foo': non-standard syntax; use '&' to create a pointer to member
error C2672: 'std::async': no matching overloaded function found
error C2780: 'std::future<_Invoke_traits<void,decay<_Ty>::type,decay<_ArgTypes>::type...>::type> std::async(std::launch,_Fty &&,_ArgTypes &&...)': expects 3 arguments - 1 provided

Seems like MSVC is complaining that I have not used ptr->foo() but I am not sure.

What am I doing wrong?

Body:
You can use a lambda like following, using a policy*

auto handle = std::async(std::launch::async, [&ptr](){
        return ptr->foo(); // Ofcourse make foo public in your snippet
});

auto res = handle.get();

*Not necessarily required


问:
Xamarin Forms Custom SearchbarRenderer with Loadingcircle like Netflix
I really want to implement a loading circle in the searchbar (overriding the cancel button while loading) on android like Netflix.

Currently Im getting the cancel button with

```<code>var searchBttId = searchView.Resources.GetIdentifier("android:id/search_close_btn", null, null);
var imbCancel = (searchView.FindViewById(searchBttId) as Android.Widget.ImageView)
</code>```

but I dont know how to add a progresscircle and how to interact with it. I thought of adding it with AddView, but nothing pops up when testing.

Test:

```<code>var _v = new Android.Widget.ImageView(Context) { };
_v.SetBackgroundColor(new Android.Graphics.Color(200, 0, 0));
var c = new LayoutParams(500, 500);
_v.LayoutParameters = c;
searchView.AddView(_v);
</code>```

答:
I really want to implement a loading circle in the searchbar (overriding the cancel button while loading) on android like Netflix.

According to your description, you want to override searchbar's search_close_btn using other icon, like loading circle? Am I right?

If yes, I suggest you can use custom render to change searchbar's search_close_btn image.

Firstly, create custom Searchbar that inherit SearchBar in Form.cs.

```<code>public  class MySearchBar:SearchBar
{

}
</code>```

Then implementing custom render in Android platform.

```<code>[assembly: ExportRenderer(typeof(MySearchBar), typeof(MySearchBarRenderer))]
namespace demo3.Droid
{
 public class MySearchBarRenderer: SearchBarRenderer
{
    public MySearchBarRenderer(Context context):base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            var searchView = Control;

            int searchViewCloseButtonId = Control.Resources.GetIdentifier("android:id/search_close_btn", null, null);
            var closeIcon = searchView.FindViewById(searchViewCloseButtonId);
            (closeIcon as ImageView).SetImageResource(Resource.Drawable.plu3);
        }
    }
}
}
</code>```

Please see the gif:

About Custom Render, you can take a look:

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/entry

Body:
I really want to implement a loading circle in the searchbar (overriding the cancel button while loading) on android like Netflix.

Currently Im getting the cancel button with

var searchBttId = searchView.Resources.GetIdentifier("android:id/search_close_btn", null, null);
var imbCancel = (searchView.FindViewById(searchBttId) as Android.Widget.ImageView)

but I dont know how to add a progresscircle and how to interact with it. I thought of adding it with AddView, but nothing pops up when testing.

Test:

var _v = new Android.Widget.ImageView(Context) { };
_v.SetBackgroundColor(new Android.Graphics.Color(200, 0, 0));
var c = new LayoutParams(500, 500);
_v.LayoutParameters = c;
searchView.AddView(_v);

Body:
I really want to implement a loading circle in the searchbar (overriding the cancel button while loading) on android like Netflix.

According to your description, you want to override searchbar's search_close_btn using other icon, like loading circle? Am I right?

If yes, I suggest you can use custom render to change searchbar's search_close_btn image.

Firstly, create custom Searchbar that inherit SearchBar in Form.cs.

public  class MySearchBar:SearchBar
{

}

Then implementing custom render in Android platform.

[assembly: ExportRenderer(typeof(MySearchBar), typeof(MySearchBarRenderer))]
namespace demo3.Droid
{
 public class MySearchBarRenderer: SearchBarRenderer
{
    public MySearchBarRenderer(Context context):base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<SearchBar> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            var searchView = Control;

            int searchViewCloseButtonId = Control.Resources.GetIdentifier("android:id/search_close_btn", null, null);
            var closeIcon = searchView.FindViewById(searchViewCloseButtonId);
            (closeIcon as ImageView).SetImageResource(Resource.Drawable.plu3);
        }
    }
}
}

Please see the gif:

About Custom Render, you can take a look:

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/entry


问:
Exception: The file or folder has invalid access settings. (line 31, file "newfile")
```<code>var holderArray = [
  folder.getId(),
  folder.getName(),
  folder.getOwner(),
  folderPath,
  folder.getDateCreated(),
  folder.getLastUpdated(),
  folder.getAccess(user),
  folder.getSharingAccess(),
  folder.getSharingPermission(),
  folder.getUrl()
];
</code>```

For some reason, this above line is causing an error saying I have invalid access settings.
I am not sure why this is happening. I have specified which folder to access and I have also given access to my Drive folder as well.

答:
If you are using this code in an onOpen() or onEdit() function GS will throw this error.
The logic is that those functions can run for anyone that has access to the sheet but they may not have acces to your google drive.</p>

Body:
var holderArray = [
  folder.getId(),
  folder.getName(),
  folder.getOwner(),
  folderPath,
  folder.getDateCreated(),
  folder.getLastUpdated(),
  folder.getAccess(user),
  folder.getSharingAccess(),
  folder.getSharingPermission(),
  folder.getUrl()
];

For some reason, this above line is causing an error saying I have invalid access settings.
I am not sure why this is happening. I have specified which folder to access and I have also given access to my Drive folder as well.


问:
When will the application receive a install_referrer with content utm_source=(not%20set)&utm_medium=(not%20set)?
I'm using instll_referrrer tracking the user installation. Recently, I found a lot of user send the refer utm_source=(not%20set)&utm_medium=(not%20set) to my server.

I searched this on Google, and find a artical https://plus.google.com/+AndroidDevelopers/posts/E54ae9beKLB which tell me this will be set as default for user from deeplinks. And then I searched the definition of deeplink but I don't quite understand it.

From now on, if there is no referrer parameter in the URL, a default
  will be set to separate organic installs from deeplinks (i.e. a third
  party referral to your Play Store listing).

Dose this means if I received some install_referrer with content content utm_source=(not%20set)&utm_medium=(not%20set),the user who sent these referrer have installed my app by third party referral which has a format like {scheme}://{host_path} ?

答:
The apps do not pass referrer to the store if it comes from Google and Facebook.

So you get utm_source=(not%20set)&utm_medium=(not%20set)


问:
Unhandled Exception: NoSuchMethodError: The getter 'focusScopeNode' was called on null
I am new to flutter and have been facing problem to "focusScopeNode". I have also tried the other solutions on this website as well but unable to detect the problem. I am not able to understand the concept of Context and builders. Any kind of help would  be greatly appreciated.

Unhandled Exception: NoSuchMethodError: The getter 'focusScopeNode'
  was called on null. E/flutter (18828): Receiver: null E/flutter
  (18828): Tried calling: focusScopeNode

```<code>class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      routes: {
        '/login': (context) => Login(),
      },
      title: 'NavigationDrawer Demo',
      theme: new ThemeData(
        primarySwatch: Colors.red,
      ),
      home: new HomePage(),
    );
  }
}
class DrawerItem {
  String title;
  IconData icon;
  DrawerItem(this.title, this.icon);
}
FirebaseUser user;

class HomePage extends StatefulWidget {
  HomePage({
    this.auth,
    this.onSignedOut,
  });
  final AuthImplementation auth;
  final VoidCallback onSignedOut;
  final drawerItems = [
    new DrawerItem("Home", Icons.home),
    new DrawerItem("Logout", Icons.exit_to_app),
  ];

  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  void _logOutUser() async {
    try {
      await widget.auth.signOut();
      widget.onSignedOut();

    } catch (e) {
      print(e.toString());
    }
  }

  int _selectedDrawerIndex = 0;
  _getDrawerItemWidget(int pos) {
    switch (pos) {
      case 0:
        return new MyTabbedPage();
      case 7:
        _logOutUser();
        return new StartApp();
      default:
        return new Text("Error");
    }
  }

  _onSelectItem(int index) {
    setState(() => _selectedDrawerIndex = index);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    var drawerOptions = <Widget>[];
    for (var i = 0; i < widget.drawerItems.length; i++) {
      var d = widget.drawerItems[i];
      drawerOptions.add(
          new ListTile(
            leading: new Icon(d.icon),
            title: new Text(d.title),
            selected: i == _selectedDrawerIndex,
            onTap: () => _onSelectItem(i),
          )
      );
    }
  }
}
</code>```

答:
I think the issue could be where you called your _onSelectedItem() method. Try putting the method within the Build context like so:

```<code>@override
  Widget build(BuildContext context) {

_onSelectItem(int index) {
    setState(() => _selectedDrawerIndex = index);
    Navigator.of(context).pop();
  }

    var drawerOptions = <Widget>[];
    for (var i = 0; i < widget.drawerItems.length; i++) {
      var d = widget.drawerItems[i];
      drawerOptions.add(
          new ListTile(
            leading: new Icon(d.icon),
            title: new Text(d.title),
            selected: i == _selectedDrawerIndex,
            onTap: () => _onSelectItem(i),
          )
      );
    }
  }
</code>```

Could be that when you call Navigator.pop(context), it has no idea what the "context" is. So by putting the method within the Build(context) it should solve it.

Body:
I am new to flutter and have been facing problem to "focusScopeNode". I have also tried the other solutions on this website as well but unable to detect the problem. I am not able to understand the concept of Context and builders. Any kind of help would  be greatly appreciated.

Unhandled Exception: NoSuchMethodError: The getter 'focusScopeNode'
  was called on null. E/flutter (18828): Receiver: null E/flutter
  (18828): Tried calling: focusScopeNode

class Homepage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      routes: {
        '/login': (context) => Login(),
      },
      title: 'NavigationDrawer Demo',
      theme: new ThemeData(
        primarySwatch: Colors.red,
      ),
      home: new HomePage(),
    );
  }
}
class DrawerItem {
  String title;
  IconData icon;
  DrawerItem(this.title, this.icon);
}
FirebaseUser user;

class HomePage extends StatefulWidget {
  HomePage({
    this.auth,
    this.onSignedOut,
  });
  final AuthImplementation auth;
  final VoidCallback onSignedOut;
  final drawerItems = [
    new DrawerItem("Home", Icons.home),
    new DrawerItem("Logout", Icons.exit_to_app),
  ];

  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
  void _logOutUser() async {
    try {
      await widget.auth.signOut();
      widget.onSignedOut();

    } catch (e) {
      print(e.toString());
    }
  }

  int _selectedDrawerIndex = 0;
  _getDrawerItemWidget(int pos) {
    switch (pos) {
      case 0:
        return new MyTabbedPage();
      case 7:
        _logOutUser();
        return new StartApp();
      default:
        return new Text("Error");
    }
  }

  _onSelectItem(int index) {
    setState(() => _selectedDrawerIndex = index);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    var drawerOptions = <Widget>[];
    for (var i = 0; i < widget.drawerItems.length; i++) {
      var d = widget.drawerItems[i];
      drawerOptions.add(
          new ListTile(
            leading: new Icon(d.icon),
            title: new Text(d.title),
            selected: i == _selectedDrawerIndex,
            onTap: () => _onSelectItem(i),
          )
      );
    }
  }
}

Body:
I think the issue could be where you called your _onSelectedItem() method. Try putting the method within the Build context like so:

@override
  Widget build(BuildContext context) {

_onSelectItem(int index) {
    setState(() => _selectedDrawerIndex = index);
    Navigator.of(context).pop();
  }

    var drawerOptions = <Widget>[];
    for (var i = 0; i < widget.drawerItems.length; i++) {
      var d = widget.drawerItems[i];
      drawerOptions.add(
          new ListTile(
            leading: new Icon(d.icon),
            title: new Text(d.title),
            selected: i == _selectedDrawerIndex,
            onTap: () => _onSelectItem(i),
          )
      );
    }
  }

Could be that when you call Navigator.pop(context), it has no idea what the "context" is. So by putting the method within the Build(context) it should solve it.


问:
jaas config contents reading to defaults [Kerberos]
I am trying to connect to Kerberized oracle server through a keytab in a spring boot application.
I have the keytab and krb5.conf under resources and the jaas conf string under application.yml like :

```<code>kerberos:
  jaasContent: "Client { \n  com.sun.security.auth.module.Krb5LoginModule required\n  useTicketCache=false\n  useKeyTab=true\n  keyTab=\"%s\"\n  doNotPrompt=true\n  principal=\"%s\";\n};"
</code>```

The end result of substituting with keytab and principal looks like this:

```<code>Client {
  com.sun.security.auth.module.Krb5LoginModule required
  useTicketCache=false
  useKeyTab=true
  keyTab="C:\Users\xxxxx\AppData\Local\Temp\krb5.keytab"
  doNotPrompt=true
  principal="XXXXXX@DOMAIN.AD.COMPANY.COM";
};
</code>```

I have verified that I can read the keytab contents from resources by printing file contents in logs (although it is encoded).

I am setting this jaas to:

```<code>System.setProperty("java.security.auth.login.config", jaasConf.toString());
</code>```

When I run the application, I get the following error:

```<code>Running sql : SELECT to_char(systimestamp, 'dd-mon-yyyy hh.mi.ss.ff4 AM') FROM DUAL
>>>KinitOptions cache name is C:\Users\n714804\krb5cc_N714804
>> Acquire default native Credentials
Java config name: C:\Users\xxxx\AppData\Local\Temp\krb5.conf
Loaded from Java config
default etypes for default_tkt_enctypes: 18 17.
>>> Found no TGT's in LSA
Failed to read from oracle: Failed to obtain JDBC Connection; nested exception is java.sql.SQLRecoverableException: IO Error: The service in process is not supported. Unable to obtain password from user

org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLRecoverableException: IO Error: The service in process is not supported. Unable to obtain password from user

    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:452)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:462)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:473)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:480)
    at com.jpmorgan.ct.GetOracleTime.getOracleTime(GetOracleTime.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.jpmorgan.moneta.boot.logging.RequestLoggingFilter.doFilter(RequestLoggingFilter.java:141)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.jpmorgan.moneta.boot.logging.PerfLoggingFilter.doFilter(PerfLoggingFilter.java:50)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.jpmorgan.moneta.boot.logging.MDCFilter.doFilter(MDCFilter.java:31)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:109)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.jpmorgan.moneta.boot.web.ExcludeFontVaryHeadersFilter.doFilterInternal(ExcludeFontVaryHeadersFilter.java:58)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLRecoverableException: IO Error: The service in process is not supported. Unable to obtain password from user

    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:774)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:688)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:39)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:691)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:155)
    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:146)
    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205)
    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169)
    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:158)
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:116)
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79)
    ... 73 more
Caused by: oracle.net.ns.NetException: The service in process is not supported. Unable to obtain password from user

    at oracle.net.ano.AuthenticationService.g(Unknown Source)
    at oracle.net.ano.AuthenticationService.e(Unknown Source)
    at oracle.net.ano.Ano.negotiation(Unknown Source)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:345)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1438)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:518)
    ... 85 more
Caused by: javax.security.auth.login.LoginException: Unable to obtain password from user

    at com.sun.security.auth.module.Krb5LoginModule.promptForPass(Krb5LoginModule.java:897)
    at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(Krb5LoginModule.java:760)
    at com.sun.security.auth.module.Krb5LoginModule.login(Krb5LoginModule.java:617)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javax.security.auth.login.LoginContext.invoke(LoginContext.java:755)
    at javax.security.auth.login.LoginContext.access$000(LoginContext.java:195)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:682)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:680)
    at javax.security.auth.login.LoginContext.login(LoginContext.java:587)
</code>```

But when I do a manual kinit and obtain a Credentials cache in in my C:\Users\xxxxx\krb5cc_xxxxx
the application works perfectly.

From what I understand the Krb5LoginModule required in jaas.conf will read the keytab and other properties to generate a cache/TGT with the keytab provided and I wouldn't have to do a kinit ?

I further debugged taking on to this understanding and found out that that jaas is not taken to effect and Krb5LoginModule called with some default settings.

```<code>Unable to obtain password from user at com.sun.security.auth.module.Krb5LoginModule.promptForPass(Krb5LoginModule.java:897)
</code>```

Krb5LoginModule.java:897 led me ktab == null and useKeytab = false, which contradict to what I have set in the jaas.conf

I would really appreciate if someone could help me understand if there is something wrong in my jaas.conf or in the approachh I am taking.

答: Have you checked out the JDBC developer's guide for reference? </p>

Body:
I am trying to connect to Kerberized oracle server through a keytab in a spring boot application.
I have the keytab and krb5.conf under resources and the jaas conf string under application.yml like :

kerberos:
  jaasContent: "Client { \n  com.sun.security.auth.module.Krb5LoginModule required\n  useTicketCache=false\n  useKeyTab=true\n  keyTab=\"%s\"\n  doNotPrompt=true\n  principal=\"%s\";\n};"

The end result of substituting with keytab and principal looks like this:

Client {
  com.sun.security.auth.module.Krb5LoginModule required
  useTicketCache=false
  useKeyTab=true
  keyTab="C:\Users\xxxxx\AppData\Local\Temp\krb5.keytab"
  doNotPrompt=true
  principal="XXXXXX@DOMAIN.AD.COMPANY.COM";
};

I have verified that I can read the keytab contents from resources by printing file contents in logs (although it is encoded).

I am setting this jaas to:

System.setProperty("java.security.auth.login.config", jaasConf.toString());

When I run the application, I get the following error:

Running sql : SELECT to_char(systimestamp, 'dd-mon-yyyy hh.mi.ss.ff4 AM') FROM DUAL
>>>KinitOptions cache name is C:\Users\n714804\krb5cc_N714804
>> Acquire default native Credentials
Java config name: C:\Users\xxxx\AppData\Local\Temp\krb5.conf
Loaded from Java config
default etypes for default_tkt_enctypes: 18 17.
>>> Found no TGT's in LSA
Failed to read from oracle: Failed to obtain JDBC Connection; nested exception is java.sql.SQLRecoverableException: IO Error: The service in process is not supported. Unable to obtain password from user

org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLRecoverableException: IO Error: The service in process is not supported. Unable to obtain password from user

    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:82)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:371)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:452)
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:462)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:473)
    at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:480)
    at com.jpmorgan.ct.GetOracleTime.getOracleTime(GetOracleTime.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.jpmorgan.moneta.boot.logging.RequestLoggingFilter.doFilter(RequestLoggingFilter.java:141)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.jpmorgan.moneta.boot.logging.PerfLoggingFilter.doFilter(PerfLoggingFilter.java:50)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.jpmorgan.moneta.boot.logging.MDCFilter.doFilter(MDCFilter.java:31)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:109)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at com.jpmorgan.moneta.boot.web.ExcludeFontVaryHeadersFilter.doFilterInternal(ExcludeFontVaryHeadersFilter.java:58)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1594)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLRecoverableException: IO Error: The service in process is not supported. Unable to obtain password from user

    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:774)
    at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:688)
    at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:39)
    at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:691)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:208)
    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:155)
    at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:146)
    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205)
    at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169)
    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:158)
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:116)
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79)
    ... 73 more
Caused by: oracle.net.ns.NetException: The service in process is not supported. Unable to obtain password from user

    at oracle.net.ano.AuthenticationService.g(Unknown Source)
    at oracle.net.ano.AuthenticationService.e(Unknown Source)
    at oracle.net.ano.Ano.negotiation(Unknown Source)
    at oracle.net.ns.NSProtocol.connect(NSProtocol.java:345)
    at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1438)
    at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:518)
    ... 85 more
Caused by: javax.security.auth.login.LoginException: Unable to obtain password from user

    at com.sun.security.auth.module.Krb5LoginModule.promptForPass(Krb5LoginModule.java:897)
    at com.sun.security.auth.module.Krb5LoginModule.attemptAuthentication(Krb5LoginModule.java:760)
    at com.sun.security.auth.module.Krb5LoginModule.login(Krb5LoginModule.java:617)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at javax.security.auth.login.LoginContext.invoke(LoginContext.java:755)
    at javax.security.auth.login.LoginContext.access$000(LoginContext.java:195)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:682)
    at javax.security.auth.login.LoginContext$4.run(LoginContext.java:680)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.login.LoginContext.invokePriv(LoginContext.java:680)
    at javax.security.auth.login.LoginContext.login(LoginContext.java:587)

But when I do a manual kinit and obtain a Credentials cache in in my C:\Users\xxxxx\krb5cc_xxxxx
the application works perfectly.

From what I understand the Krb5LoginModule required in jaas.conf will read the keytab and other properties to generate a cache/TGT with the keytab provided and I wouldn't have to do a kinit ?

I further debugged taking on to this understanding and found out that that jaas is not taken to effect and Krb5LoginModule called with some default settings.

Unable to obtain password from user at com.sun.security.auth.module.Krb5LoginModule.promptForPass(Krb5LoginModule.java:897)

Krb5LoginModule.java:897 led me ktab == null and useKeytab = false, which contradict to what I have set in the jaas.conf

I would really appreciate if someone could help me understand if there is something wrong in my jaas.conf or in the approachh I am taking.


问:
SQL database view all foreign keys
I am trying to view all foreign keys of my database and I have the following code to do that:

```<code>SELECT
  tc.TABLE_NAME,
  sc.COLUMN_NAME,
  CONSTRAINT_NAME,
  CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
inner join INFORMATION_SCHEMA.COLUMNS as sc
on sc.TABLE_NAME = tc.TABLE_NAME
order by tc.TABLE_NAME
</code>```

But it seems to give more results than it should be. It gives around 30.000 result and it should be no more than 2000. What I am doing wrong.
PS: I need this to return the table name, column name, column id and constraint type for further implementation in Laravel application.

答:
I think the best option here is to use EXEC sp_fkeys 'TableName'. Check this out for more details

check this question

Title: SQL database view all foreign keys

Body:
I am trying to view all foreign keys of my database and I have the following code to do that:

SELECT
  tc.TABLE_NAME,
  sc.COLUMN_NAME,
  CONSTRAINT_NAME,
  CONSTRAINT_TYPE
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc
inner join INFORMATION_SCHEMA.COLUMNS as sc
on sc.TABLE_NAME = tc.TABLE_NAME
order by tc.TABLE_NAME

But it seems to give more results than it should be. It gives around 30.000 result and it should be no more than 2000. What I am doing wrong.
PS: I need this to return the table name, column name, column id and constraint type for further implementation in Laravel application.


问:
How do I mask an email address between the first and the last character before the @ sign?
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe@abc.com then I should output j*****e@abc.com.

```<code>var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first[i] = '*';
        }
        ans = first +"@" +parts[1];
    }else{

    }
    return ans;
};
</code>```

However in my loop I can't change the characters to asterisks.

After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?

答:
You can use the bracket notation on a string (like an array) to get the character at a specific index, but you can't use this to change characters. So first[i] = '*' in your code wont do anything.

Strings in JavaScript are immutable. This means that if you want to change a string, a new string instance will be created. This also means that when you change a string in a for-loop, it can impact performance. (Although in this case the difference wont be noticeable.
)

I would use this code:

function maskPII(str) {
  const indexOfAt = str.indexOf('@');
  if (indexOfAt <= 2) {
    return str;
  }

  return str[0] + '*'.repeat(indexOfAt - 2) + str.substring(indexOfAt - 1);
}

const email = 'johndoe@abc.com';
console.log(email);
console.log(maskPII(email));```

It will look for the index of the @ sign. If the index is less or equal than 2, (when not found the index will be -1) it will return the original string.

Otherwise it will get the first character, calculate the amount of asterisks needed (index of the @ sign -2) and repeat those and then add the rest of the original string.

Body:
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe@abc.com then I should output j*****e@abc.com.

var maskPII = function(S) {
    var ans = "";
    if(S.includes("@")){
        S = S.toLowerCase();
        var parts = S.split("@");
        var first = parts[0];
        for(var i=0;i<parts[0].length;i++){
            if(i!=0 && i!=parts[0].length - 1)
                first[i] = '*';
        }
        ans = first +"@" +parts[1];
    }else{

    }
    return ans;
};

However in my loop I can't change the characters to asterisks.

After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?

Body:
You can use the bracket notation on a string (like an array) to get the character at a specific index, but you can't use this to change characters. So first[i] = '*' in your code wont do anything.

Strings in JavaScript are immutable. This means that if you want to change a string, a new string instance will be created. This also means that when you change a string in a for-loop, it can impact performance. (Although in this case the difference wont be noticeable.
)

I would use this code:

function maskPII(str) {
  const indexOfAt = str.indexOf('@');
  if (indexOfAt <= 2) {
    return str;
  }

  return str[0] + '*'.repeat(indexOfAt - 2) + str.substring(indexOfAt - 1);
}

const email = 'johndoe@abc.com';
console.log(email);
console.log(maskPII(email));

It will look for the index of the @ sign. If the index is less or equal than 2, (when not found the index will be -1) it will return the original string.

Otherwise it will get the first character, calculate the amount of asterisks needed (index of the @ sign -2) and repeat those and then add the rest of the original string.


问:
reactjs how to filter / check if a any object in an array is present in another array of objects?
im facing the issue when trying to implement some conditional rendering. Here is the context:

the data:

```<code>groups_a : [
             {id:1} ,
             {id:2}
            ]

groups_b : [
             {id:1} ,
             {id:3}
            ]
</code>```

The condition:

I wish to be check each item in groups_b , whether they exist in groups_a . So in this case , the condition should return back true because groups_b has id:1 and so does groups_a

JSX :

```<code>            {###the condition ##
                         ?
            <Button>Approve</Button>
            :
            null
            }
</code>```

答:
it's an other solution that you can get the common list also.

const groupA = [{id:1}, {id:3}, {id:4}];
const groupB = [{id:1}, {id:2}];

const ListCommon = groupA.filter(x => groupB.find(y => x.id === y.id));

console.log('result:', ListCommon.length>0)
console.log('List:', ListCommon)```

Body:
im facing the issue when trying to implement some conditional rendering. Here is the context:

the data:

groups_a : [
             {id:1} ,
             {id:2}
            ]

groups_b : [
             {id:1} ,
             {id:3}
            ]

The condition:

I wish to be check each item in groups_b , whether they exist in groups_a . So in this case , the condition should return back true because groups_b has id:1 and so does groups_a

JSX :

            {###the condition ##
                         ?
            <Button>Approve</Button>
            :
            null
            }


Title: Minimization problem with linking constraints in R

Body:
How should I incorporate the linking constraints into the optimization problem formulation in equations 1 - 4 where Y_i's are binary variables?

minimize
    22X11 + 20.5X12 + 21X13 + 19X14 + 21X21 + 21X22 + 18X23 + 17X24 +
    22X31 + 24X32 + 22X33 + 23X34 + 22X41 + 16X42 + 17X43 + 17.5X44 +
    1500 Y1 + 1700 Y2 + 1500 Y3 + 1400 Y4

subject to constraints

    2.00 X11 + 1.80 X21 + 2.30 X31 + 2.10 X41 >= 750
    2.80 X12 + 2.30 X22 + 2.20 X32 + 2.60 X42 >= 800
    1.70 X13 + 1.75 X23 + 1.60 X33 + 1.90 X43 >= 1000
    2.40 X14 + 1.90 X24 + 2.60 X34 + 2.40 X44 >= 300

    X11 - 1500 Y1 <= 0
    X21 - 2000 Y2 <= 0
    X31 - 1500 Y3 <= 0
    X41 - 1800 Y4 <= 0
    X12 - 500 Y1 >= 0
    X22 - 500 Y2 >= 0
    X32 - 500 Y3 >= 0
    X42 - 500 Y4 >= 0

    Y1 = 1 if X11>0 and 0 otherwise
    Y1 = 1 if X12>0 and 0 otherwise
    Y2 = 1 if X21>0 and 0 otherwise
    Y2 = 1 if X22>0 and 0 otherwise
    Y3 = 1 if X31>0 and 0 otherwise
    Y3 = 1 if X32>0 and 0 otherwise
    Y4 = 1 if X41>0 and 0 otherwise
    Y4 = 1 if X42>0 and 0 otherwise

R code to find optimal solutions without those linking variables:

library(lpSolve)
f.obj <-  c(22,20.5,21,19,21,21,18,17,22,24,22,23,22,16,17,17.5,1500,1700,1500,1400)

const1 = c(2.00,1.80,2.30,2.10)
const2 = c(2.80,2.30,2.20,2.60)
const3 = c(1.70,1.75,1.60,1.90)
const4 = c(2.40,1.90,2.60,2.40)

f.con <- rbind(const1,const2,const3,const4)
f.dir <- c(rep(">=",2), ">=", ">=")
f.rhs <- c(750,800,1000,300)
res <- lp("min", f.obj, f.con,f.dir,f.rhs, binary.vec=c(1,2))

res$solution
res$objective
res$objval

Body:
Here is an option.

Convert X_ij's into small numbers. I just use one magnitude larger than the values seen here.

library(lpSolve)
n <- 20
denom <- 10e3
f.obj <- c(c(22,20.5,21,19,
    21,21,18,17,
    22,24,22,23,
    22,16,17,17.5) / denom,
    1500,1700,1500,1400)

#identify location of variables for easy identification
vars <- c(paste0("X", c(outer(1:4, 1:4, paste0))), paste0("Y", 1:4))
vars <- setNames(seq_along(vars), vars)

#X11 X21 X31 X41 X12 X22 X32 X42 X13 X23 X33 X43 X14 X24 X34 X44  Y1  Y2  Y3  Y4
#  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20

Constraints as per OP while shrinking coefficients appropriately:

const01 <- replace(rep(0, n), 1:4, c(2.00,1.80,2.30,2.10))
const02 <- replace(rep(0, n), 5:8, c(2.80,2.30,2.20,2.60))
const03 <- replace(rep(0, n), 9:12, c(1.70,1.75,1.60,1.90))
const04 <- replace(rep(0, n), 13:16, c(2.40,1.90,2.60,2.40))

#X11, X12, Y1
const05 <- replace(rep(0, n), c(1,17), c(-1, 1500 / denom))
const06 <- replace(rep(0, n), c(5,17), c(1, -500 / denom))

#X21, X22, Y2
const07 <- replace(rep(0, n), c(2,18), c(-1, 2000 / denom))
const08 <- replace(rep(0, n), c(6,18), c(1, -500 / denom))

#X31, X32, Y3
const09 <- replace(rep(0, n), c(3,19), c(-1, 1500 / denom))
const10 <- replace(rep(0, n), c(7,19), c(1, -500 / denom))

#X41, X42, Y4
const11 <- replace(rep(0, n), c(4,20), c(-1, 1800 / denom))
const12 <- replace(rep(0, n), c(8,20), c(1, -500 / denom))

For linking variables, use X <= Y so that when X is non-zero, Y must be 1.

#X11, X12, Y1
const11 <- replace(rep(0, n), c(1,17), c(-1, 1))
const12 <- replace(rep(0, n), c(5,17), c(-1, 1))

#X21, X22, Y2
const13 <- replace(rep(0, n), c(2,18), c(-1, 1))
const14 <- replace(rep(0, n), c(6,18), c(-1, 1))

#X31, X32, Y3
const15 <- replace(rep(0, n), c(3,19), c(-1, 1))
const16 <- replace(rep(0, n), c(7,19), c(-1, 1))

#X41, X42, Y4
const17 <- replace(rep(0, n), c(4,20), c(-1, 1))
const18 <- replace(rep(0, n), c(8,20), c(-1, 1))

Calling the solver while shrinking RHS appropriately:

f.con <- do.call(rbind, mget(ls(pattern="^const")))
f.dir <- rep(">=", nrow(f.con))
f.rhs <- c(c(750,800,1000,300) / denom, rep(0, nrow(f.con) - 4))
res <- lp("min", f.obj, f.con, f.dir, f.rhs, binary.vec=17:20)

res$solution
# [1] 0.00000000 0.00000000 0.00000000 0.03571429 0.00000000 0.00000000 0.00000000 0.03076923
# [9] 0.00000000 0.00000000 0.00000000 0.05263158 0.00000000 0.00000000 0.01153846 0.00000000
#[17] 0.00000000 0.00000000 0.00000000 1.00000000

Reversing the shrinking:

(optval <- setNames(replace(res$solution, 1:16, denom * res$solution[1:16]), names(vars)))

And the optimal values:

     X11      X21      X31      X41      X12      X22      X32      X42      X13      X23
  0.0000   0.0000   0.0000 357.1429   0.0000   0.0000   0.0000 307.6923   0.0000   0.0000
     X33      X43      X14      X24      X34      X44       Y1       Y2       Y3       Y4
  0.0000 526.3158   0.0000   0.0000 115.3846   0.0000   0.0000   0.0000   0.0000   1.0000

Obj value:

sum(optval * replace(f.obj, 1:16, denom * f.obj[1:16]))
#[1] 27483.29


问:
How to make a toggleable mat-sidenav push also a fixed header in the mat-sidenav-content
I'm using the mat-sidenav-container to create the desktop version of my page, but I want to make the mat-sidenav toggleable , which I've already managed to do.
The problem now is that I have a fixed header on the mat-sidenav-content, and that part is not being pushed when the mat-sidenav is displayed.

For the  mat-sidenav-content I'm using the css grid to divide this section into two parts (the fixed header and the main content)

Here's a stackblitz demo.

Do you have any idea how I can make the mat-sidenav push also the fixed header?

Thanks.

答:
You have to remove these styles from .content__header:

```<code>height: 12rem;
position: fixed;
left: 0;
</code>```

and add position: sticky to it. Because of the position: fixed, the block could not be pushed to the side by the sidebar and because of the fixed height, it overflowed when the position: fixed was removed. The height was especially not needed, as you already specified it in your .content class with this: grid-template-rows: 12rem auto;. Changing it to position: sticky makes the header still be there on scroll, but also be pushed to the side. Important is that top: 0 is still there.

The .content__header class should now look like this:

```<code>.content__header {
  background-color: #eee;
  width: 100%;
  position: sticky;
  top: 0;
  padding: 0.5rem 1rem;
  z-index: 3;
}
</code>```

Body:
You have to remove these styles from .content__header:

height: 12rem;
position: fixed;
left: 0;

and add position: sticky to it. Because of the position: fixed, the block could not be pushed to the side by the sidebar and because of the fixed height, it overflowed when the position: fixed was removed. The height was especially not needed, as you already specified it in your .content class with this: grid-template-rows: 12rem auto;. Changing it to position: sticky makes the header still be there on scroll, but also be pushed to the side. Important is that top: 0 is still there.

The .content__header class should now look like this:

.content__header {
  background-color: #eee;
  width: 100%;
  position: sticky;
  top: 0;
  padding: 0.5rem 1rem;
  z-index: 3;
}


问:
How to force users to update app from play store in Flutter using in_app_update
I want the users of my app to always have the latest version. If they don't have the latest version, it should download the latest version from play store first as shown in the image.

I found a package called Upgrader but this just gives a prompt. It is not linked to play store as shown in image.

Edit

As suggested by Maadhav Sharma, now I am using the in_app_update package but it says no update available.

This is my code:

....

class _TnPState extends State<TnP> {
  ThemeBloc _themeBloc;
  FirebaseMessaging _firebaseMessaging;
  NotificationBloc _notificationBloc;
  String _test;

  @override
  void initState() {
    _themeBloc = ThemeBloc();
    _firebaseMessaging = FirebaseMessaging();
    _notificationBloc = NotificationBloc();
    _firebaseMessaging.configure(
      onMessage: (notification) async => _notificationBloc.yes(),
      onResume: (notification) async => _notificationBloc.yes(),
      onLaunch: (notification) async => _notificationBloc.yes(),
    );
    checkForUpdate();
    super.initState();
  }

  Future<void> checkForUpdate() async {
    InAppUpdate.checkForUpdate().then((info) {
      String display = info.toString();
      setState((){
        _test = display;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<AppTheme>(
      stream: _themeBloc.themeStream,
      initialData: AppTheme.Light,
      builder: (context, AsyncSnapshot<AppTheme> snapshot) {
        return MaterialApp(
          title: 'TnP',
          debugShowCheckedModeBanner: false,
          theme: appThemeData[snapshot.data],
          home: _test==null ?
                Container() :
                InAppUpdateScreen(display: _test),//SplashScreen(),
        );
      },
    );
  }
}

```

InAppUpdateScreen just displays the text.

App in play store shows update is available:

But the app which is an older version installed via playstore shows no update:

Any idea how to solve this?

答:
There is a package for what you want:

 https://pub.dev/packages/in_app_update

Android

This plugin integrates the official Android APIs to perform in app updated that were released in 2019: https://developer.android.com/guide/app-bundle/in-app-updates

iOS

iOS does not offer such a functionality. You might want to look into e.g. https://pub.dev/packages/upgrader. If you call the methods above on a iOS device you'll run into a not-implemented exception.

Thanks...

Body:
I want the users of my app to always have the latest version. If they don't have the latest version, it should download the latest version from play store first as shown in the image.

I found a package called Upgrader but this just gives a prompt. It is not linked to play store as shown in image.

Edit

As suggested by Maadhav Sharma, now I am using the in_app_update package but it says no update available.

This is my code:

....

class _TnPState extends State<TnP> {
  ThemeBloc _themeBloc;
  FirebaseMessaging _firebaseMessaging;
  NotificationBloc _notificationBloc;
  String _test;

  @override
  void initState() {
    _themeBloc = ThemeBloc();
    _firebaseMessaging = FirebaseMessaging();
    _notificationBloc = NotificationBloc();
    _firebaseMessaging.configure(
      onMessage: (notification) async => _notificationBloc.yes(),
      onResume: (notification) async => _notificationBloc.yes(),
      onLaunch: (notification) async => _notificationBloc.yes(),
    );
    checkForUpdate();
    super.initState();
  }

  Future<void> checkForUpdate() async {
    InAppUpdate.checkForUpdate().then((info) {
      String display = info.toString();
      setState((){
        _test = display;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<AppTheme>(
      stream: _themeBloc.themeStream,
      initialData: AppTheme.Light,
      builder: (context, AsyncSnapshot<AppTheme> snapshot) {
        return MaterialApp(
          title: 'TnP',
          debugShowCheckedModeBanner: false,
          theme: appThemeData[snapshot.data],
          home: _test==null ?
                Container() :
                InAppUpdateScreen(display: _test),//SplashScreen(),
        );
      },
    );
  }
}

InAppUpdateScreen just displays the text.

App in play store shows update is available:

But the app which is an older version installed via playstore shows no update:

Any idea how to solve this?


问:
How can I put the names of dataframes that are stored in a list into the column names of each dataframe?
Objective: add the dataframe names as prefixes to some columns for a long list of dataframes

Problem: Using lapply or loops it seems like R doesn't pass the name of the dataframes to the method.

Data:

```<code>A<-data.frame(column_1=c(1,2,3),column_2=c(4,5,6),column_3=c(7,8,9),column_4=c(10,11,12))
B<-data.frame(column_1=c(13,14,15),column_2=c(16,17,18),column_3=c(19,20,21),column_4=c(22,23,24))
C<-data.frame(column_1=c(25,26,27),column_2=c(28,29,30),column_3=c(31,32,33),column_4=c(34,35,36))
list_of_dataframes<-list(A,B,C)
names(list_of_dataframes)<-c("A","B","C")
</code>```

This is just an example. Actually my list of dataframes is quite long. So, it comes unhandy to add names manually with 'comment' like it is done here.

Desired Solution:

```<code>$A
  A_column_1 A_column_2 A_column_3 column_4
1          1          4          7       10
2          2          5          8       11
3          3          6          9       12

$B
  B_column_1 B_column_2 B_column_3 column_4
1         13         16         19       22
2         14         17         20       23
3         15         18         21       24

$C
  C_column_1 C_column_2 C_column_3 column_4
1         25         28         31       34
2         26         29         32       35
3         27         30         33       36
</code>```

As you can see the dataframe names are in the column names, except for column 4 which I want to exclude from this operation.

My Try:

The desired solution was actually produced by some code:

```<code>comment(list_of_dataframes$A) <- "A"
comment(list_of_dataframes$B) <- "B"
comment(list_of_dataframes$C) <- "C"

list_of_dataframes<-lapply(list_of_dataframes,function(dataframe){

  a<-comment(dataframe)

  colnames(dataframe)[c(1,2,3)]<-paste(a, colnames(dataframe)[c(1,2,3)], sep = "_")

  return(dataframe)

}
)

list_of_dataframes
</code>```

The problem with this solution is that I actually have a very long list of dataframes and I have many of such lists. So, I need to do all of this in an automated fashion.
In the above code I use 'comment' where I separately type in the name of each dataframe. I need instead to automatically take the name of each dataframe. How can I do this?

I tried to use deparse(substitute(dataframe)) as here:

```<code>list_of_dataframes<-lapply(list_of_dataframes,function(dataframe){

  a<-deparse(substitute(dataframe))

  colnames(dataframe)<-paste(a, colnames(dataframe), sep = "_")

  return(dataframe)

}
)
</code>```

But, as you can see the names of the dataframe don't seem to be passed to lapply:

```<code>$A
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1               1               4               7              10
2               2               5               8              11
3               3               6               9              12

$B
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1              13              16              19              22
2              14              17              20              23
3              15              18              21              24

$C
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1              25              28              31              34
2              26              29              32              35
3              27              30              33              36
</code>```

Do you have any ideas how I can overcome this problem?

答:
In base R, you can do :

```<code>Map(function(x, y) {names(x)[1:3] = paste(y, names(x)[1:3], sep = "_");x},
                   list_of_dataframes, names(list_of_dataframes))
</code>```

Or using imap from purrr

```<code>library(dplyr)
purrr::imap(list_of_dataframes,
             ~.x %>% rename_at(1:3, function(x) paste(.y, x, sep = "_")))

#$A
#  A_column_1 A_column_2 A_column_3 column_4
#1          1          4          7       10
#2          2          5          8       11
#3          3          6          9       12

#$B
#  B_column_1 B_column_2 B_column_3 column_4
#1         13         16         19       22
#2         14         17         20       23
#3         15         18         21       24

#$C
#  C_column_1 C_column_2 C_column_3 column_4
#1         25         28         31       34
#2         26         29         32       35
#3         27         30         33       36
</code>```

Body:
Objective: add the dataframe names as prefixes to some columns for a long list of dataframes

Problem: Using lapply or loops it seems like R doesn't pass the name of the dataframes to the method.

Data:

A<-data.frame(column_1=c(1,2,3),column_2=c(4,5,6),column_3=c(7,8,9),column_4=c(10,11,12))
B<-data.frame(column_1=c(13,14,15),column_2=c(16,17,18),column_3=c(19,20,21),column_4=c(22,23,24))
C<-data.frame(column_1=c(25,26,27),column_2=c(28,29,30),column_3=c(31,32,33),column_4=c(34,35,36))
list_of_dataframes<-list(A,B,C)
names(list_of_dataframes)<-c("A","B","C")

This is just an example. Actually my list of dataframes is quite long. So, it comes unhandy to add names manually with 'comment' like it is done here.

Desired Solution:

$A
  A_column_1 A_column_2 A_column_3 column_4
1          1          4          7       10
2          2          5          8       11
3          3          6          9       12

$B
  B_column_1 B_column_2 B_column_3 column_4
1         13         16         19       22
2         14         17         20       23
3         15         18         21       24

$C
  C_column_1 C_column_2 C_column_3 column_4
1         25         28         31       34
2         26         29         32       35
3         27         30         33       36

As you can see the dataframe names are in the column names, except for column 4 which I want to exclude from this operation.

My Try:

The desired solution was actually produced by some code:

comment(list_of_dataframes$A) <- "A"
comment(list_of_dataframes$B) <- "B"
comment(list_of_dataframes$C) <- "C"

list_of_dataframes<-lapply(list_of_dataframes,function(dataframe){

  a<-comment(dataframe)

  colnames(dataframe)[c(1,2,3)]<-paste(a, colnames(dataframe)[c(1,2,3)], sep = "_")

  return(dataframe)

}
)

list_of_dataframes

The problem with this solution is that I actually have a very long list of dataframes and I have many of such lists. So, I need to do all of this in an automated fashion.
In the above code I use 'comment' where I separately type in the name of each dataframe. I need instead to automatically take the name of each dataframe. How can I do this?

I tried to use deparse(substitute(dataframe)) as here:

list_of_dataframes<-lapply(list_of_dataframes,function(dataframe){

  a<-deparse(substitute(dataframe))

  colnames(dataframe)<-paste(a, colnames(dataframe), sep = "_")

  return(dataframe)

}
)

But, as you can see the names of the dataframe don't seem to be passed to lapply:

$A
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1               1               4               7              10
2               2               5               8              11
3               3               6               9              12

$B
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1              13              16              19              22
2              14              17              20              23
3              15              18              21              24

$C
  X[[i]]_column_1 X[[i]]_column_2 X[[i]]_column_3 X[[i]]_column_4
1              25              28              31              34
2              26              29              32              35
3              27              30              33              36

Do you have any ideas how I can overcome this problem?

Body:
In base R, you can do :

Map(function(x, y) {names(x)[1:3] = paste(y, names(x)[1:3], sep = "_");x},
                   list_of_dataframes, names(list_of_dataframes))

Or using imap from purrr

library(dplyr)
purrr::imap(list_of_dataframes,
             ~.x %>% rename_at(1:3, function(x) paste(.y, x, sep = "_")))

#$A
#  A_column_1 A_column_2 A_column_3 column_4
#1          1          4          7       10
#2          2          5          8       11
#3          3          6          9       12

#$B
#  B_column_1 B_column_2 B_column_3 column_4
#1         13         16         19       22
#2         14         17         20       23
#3         15         18         21       24

#$C
#  C_column_1 C_column_2 C_column_3 column_4
#1         25         28         31       34
#2         26         29         32       35
#3         27         30         33       36