问:
API Facebook graph API15 - get multiple pages access token and to grant them with curl
My problem

I coded in Python a routine to retrieve all the statistics of Facebook pages and posts of my employer.

```<code>Authorisations:

    read_insights
    pages_show_list
    pages_read_engagement
    pages_read_user_content
</code>```

However, there are 74 of them (it's a short list of around 450 pages in two Facebook business accounts...) and copying and pasting the tokens one by one, twice to grant them like long-term-token via the Graph API interface, even every two months, is tedious...

I already have some FB application here : https://developers.facebook.com/apps

Either it's impossible or it's something that isn't explained in the Facebook doc.

I'd try

I tried to generate tokens with curl/postman, but I'm stuck.

There is informations on the internet, but with old versions of the API, information with insinuations from connoisseurs, references to overly general docs, ...  or which require going through the graphical interface.

on curl/postman:

https://graph.facebook.com/oauth/access_token?client_id={app_id}&client_secret={app_secret}&grant_type=client_credentials

https://graph.facebook.com/{my-page-id}/feed?access_token={app_id}|{access-token}

return :

```<code>{
    "error": {
        "message": "(#10) This endpoint requires the 'pages_read_user_content' permission or the 'Page Public Content Access' feature. Refer to https://developers.facebook.com/docs/apps/review/login-permissions#manage-pages and https://developers.facebook.com/docs/apps/review/feature#reference-PAGES_ACCESS for details.",
        "type": "OAuthException",
        "code": 10,
        "fbtrace_id": "AVEX_qDiDBq7zyVZ6ASC6cC"
    }
}
</code>```

There are too many places where I face unknowns and I need the help of the team ;-)

The user configuration on business manager ? I need to pass through a system user ?

Another grant_type for the token ? https://graph.facebook.com/oauth/access_token?client_id={app-id}&client_secret={secret-app}&grant_type=client_credentials

To grant_type the app token ? How to use "scope" ?

I get confused in the user, app and access pages??

I expect...

I'm expecting a sequence of curl requests (or urlrequest for Python code) to retrieve tokens from my FB pages and messages with the distinction between user and application tokens, and pages access. (to avoid confusion).

Thanks in advance !

Body:
My problem

I coded in Python a routine to retrieve all the statistics of Facebook pages and posts of my employer.

Authorisations:

    read_insights
    pages_show_list
    pages_read_engagement
    pages_read_user_content

However, there are 74 of them (it's a short list of around 450 pages in two Facebook business accounts...) and copying and pasting the tokens one by one, twice to grant them like long-term-token via the Graph API interface, even every two months, is tedious...

I already have some FB application here : https://developers.facebook.com/apps

Either it's impossible or it's something that isn't explained in the Facebook doc.

I'd try

I tried to generate tokens with curl/postman, but I'm stuck.

There is informations on the internet, but with old versions of the API, information with insinuations from connoisseurs, references to overly general docs, ...  or which require going through the graphical interface.

on curl/postman:

https://graph.facebook.com/oauth/access_token?client_id={app_id}&client_secret={app_secret}&grant_type=client_credentials

https://graph.facebook.com/{my-page-id}/feed?access_token={app_id}|{access-token}

return :

{
    "error": {
        "message": "(#10) This endpoint requires the 'pages_read_user_content' permission or the 'Page Public Content Access' feature. Refer to https://developers.facebook.com/docs/apps/review/login-permissions#manage-pages and https://developers.facebook.com/docs/apps/review/feature#reference-PAGES_ACCESS for details.",
        "type": "OAuthException",
        "code": 10,
        "fbtrace_id": "AVEX_qDiDBq7zyVZ6ASC6cC"
    }
}

There are too many places where I face unknowns and I need the help of the team ;-)

The user configuration on business manager ? I need to pass through a system user ?

Another grant_type for the token ? https://graph.facebook.com/oauth/access_token?client_id={app-id}&client_secret={secret-app}&grant_type=client_credentials

To grant_type the app token ? How to use "scope" ?

I get confused in the user, app and access pages??

I expect...

I'm expecting a sequence of curl requests (or urlrequest for Python code) to retrieve tokens from my FB pages and messages with the distinction between user and application tokens, and pages access. (to avoid confusion).

Thanks in advance !


来源: stackexchange

问:
Python code not loading php file gives "UnicodeDecodeError: 'utf-8' codec can't decode byte". Trying to load Laravel 8 folder
Hello i have coded this program to make class diagram in python but when I am trying to load my Laravel directory and look into php files to generate their class diagram but getting this error even i have put utf-8. Any help will be appreciated.

Code:

```<code>import os
import re
import tempfile
import webbrowser

# Define the path to the Laravel project
project_path = 'C:/xampp/htdocs/Laravel-8-project'

# Find all the PHP class files in the project
def find_class_files(dir):
    results = []
    for file in os.listdir(dir):
        file_path = os.path.join(dir, file)
        if os.path.isdir(file_path):
            results.extend(find_class_files(file_path))
        elif os.path.splitext(file)[1] == '.php':
            results.append(file_path)
    return results

# Parse the class names and dependencies from the class files
def parse_classes(class_files):
    classes = []
    for file in class_files:
        with open(file, 'r', encoding='utf-8') as f:
            contents = f.read()
        class_name = get_class_name(contents)
        if class_name:
            dependencies = get_dependencies(contents)
            classes.append({
                'name': class_name,
                'dependencies': dependencies,
            })
    return classes

# Extract the class name from a PHP class file

# Extract the dependencies from a PHP class file

# Generate an HTML class diagram from a list of classes

# Display an HTML class diagram in the browser

# Find all the PHP class files in the Laravel project
class_files = find_class_files(project_path)

# Parse the class names and dependencies from the class files
classes = parse_classes(class_files)

# Generate the HTML for the class diagram
html = generate_class_diagram(classes)

# Display the class diagram in the browser
display_class_diagram(html)
</code>```

I am getting this error message i dont know whats happening here.

```<code>Traceback (most recent call last):
  File "C:\Users\inaqi\Desktop\cd.py", line 77, in <module>
    classes = parse_classes(class_files)
  File "C:\Users\inaqi\Desktop\cd.py", line 25, in parse_classes
    contents = f.read()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self. Errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 105: invalid continuation byte
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hello i have coded this program to make class diagram in python but when I am trying to load my Laravel directory and look into php files to generate their class diagram but getting this error even i have put utf-8. Any help will be appreciated.

Code:

import os
import re
import tempfile
import webbrowser

# Define the path to the Laravel project
project_path = 'C:/xampp/htdocs/Laravel-8-project'

# Find all the PHP class files in the project
def find_class_files(dir):
    results = []
    for file in os.listdir(dir):
        file_path = os.path.join(dir, file)
        if os.path.isdir(file_path):
            results.extend(find_class_files(file_path))
        elif os.path.splitext(file)[1] == '.php':
            results.append(file_path)
    return results

# Parse the class names and dependencies from the class files
def parse_classes(class_files):
    classes = []
    for file in class_files:
        with open(file, 'r', encoding='utf-8') as f:
            contents = f.read()
        class_name = get_class_name(contents)
        if class_name:
            dependencies = get_dependencies(contents)
            classes.append({
                'name': class_name,
                'dependencies': dependencies,
            })
    return classes

# Extract the class name from a PHP class file

# Extract the dependencies from a PHP class file

# Generate an HTML class diagram from a list of classes

# Display an HTML class diagram in the browser

# Find all the PHP class files in the Laravel project
class_files = find_class_files(project_path)

# Parse the class names and dependencies from the class files
classes = parse_classes(class_files)

# Generate the HTML for the class diagram
html = generate_class_diagram(classes)

# Display the class diagram in the browser
display_class_diagram(html)

I am getting this error message i dont know whats happening here.

Traceback (most recent call last):
  File "C:\Users\inaqi\Desktop\cd.py", line 77, in <module>
    classes = parse_classes(class_files)
  File "C:\Users\inaqi\Desktop\cd.py", line 25, in parse_classes
    contents = f.read()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self. Errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 105: invalid continuation byte


问:
Trying to set values with HTML tags in radio input tags
In React, I have an array of objects and I wish to use superscript on a particular index. I want set the value to a state variable but it seems the state can not detect the value because it sees a HTML tag and not a string. How can I solve this?
questions:
{
question:
A right triangle has sides that are consecutive even integers. The longest
side is z. Which of the following equations could be used to find z?
,
options: [(z-4) 2 = z 2 - (z-2) 2,
(z-2) 2 = z 2 - (z-4),
z 2 = z 2 - z-4 2,
z 2 = (z-1) 2 + (z-2) 2 ],
answer: (z-4) 2 = z 2 - (z-2) 2
}
React component:

```<code><div id="inputs">
       <div><input type="radio" name="options" value={answerList[0]} onChange={changeValue}
       checked={radioValue == answerList[0]}/><label>{answerList[0]}</label></div>
       <div><input type="radio" name="options" value={answerList[1]} onChange={changeValue}
       checked={radioValue == answerList[1]}/><label>{answerList[1]}</label></div>
       <div><input type="radio" name="options" value={answerList[2]} onChange={changeValue}
       checked={radioValue == answerList[2]}/><label>{answerList[2]}</label></div>
       <div><input type="radio" name="options" value={answerList[3]} onChange={changeValue}
       checked={radioValue == answerList[3]}/><label>{answerList[3]}</label></div>
       </div>
</code>```

Body:
In React, I have an array of objects and I wish to use superscript on a particular index. I want set the value to a state variable but it seems the state can not detect the value because it sees a HTML tag and not a string. How can I solve this?
questions:
{
question:
A right triangle has sides that are consecutive even integers. The longest
side is z. Which of the following equations could be used to find z?
,
options: [(z-4) 2 = z 2 - (z-2) 2,
(z-2) 2 = z 2 - (z-4),
z 2 = z 2 - z-4 2,
z 2 = (z-1) 2 + (z-2) 2 ],
answer: (z-4) 2 = z 2 - (z-2) 2
}
React component:

<input type="radio" name="options" value={answerList[0]} onChange={changeValue}
       checked={radioValue == answerList[0]}/>{answerList[0]}

<input type="radio" name="options" value={answerList[1]} onChange={changeValue}
       checked={radioValue == answerList[1]}/>{answerList[1]}

<input type="radio" name="options" value={answerList[2]} onChange={changeValue}
       checked={radioValue == answerList[2]}/>{answerList[2]}

<input type="radio" name="options" value={answerList[3]} onChange={changeValue}
       checked={radioValue == answerList[3]}/>{answerList[3]}


问:
Why empty list AND a boolean literal yields an empty list, but empty list OR a boolean literal a bool?
The title pretty much summarizes it all.

Why, in Python, performing a logical and with an empty list and a boolean literal (like True or False) returns an empty list, but performing a logical or returns a boolean value?

Directly in Python here is what I did, but have not understood it:

```<code>$ python
Python 3.10.6 (main, Aug 24 2022, 14:30:54) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> empty_list = []
>>> empty_list
[]
>>> empty_list and True
[]
>>> empty_list and False
[]
>>> empty_list or True
True
>>> empty_list or False
False
</code>```

I know I can use a cast bool(empty_list) and then I'd only have boolean as a return, but my question is whats is so different in using an and or or that the return different types are different? Aren't they both logical operators?

Body:
The title pretty much summarizes it all.

Why, in Python, performing a logical and with an empty list and a boolean literal (like True or False) returns an empty list, but performing a logical or returns a boolean value?

Directly in Python here is what I did, but have not understood it:

$ python
Python 3.10.6 (main, Aug 24 2022, 14:30:54) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> empty_list = []
>>> empty_list
[]
>>> empty_list and True
[]
>>> empty_list and False
[]
>>> empty_list or True
True
>>> empty_list or False
False

I know I can use a cast bool(empty_list) and then I'd only have boolean as a return, but my question is whats is so different in using an and or or that the return different types are different? Aren't they both logical operators?


问:
Avalara Integration with InkSoft
I am looking to integrate Avalara with existing InkSoft platform. Looking for some useful links and help to achieve above.

Avalara integration is not available OOTB but the APIs are available to integrate.

What is the right approach for this? Are there any solutions available in the market?

Title: Avalara Integration with InkSoft


问:
Java 8 JNI error: class file version problem
I have a Java-8 application (including javafx) which I wrote a few years ago.
It runs well under:

```<code>`   java version "1.8.0_291"
    Java(TM) SE Runtime Environment (build 1.8.0_291-b10)
    Java HotSpot(TM) 64-Bit Server VM (build 25.291-b10, mixed mode)
`
B
</code>```

ut on a different computer under:

```<code>    openjdk version "1.8.0_352"
    OpenJDK Runtime Environment (Temurin)(build 1.8.0_352-b08)
    OpenJDK 64-Bit Server VM (Temurin)(build 25.352-b08, mixed mode)
</code>```

I get a JNI error:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: javafx/application/Application has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

```<code>`   at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:473)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:473)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)
`
</code>```

The PATH looks OK:
/usr/lib/jvm/jdk8u352-b08/bin:/bin:/opt/gradle/gradle-7.5.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

java and javac versions are identical: 1.8.0_352

I have explored any problem, I can think off, and have come out empty.
Is it Oracle vs Openjdk?`

Body:
I have a Java-8 application (including javafx) which I wrote a few years ago.
It runs well under:

`   java version "1.8.0_291"
    Java(TM) SE Runtime Environment (build 1.8.0_291-b10)
    Java HotSpot(TM) 64-Bit Server VM (build 25.291-b10, mixed mode)
`
B

ut on a different computer under:

    openjdk version "1.8.0_352"
    OpenJDK Runtime Environment (Temurin)(build 1.8.0_352-b08)
    OpenJDK 64-Bit Server VM (Temurin)(build 25.352-b08, mixed mode)

I get a JNI error:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: javafx/application/Application has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

`   at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:473)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:756)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:473)
    at java.net.URLClassLoader.access$100(URLClassLoader.java:74)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:369)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:363)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:362)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
    at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)
`

The PATH looks OK:
/usr/lib/jvm/jdk8u352-b08/bin:/bin:/opt/gradle/gradle-7.5.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

java and javac versions are identical: 1.8.0_352

I have explored any problem, I can think off, and have come out empty.
Is it Oracle vs Openjdk?`


问:
make a Nyquist Plot using Magnitude and Phase with Python
Right now I have the data of Magnitude and Phase and I want to make a Nyquist Plot. I have searched in Internet how to convert this 2 Data to transfer function but unfortunately most of the website shows the way to calculate the Magnitude and Phase from Transfer function. So it makes me confuse to plot a Nyquist graph with python.

So is there any solution for drawing Nyquist plot with the data of Magnitude and Phase using Python?


问:
How to print deepface analysis recursively into a pandas dataframe and subsequently into a csv?
`   from deepface import DeepFace
import pandas as pd
import os, os.path
from os import path

```<code>test = '(path to jpg images)'
csv_records = '(path to save csv records)'
df = pd.DataFrame()
for file in os.listdir(test):
    if file.endswith('.jpg'):
        thisframe = 0
        filename = str(os.path.join(test, str(thisframe) + '.jpg'))
        predictions = DeepFace.analyze(filename, actions = ['emotion'])
        df2 = pd.DataFrame(predictions)
        df3 = df.append(df2)
        df3.to_csv(os.path.join(csv_records, 'record.csv'))
        thisframe += 1`
</code>```

I'm making an emotion recognition program and the images are obtained from a program which exports frames in jpg format from real-time footage. I want to pass those images into the deepface.analyze program and then combine the 'emotion' part of the analysis for all of the frames into a dataframe and subsequently export the results into a csv file. So if there's 24 frames, there should  be 24 'emotion' results in the csv file.

I've tried searching other questions here but they either don't answer my question or I don't understand them. Thanks in advance.

Body:
`   from deepface import DeepFace
import pandas as pd
import os, os.path
from os import path

test = '(path to jpg images)'
csv_records = '(path to save csv records)'
df = pd.DataFrame()
for file in os.listdir(test):
    if file.endswith('.jpg'):
        thisframe = 0
        filename = str(os.path.join(test, str(thisframe) + '.jpg'))
        predictions = DeepFace.analyze(filename, actions = ['emotion'])
        df2 = pd.DataFrame(predictions)
        df3 = df.append(df2)
        df3.to_csv(os.path.join(csv_records, 'record.csv'))
        thisframe += 1`

I'm making an emotion recognition program and the images are obtained from a program which exports frames in jpg format from real-time footage. I want to pass those images into the deepface.analyze program and then combine the 'emotion' part of the analysis for all of the frames into a dataframe and subsequently export the results into a csv file. So if there's 24 frames, there should  be 24 'emotion' results in the csv file.

I've tried searching other questions here but they either don't answer my question or I don't understand them. Thanks in advance.


问:
Use widget inside TextFormField
I am in need to have a widget inside a TextFormField. For an example of what I need, see how this library uses images inline in the ExtendedTextField. I need that exact same thing, but instead of an inline image it would be an inline widget.

Is there a way to accomplish this?

Thank you

Title: Use widget inside TextFormField


问:
Generating a functional component declaration based on state - React / Tailwind
In the below code (SideBar.jsx), when a user clicks on a menu item, I capture the title from the Menus array and hold it in the component state.  I've console logged the component state and this is working as planned, when menu items are clicked.  I now want to use the value in the component state as the name of a component declaration elsewhere in the function, so that when the user clicks a certain menu item, it will open a corresponding .jsx functional component (e.g. HomePage.jsx, Notifications.jsx, Members.jsx, etc - determined from the previously mentioned array).

If I want to declare a functional component, then I code it as below (using Homepage as an example):

```<code><HomePage />
</code>```

So I tried doing the following to dynamically generate the declaration from the content of the component state:

```<code><{component} />
</code>```

But this gives me a syntax error, so I guess my approach here is wrong.

How would I go about dynamically creating the component declaration content based on the value held in the component state?

Code:

App.jsx

```<code>import SideBar from './components/SideBar';
const App = () => {
  return (
    <div>
      <SideBar />
    </div>
  );
};
export default App;
</code>```

SideBar.jsx

```<code>import { useState } from 'react';
import HomePage from './HomePage';

function SideBar() {
  const [open, setOpen] = useState(true);
  const [component, setComponent] = useState('');
  console.log(component)
  const Menus = [
    { id: '1', title: 'HomePage', src: 'Chart_fill' },
    { id: '2', title: 'Notifications', src: 'Chat' },
    { id: '3', title: 'Members', src: 'User', gap: true },
    { id: '4', title: 'Events', src: 'Calendar' },
    { id: '5', title: 'Staff', src: 'Search' },
    { id: '6', title: 'Services', src: 'Chart' },
    { id: '7', title: 'Reports', src: 'Folder', gap: true },
    { id: '8', title: 'Settings', src: 'Setting' },
  ];

  return (
    <div className="flex">
      <div
        className={` ${
          open ? 'w-72' : 'w-20 '
        } bg-dark-purple h-screen p-5  pt-8 relative duration-300`}
      >
        <img
          src={require('../assets/control.png')}
          alt="Missing Icon"
          className={`absolute cursor-pointer -right-3 top-10 w-7 border-dark-purple
           border-2 rounded-full  ${!open && 'rotate-180'}`}
          onClick={() => setOpen(!open)}
        />
        <div className="flex gap-x-4 items-center">
          <img
            src={require('../assets/logo.png')}
            alt="Missing Icon"
            className={`cursor-pointer duration-500 ${
              open && 'rotate-[360deg]'
            }`}
          />
          <h1
            className={`text-white origin-left font-medium text-xl duration-200 ${
              !open && 'scale-0'
            }`}
          >
            ADCA
          </h1>
        </div>
        <ul className="pt-6">
          {Menus.map((Menu, index) => (
            <li
              onClick={() => {
                component !== Menu.title
                  ? setComponent(Menu.title)
                  : setComponent('');
              }
              }
              key={index}
              className={`flex rounded-md p-2 cursor-pointer hover:bg-light-white text-gray-300 text-sm items-center gap-x-4
              ${Menu.gap ? 'mt-9' : 'mt-2'} ${
                index === 0 && 'bg-light-white' // sets the background overlay colour of a menu item (by index number)
              } `}
            >
              <img
                src={require(`../assets/${Menu.src}.png`)}
                alt="Missing Icon"
              />
              <span className={`${!open && 'hidden'} origin-left duration-200`}>
                {Menu.title}
              </span>
            </li>
          ))}
        </ul>
      </div>
      <div className="h-screen flex-1 p-7">
        <h1 className="text-2xl font-semibold ">Home Page</h1>

        <{component} />

      </div>
    </div>
  );
}

export default SideBar;
</code>```

Body:
In the below code (SideBar.jsx), when a user clicks on a menu item, I capture the title from the Menus array and hold it in the component state.  I've console logged the component state and this is working as planned, when menu items are clicked.  I now want to use the value in the component state as the name of a component declaration elsewhere in the function, so that when the user clicks a certain menu item, it will open a corresponding .jsx functional component (e.g. HomePage.jsx, Notifications.jsx, Members.jsx, etc - determined from the previously mentioned array).

If I want to declare a functional component, then I code it as below (using Homepage as an example):

<HomePage />

So I tried doing the following to dynamically generate the declaration from the content of the component state:

<{component} />

But this gives me a syntax error, so I guess my approach here is wrong.

How would I go about dynamically creating the component declaration content based on the value held in the component state?

Code:

App.jsx

import SideBar from './components/SideBar';
const App = () => {
  return (

      <SideBar />

  );
};
export default App;

SideBar.jsx

import { useState } from 'react';
import HomePage from './HomePage';

function SideBar() {
  const [open, setOpen] = useState(true);
  const [component, setComponent] = useState('');
  console.log(component)
  const Menus = [
    { id: '1', title: 'HomePage', src: 'Chart_fill' },
    { id: '2', title: 'Notifications', src: 'Chat' },
    { id: '3', title: 'Members', src: 'User', gap: true },
    { id: '4', title: 'Events', src: 'Calendar' },
    { id: '5', title: 'Staff', src: 'Search' },
    { id: '6', title: 'Services', src: 'Chart' },
    { id: '7', title: 'Reports', src: 'Folder', gap: true },
    { id: '8', title: 'Settings', src: 'Setting' },
  ];

  return (

         setOpen(!open)}
        />

            ADCA

          {Menus.map((Menu, index) => (

 {
                component !== Menu.title
                  ? setComponent(Menu.title)
                  : setComponent('');
              }
              }
              key={index}
              className={`flex rounded-md p-2 cursor-pointer hover:bg-light-white text-gray-300 text-sm items-center gap-x-4
              ${Menu.gap ? 'mt-9' : 'mt-2'} ${
                index === 0 && 'bg-light-white' // sets the background overlay colour of a menu item (by index number)
              } `}
            >
              <img
                src={require(`../assets/${Menu.src}.png`)}
                alt="Missing Icon"
              />
              <span className={`${!open && 'hidden'} origin-left duration-200`}>
                {Menu.title}

          ))}

Home Page

        <{component} />

  );
}

export default SideBar;


问:
sql: converting argument $1 type: unsupported type gorm.DB, a struct
Have this:

orm.DB.Table("users", orm.DB.Model(&[]models.User{})).Find(&users)
```

Got this:

sql: converting argument $1 type: unsupported type gorm.DB, a struct

Body:
Have this:

orm.DB.Table("users", orm.DB.Model(&[]models.User{})).Find(&users)

Got this:

sql: converting argument $1 type: unsupported type gorm.DB, a struct


问:
How to work with ag-grid "min" "max" values
how to handle editing of min and max values in ag-grid for angular, so that min value can't be bigger than max value and vice versa?

Let's say we have a data structure like this to put into ag-grid

```<code>{
  data: [
    {
      id: '0',
      one_min: 23,
      one_max: 42,
      two_min: 1,
      two_max: 5,
    },
    {
      id: '1',
      one_min: 20,
      one_max: 40,
      two_min: 10,
      two_max: 15,
    }
  ]
}
</code>```

Then i would dynamically create the columnDefs with something like this:

export class SomeComponent implements OnInit {
  @Input() data!: any[];
  columnDefs: ColDef = [];

  ngOnInit() {
    this.data.forEach(data => Object.keys(data).forEach(key => {
      this.columnDefs.push({
        field: key,
        editable: true,
        ...
      })
    })
  }
}
```
<p>But how to figure out the composit fields 'one' and 'two' and how to tell the grid that min value can't be bigger than max value and vice versa?</p>
<p>The table in this example should lead to 4 rows with 2 columns</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>one_min</th>
<th>one_max</th>
<th>two_min</th>
<th>two_max</th>
</tr>
</thead>
<tbody>
<tr>
<td>23</td>
<td>42</td>
<td>1</td>
<td>5</td>
</tr>
<tr>
<td>20</td>
<td>40</td>
<td>10</td>
<td>15</td>
</tr>
</tbody>
</table>
</div>
<p>I couldn't get any answer from the official docs but i'm sure there must be an easy way of doing this.</p>
<hr />
<h2>Solution</h2>
<p>What we want here is the valueSetter parameter of ColDef.
So data generation should look something like this:</p>
<pre class="lang-js prettyprint-override"><code>export class SomeComponent implements OnInit {
  @Input() data!: any[];
  columnDefs: ColDef = [];

  ngOnInit() {
    this.data.forEach(data => Object.keys(data).forEach(key => {
      this.columnDefs.push({
        field: key,
        editable: true,
        valueSetter: (params) => {
          const colId = params.column.getColId();
          const colIdSplit = colId.split('_');
          const key = colIdSplit[0];
          const param = colIdSplit[1];
          if (param.toLocaleLowerCase() === 'min') {
            const result = !!params.data[`${key}_max`]
                ? parseInt(params.newValue, 10) <= parseInt(params.data[`${key}_max`], 10)
                : true;
            params.data[colId] = result ? params.newValue : params.oldValue;
            return result;
          }
          if (param.toLocaleLowerCase() === 'max') {
            const result = !!params.data[`${key}_min`]
                ? parseInt(params.newValue, 10) >= parseInt(params.data[`${key}_min`], 10)
                : true;
            params.data[colId] = result ? params.newValue : params.oldValue;
            return result;
          }
        return true;
        },
        ...
      })
    })
  }
}
</code>```

Body:
how to handle editing of min and max values in ag-grid for angular, so that min value can't be bigger than max value and vice versa?

Let's say we have a data structure like this to put into ag-grid

{
  data: [
    {
      id: '0',
      one_min: 23,
      one_max: 42,
      two_min: 1,
      two_max: 5,
    },
    {
      id: '1',
      one_min: 20,
      one_max: 40,
      two_min: 10,
      two_max: 15,
    }
  ]
}

Then i would dynamically create the columnDefs with something like this:

export class SomeComponent implements OnInit {
  @Input() data!: any[];
  columnDefs: ColDef = [];

  ngOnInit() {
    this.data.forEach(data => Object.keys(data).forEach(key => {
      this.columnDefs.push({
        field: key,
        editable: true,
        ...
      })
    })
  }
}

But how to figure out the composit fields 'one' and 'two' and how to tell the grid that min value can't be bigger than max value and vice versa?

The table in this example should lead to 4 rows with 2 columns

one_min
one_max
two_min
two_max

23
42
1
5

20
40
10
15

I couldn't get any answer from the official docs but i'm sure there must be an easy way of doing this.

Solution

What we want here is the valueSetter parameter of ColDef.
So data generation should look something like this:

export class SomeComponent implements OnInit {
  @Input() data!: any[];
  columnDefs: ColDef = [];

  ngOnInit() {
    this.data.forEach(data => Object.keys(data).forEach(key => {
      this.columnDefs.push({
        field: key,
        editable: true,
        valueSetter: (params) => {
          const colId = params.column.getColId();
          const colIdSplit = colId.split('_');
          const key = colIdSplit[0];
          const param = colIdSplit[1];
          if (param.toLocaleLowerCase() === 'min') {
            const result = !!params.data[`${key}_max`]
                ? parseInt(params.newValue, 10) <= parseInt(params.data[`${key}_max`], 10)
                : true;
            params.data[colId] = result ? params.newValue : params.oldValue;
            return result;
          }
          if (param.toLocaleLowerCase() === 'max') {
            const result = !!params.data[`${key}_min`]
                ? parseInt(params.newValue, 10) >= parseInt(params.data[`${key}_min`], 10)
                : true;
            params.data[colId] = result ? params.newValue : params.oldValue;
            return result;
          }
        return true;
        },
        ...
      })
    })
  }
}


问:
Query on the access to Object in JS
I got the excise on JS as below:

Finish the function group. Sort each food by it's type and return an object in the format shown below example.

```<code>Given an array of fruits in this format:

[
    { food: 'apple', type: 'fruit' },
    { food: 'orange', type: 'fruit' },
    { food: 'carrot', type: 'vegetable' }
]
Let's turn it into an object with this format:

{
     fruit: ['orange', 'apple'],
     vegetable: ['carrot']
}
</code>```

Correct answer is below codes:

```<code>// food is an array full of food objects
// let's group them by "type" and return them
function group(foods) {
    return foods.reduce((accumulator, currentValue) => {
        accumulator[currentValue.type] = accumulator[currentValue.type] || []
        accumulator[currentValue.type].push(currentValue.food);
        return accumulator;
    }, {});
}

module.exports = group;
</code>```

My question is, since the initial value for accumulator is a empty object {}, and we plan to add new values to this Object. But why use the line like this "accumulator[currentValue.type].push(currentValue.food);", I thought it should push a value to array when it is written like this "accumulator[currentValue.type]", why it didn't be written like "accumulator.currentValue.type"? should it be the way how to access the value in Object? Could you explain why I am wrong?

Thanks,

Title: Query on the access to Object in JS

Body:
I got the excise on JS as below:

Finish the function group. Sort each food by it's type and return an object in the format shown below example.

Given an array of fruits in this format:

[
    { food: 'apple', type: 'fruit' },
    { food: 'orange', type: 'fruit' },
    { food: 'carrot', type: 'vegetable' }
]
Let's turn it into an object with this format:

{
     fruit: ['orange', 'apple'],
     vegetable: ['carrot']
}

Correct answer is below codes:

// food is an array full of food objects
// let's group them by "type" and return them
function group(foods) {
    return foods.reduce((accumulator, currentValue) => {
        accumulator[currentValue.type] = accumulator[currentValue.type] || []
        accumulator[currentValue.type].push(currentValue.food);
        return accumulator;
    }, {});
}

module.exports = group;

My question is, since the initial value for accumulator is a empty object {}, and we plan to add new values to this Object. But why use the line like this "accumulator[currentValue.type].push(currentValue.food);", I thought it should push a value to array when it is written like this "accumulator[currentValue.type]", why it didn't be written like "accumulator.currentValue.type"? should it be the way how to access the value in Object? Could you explain why I am wrong?

Thanks,


问:
Unit test with react and logRocket
I installed the LogRocket library on my application.

I initialise logRocket on my index.ts

like this :

```<code>LogRocket.init('url', {
  dom : {
   textSanitizer: true,
   inputSanitizer: true,
  }
});

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
 </React.StrictMode>,
 document.getElementById('root')
);

reportWebVitals();
</code>```

if I run the unit test of index.ts :

```<code>ReferenceError: XMLHttpRequest is not defined

  21 | });
  22 |
> 23 | LogRocket.init('url', {
     |           ^
  24 |   dom : {
  25 |     textSanitizer: true,
  26 |     inputSanitizer: true,
</code>```

here is the test :

```<code> jest.mock('react-dom', () => ({ render: jest.fn() }));

 describe('Application root', () => {
   it('should render without crashing', () => {
    const ReactStrictMode = (
    <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
   );
   const rootElement = document.getElementById('root');

   ReactDOM.render(ReactStrictMode, rootElement);
   expect(ReactDOM.render).toHaveBeenCalledWith(ReactStrictMode, rootElement);
  });
});
</code>```

What would be the solution for the unit test to integrate logRocket without returning an error?

Title: Unit test with react and logRocket

Body:
I installed the LogRocket library on my application.

I initialise logRocket on my index.ts

like this :

LogRocket.init('url', {
  dom : {
   textSanitizer: true,
   inputSanitizer: true,
  }
});

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
 </React.StrictMode>,
 document.getElementById('root')
);

reportWebVitals();

if I run the unit test of index.ts :

ReferenceError: XMLHttpRequest is not defined

  21 | });
  22 |
> 23 | LogRocket.init('url', {
     |           ^
  24 |   dom : {
  25 |     textSanitizer: true,
  26 |     inputSanitizer: true,

here is the test :

 jest.mock('react-dom', () => ({ render: jest.fn() }));

 describe('Application root', () => {
   it('should render without crashing', () => {
    const ReactStrictMode = (
    <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
   );
   const rootElement = document.getElementById('root');

   ReactDOM.render(ReactStrictMode, rootElement);
   expect(ReactDOM.render).toHaveBeenCalledWith(ReactStrictMode, rootElement);
  });
});

What would be the solution for the unit test to integrate logRocket without returning an error?


问:
Python: using pynput mouse listener to set a bool for x seconds
I want to have a shared bool between threads that is write-accessed in two threads (but since its just a byte should be thread-safe) and then read in the main thread. The execution of the main thread depends on wheter the bool is true or false. I currently have a pynput mouse listener thread listed below:

```<code>listener = mouse.Listener(on_click=on_click)
listener.start()

def on_click(x, y, button, pressed):
    global Xcord, Ycord, mousePressed

    if pressed:
        mousePressed = True
    Xcord = x
    Ycord = y
</code>```

and a thread plotting_thread that resets the bool mousePressed exactly after 10 seconds if it changes to true:

```<code>x = threading.Thread(target=plotting_thread, args=())
x.start()

def plotting_thread():
    while not shutdown:
        global mousePressed
        if mousePressed:
            time.sleep(10)
            mousePressed = False
</code>```

I then read the bool mousePressed in the main thread and plot something according to if mousePressed is set.

My problem is the following: The computer and mouse start to lag quite badly exactly 10 seconds after I press the mouse (without pressing it again). This can be replicated every time. So upon startup it works fine for 10 seconds, then it starts lagging. I click the mouse once, it works fine for 10 seconds and then starts lagging again, etc...

My best guess is a constant overwrite which keeps the program busy but I don't see where it could happen since on_click() is only called upon a mouse click.

I've tried to use python events via .set() and .is_set(), but that resulted in the exact same behavior. If I remove the assignment mousePressed = false in the plotting_thread(), it works fine so it definetly is some constant overwrite or something similar. But I do not see why it would happen and how to fix it so that it just works without lagging.

Thank you

Body:
I want to have a shared bool between threads that is write-accessed in two threads (but since its just a byte should be thread-safe) and then read in the main thread. The execution of the main thread depends on wheter the bool is true or false. I currently have a pynput mouse listener thread listed below:

listener = mouse.Listener(on_click=on_click)
listener.start()

def on_click(x, y, button, pressed):
    global Xcord, Ycord, mousePressed

    if pressed:
        mousePressed = True
    Xcord = x
    Ycord = y

and a thread plotting_thread that resets the bool mousePressed exactly after 10 seconds if it changes to true:

x = threading.Thread(target=plotting_thread, args=())
x.start()

def plotting_thread():
    while not shutdown:
        global mousePressed
        if mousePressed:
            time.sleep(10)
            mousePressed = False

I then read the bool mousePressed in the main thread and plot something according to if mousePressed is set.

My problem is the following: The computer and mouse start to lag quite badly exactly 10 seconds after I press the mouse (without pressing it again). This can be replicated every time. So upon startup it works fine for 10 seconds, then it starts lagging. I click the mouse once, it works fine for 10 seconds and then starts lagging again, etc...

My best guess is a constant overwrite which keeps the program busy but I don't see where it could happen since on_click() is only called upon a mouse click.

I've tried to use python events via .set() and .is_set(), but that resulted in the exact same behavior. If I remove the assignment mousePressed = false in the plotting_thread(), it works fine so it definetly is some constant overwrite or something similar. But I do not see why it would happen and how to fix it so that it just works without lagging.

Thank you


问:
Unable to update value in view despite using two way binding
I am attempting to two-way bind between the HTML and the TS. The goal is that when the user clicks the getAddress button, the TS automatically populates the input box of Address 1 and Address 2 after obtaining the information. As such, the user does not need to type the address out manually. Unfortunately, when the address values are updated, the view does not update with the new values despite using NgModel. How do I notify the view to update the input box when it receives a new value?

public async getCurrentAddress() {
    // variables
    const geolocationService = this.geolocationService
    let address1 = this.address1;
    let address2 = this.address2;
    const address = geolocationService.getAddressOfCurrentLocation()

    // the TS variables address1 and address 2 values updates but the view does not update with the new values
    address1 = address[0]
    address2 = address[1]
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-item>
  <ion-label>Enter Address 1</ion-label>
  <ion-input placeholder="Enter your address 1" [(ngModel)]="address1"></ion-input>
</ion-item>

<ion-item>
  <ion-label>Enter Address 2</ion-label>
  <ion-input placeholder="Enter your address 2" [(ngModel)]="address2"></ion-input>
</ion-item></code>```

Body:
I am attempting to two-way bind between the HTML and the TS. The goal is that when the user clicks the getAddress button, the TS automatically populates the input box of Address 1 and Address 2 after obtaining the information. As such, the user does not need to type the address out manually. Unfortunately, when the address values are updated, the view does not update with the new values despite using NgModel. How do I notify the view to update the input box when it receives a new value?

public async getCurrentAddress() {
    // variables
    const geolocationService = this.geolocationService
    let address1 = this.address1;
    let address2 = this.address2;
    const address = geolocationService.getAddressOfCurrentLocation()

    // the TS variables address1 and address 2 values updates but the view does not update with the new values
    address1 = address[0]
    address2 = address[1]
 }

<ion-item>
  <ion-label>Enter Address 1</ion-label>
  <ion-input placeholder="Enter your address 1" [(ngModel)]="address1"></ion-input>
</ion-item>

<ion-item>
  <ion-label>Enter Address 2</ion-label>
  <ion-input placeholder="Enter your address 2" [(ngModel)]="address2"></ion-input>
</ion-item>


问:
Analyzing Bounded Proportion Data in R
I need some advice to understand the following code. We are working with lung data and usually we use LMS technique to calculate the reference curves. In order to calcualte the curves with LMS method from gamlss package we use the following code (forexample)

```<code>library(gamlss)
A<-lungFunction

m1 <- gamlss(slf ~ log(height) + pb(log(age)), sigma.fo =~pb(log(age)), nu.fo =~pb(log(age)), family = BCCGo(mu.link = "log"), data=A)
</code>```

the link for µ needs to be the log.

*It seems that LMS method is not appropriate method when the response variable is a ratio or proportion, So  inflated logitSST distributions is proposed instead. In an article, the following code was used to calculate the centile curves for slf which is a proportion (0,1]. I could not understand why ga function and s function were used to define the µ. So any advice regarding that would be highly appreciated. I am also wondering how I can Implement the prediction equation and and the contribution of the splines (Mu,Sigma,nu) varies with age *

```<code>library(gamlss.inf)
library(gamlss.add)

 gen.Family("SST", "logit")

mf1 <- gamlssInf0to1(y=slf,
                     mu.formula = ~ ga(~s(log(height), log(age))),
                     sigma.formula = ~pb(log(age)),
                     nu.formula = ~pb(log(age)),
                     tau.formula = ~pb(log(age)),
                     xi1.formula = ~pb(log(age))+ pb(log(height)),
                     family = logitSST,
                     data = A,
                     n.cyc = 100,
                     trace = TRUE)
</code>```

Title: Analyzing Bounded Proportion Data in R

Body:
I need some advice to understand the following code. We are working with lung data and usually we use LMS technique to calculate the reference curves. In order to calcualte the curves with LMS method from gamlss package we use the following code (forexample)

library(gamlss)
A<-lungFunction

m1 <- gamlss(slf ~ log(height) + pb(log(age)), sigma.fo =~pb(log(age)), nu.fo =~pb(log(age)), family = BCCGo(mu.link = "log"), data=A)

the link for µ needs to be the log.

*It seems that LMS method is not appropriate method when the response variable is a ratio or proportion, So  inflated logitSST distributions is proposed instead. In an article, the following code was used to calculate the centile curves for slf which is a proportion (0,1]. I could not understand why ga function and s function were used to define the µ. So any advice regarding that would be highly appreciated. I am also wondering how I can Implement the prediction equation and and the contribution of the splines (Mu,Sigma,nu) varies with age *

library(gamlss.inf)
library(gamlss.add)

 gen.Family("SST", "logit")

mf1 <- gamlssInf0to1(y=slf,
                     mu.formula = ~ ga(~s(log(height), log(age))),
                     sigma.formula = ~pb(log(age)),
                     nu.formula = ~pb(log(age)),
                     tau.formula = ~pb(log(age)),
                     xi1.formula = ~pb(log(age))+ pb(log(height)),
                     family = logitSST,
                     data = A,
                     n.cyc = 100,
                     trace = TRUE)


问:
Why copy to a clipboard doesn't work for an html bibtex content?
I want to copy the bibtex content that is inside the span(id=cntee) when clicking on copy text. Why is the content not copied?

The copy to clipboard work when I don't use the 'bibtex_template' class in:

.

/* scrpt.js */

$(function(){
  new Clipboard('.copy-text');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* style.css */

@import url("https://fonts.googleapis.com/css?family=Oswald|Roboto:400,700");
body {
  font-size: 14px;
  height: 100%;
  /*line-height: 1.5;*/
}

.navbar {
  margin-bottom: 6em;
}

h1 {
  font-size: 2rem;
  margin-bottom: .5em;
}

p {
  font-family: 'Roboto', sans-serif;
  font-size: 1.1rem;
}

.container {
  max-width: 1024px;
  width: 90%;
  margin: 0 auto;
}

#avatar{
  margin-right: 3em;
  height: 250px;
  border-radius: 100%;
  border: 2px solid rgba(0, 0, 0, 0.7);
}

#aboutme{
  padding-top: 3em;
  padding-bottom: 2em;
}

.timeline-item {
  padding: 3em 2em 0.1em;
  position: relative;
  color: rgba(0, 0, 0, 0.7);
  border-left: 2px solid rgba(0, 0, 0, 0.3);
}

.timeline-item p {
  font-size: 1.1rem;
}

.timeline-item .date{
  margin-top: -2.1em;
  font-weight: bold;
  font-weight: 700;
  font-size: 1rem;
}

.my_pre {
  position: relative;
  margin: 1px;
  padding: 5px;
  color:#212529;
  font-size: 78.5%;
  word-break: keep-all;
  border: 2px dashed #0404d7a8;
}

.timeline-item .article{
  margin-top: -2.1em;

  font-size: 1rem;
}

.timeline-item .date img{
  width: 48px; float: left;
}

.timeline-item::after {
  width: 10px;
  height: 10px;
  display: block;
  top: 1em;
  position: absolute;
  left: -7px;
  border-radius: 10px;
  content: '';
  border: 2px solid rgba(0, 0, 0, 0.3);
  background: white;
}
.timeline-item:last-child {
  -o-border-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 60%, transparent) 1 100%;
     border-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.3) 60%, transparent) 1 100%;
     border-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 60%, transparent) 1 100%;
}

.timeline-item:first-child {
  -o-border-image: linear-gradient(to top, rgba(0, 0, 0, 0.3) 90%, transparent) 1 100%;
     border-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.3) 90%, transparent) 1 100%;
     border-image: linear-gradient(to top, rgba(0, 0, 0, 0.3) 90%, transparent) 1 100%;
}

footer {
  margin-top: 5em;
}</code>```

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css">

    <textarea id="bibtex_input" style="display:none;">
      @article{aaaaaaaa,
        author    = {S, E. and J, Z. and W, I. and N, V.},
        title     = {Test article title},
        booktitle   = {Journal of test},
        pages     = {347895},
        year      = {2018}
      }
    </textarea>

            ,

            .

            [Cite (BibTeX)]

              copy Text
            ```
          </div>
        </div>
      </div>
    </div>

    <div id="bibtex_display"></div>
  </div>

  <br>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/gh/pcooksey/bibtex-js@1.0.0/src/bibtex_js.js"></script>
  <script src="scrpt.js"></script>

</body>
</html></code>```

Body:
I want to copy the bibtex content that is inside the span(id=cntee) when clicking on copy text. Why is the content not copied?

The copy to clipboard work when I don't use the 'bibtex_template' class in:

.

/* scrpt.js */

$(function(){
  new Clipboard('.copy-text');
});

/* style.css */

@import url("https://fonts.googleapis.com/css?family=Oswald|Roboto:400,700");
body {
  font-size: 14px;
  height: 100%;
  /*line-height: 1.5;*/
}

.navbar {
  margin-bottom: 6em;
}

h1 {
  font-size: 2rem;
  margin-bottom: .5em;
}

p {
  font-family: 'Roboto', sans-serif;
  font-size: 1.1rem;
}

.container {
  max-width: 1024px;
  width: 90%;
  margin: 0 auto;
}

#avatar{
  margin-right: 3em;
  height: 250px;
  border-radius: 100%;
  border: 2px solid rgba(0, 0, 0, 0.7);
}

#aboutme{
  padding-top: 3em;
  padding-bottom: 2em;
}

.timeline-item {
  padding: 3em 2em 0.1em;
  position: relative;
  color: rgba(0, 0, 0, 0.7);
  border-left: 2px solid rgba(0, 0, 0, 0.3);
}

.timeline-item p {
  font-size: 1.1rem;
}

.timeline-item .date{
  margin-top: -2.1em;
  font-weight: bold;
  font-weight: 700;
  font-size: 1rem;
}

.my_pre {
  position: relative;
  margin: 1px;
  padding: 5px;
  color:#212529;
  font-size: 78.5%;
  word-break: keep-all;
  border: 2px dashed #0404d7a8;
}

.timeline-item .article{
  margin-top: -2.1em;

  font-size: 1rem;
}

.timeline-item .date img{
  width: 48px; float: left;
}

.timeline-item::after {
  width: 10px;
  height: 10px;
  display: block;
  top: 1em;
  position: absolute;
  left: -7px;
  border-radius: 10px;
  content: '';
  border: 2px solid rgba(0, 0, 0, 0.3);
  background: white;
}
.timeline-item:last-child {
  -o-border-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 60%, transparent) 1 100%;
     border-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.3) 60%, transparent) 1 100%;
     border-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.3) 60%, transparent) 1 100%;
}

.timeline-item:first-child {
  -o-border-image: linear-gradient(to top, rgba(0, 0, 0, 0.3) 90%, transparent) 1 100%;
     border-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.3) 90%, transparent) 1 100%;
     border-image: linear-gradient(to top, rgba(0, 0, 0, 0.3) 90%, transparent) 1 100%;
}

footer {
  margin-top: 5em;
}

<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css">

    <textarea id="bibtex_input" style="display:none;">
      @article{aaaaaaaa,
        author    = {S, E. and J, Z. and W, I. and N, V.},
        title     = {Test article title},
        booktitle   = {Journal of test},
        pages     = {347895},
        year      = {2018}
      }
    </textarea>

            ,

            .

            [Cite (BibTeX)]

              copy Text


问:
Filtering on patterns in AgensGraph
I'm having a hard time filtering by patterns in AgensGraph. According to the Cypher Query Language Reference I should be allowed to filter on patterns using NOT. However, this does not seem to work in AgensGraph.

```<code>CREATE (eric:person {name:'Eric'}), (amy:person {name:'Amy'}), (peter:person {name: 'Peter'})
MERGE (amy)-[:knows]->(peter);

MATCH (persons:person), (peter:person {name: 'Peter'})
WHERE NOT (persons)-[]->(peter)
RETURN persons.name
</code>```

I'd expect 'Eric' as a result, but I get an error saying Graph object cannot be jsonb.
How would I go about finding all people who don't know Peter using AgensGraph?

Title: Filtering on patterns in AgensGraph

Body:
I'm having a hard time filtering by patterns in AgensGraph. According to the Cypher Query Language Reference I should be allowed to filter on patterns using NOT. However, this does not seem to work in AgensGraph.

CREATE (eric:person {name:'Eric'}), (amy:person {name:'Amy'}), (peter:person {name: 'Peter'})
MERGE (amy)-[:knows]->(peter);

MATCH (persons:person), (peter:person {name: 'Peter'})
WHERE NOT (persons)-[]->(peter)
RETURN persons.name

I'd expect 'Eric' as a result, but I get an error saying Graph object cannot be jsonb.
How would I go about finding all people who don't know Peter using AgensGraph?


问:
java swing borderlayout constraints error
I am new to Java Swing and I have been trying to create a vertical menu panel but I having been facing trouble in adding it to the left middle of the frame. I have a little knowledge on the layout packages provided by Swing and tried many ways to resolve this issue yet failed to fix it.

Here's the code I tried:

this.mainPanel = new JPanel();

// Set up the button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));

// Set a border for the button panel using a TitledBorder
TitledBorder border = BorderFactory.createTitledBorder("Menu");
buttonPanel.setBorder(border);

// Create three buttons with different text
this.homeMenuButton = new JButton("Home");
this.DoctorMenuButton = new JButton("Doctors");
this.ConsultationsMenuButton = new JButton("Consultations");
this.notesMenuButton = new JButton("Notes");
this.viewConsultationsMenuButton = new JButton("View Consultations");

buttonPanel.add(homeMenuButton);
buttonPanel.add(DoctorMenuButton);
buttonPanel.add(ConsultationsMenuButton);
buttonPanel.add(notesMenuButton);
buttonPanel.add(viewConsultationsMenuButton);

GroupLayout layout = new GroupLayout(buttonPanel);
buttonPanel.setLayout(layout);

layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

layout.setHorizontalGroup(
        layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(homeMenuButton)
                .addComponent(DoctorMenuButton)
                .addComponent(ConsultationsMenuButton)
                .addComponent(notesMenuButton)
                .addComponent(viewConsultationsMenuButton)
);

layout.setVerticalGroup(
        layout.createSequentialGroup()
                .addComponent(homeMenuButton)
                .addComponent(DoctorMenuButton)
                .addComponent(ConsultationsMenuButton)
                .addComponent(notesMenuButton)
                .addComponent(viewConsultationsMenuButton)
);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(buttonPanel, gbc);
```

I tried adding BorderLayout "west" constraint and failed.

Body:
I am new to Java Swing and I have been trying to create a vertical menu panel but I having been facing trouble in adding it to the left middle of the frame. I have a little knowledge on the layout packages provided by Swing and tried many ways to resolve this issue yet failed to fix it.

Here's the code I tried:

this.mainPanel = new JPanel();

// Set up the button panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));

// Set a border for the button panel using a TitledBorder
TitledBorder border = BorderFactory.createTitledBorder("Menu");
buttonPanel.setBorder(border);

// Create three buttons with different text
this.homeMenuButton = new JButton("Home");
this.DoctorMenuButton = new JButton("Doctors");
this.ConsultationsMenuButton = new JButton("Consultations");
this.notesMenuButton = new JButton("Notes");
this.viewConsultationsMenuButton = new JButton("View Consultations");

buttonPanel.add(homeMenuButton);
buttonPanel.add(DoctorMenuButton);
buttonPanel.add(ConsultationsMenuButton);
buttonPanel.add(notesMenuButton);
buttonPanel.add(viewConsultationsMenuButton);

GroupLayout layout = new GroupLayout(buttonPanel);
buttonPanel.setLayout(layout);

layout.setAutoCreateGaps(true);
layout.setAutoCreateContainerGaps(true);

layout.setHorizontalGroup(
        layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(homeMenuButton)
                .addComponent(DoctorMenuButton)
                .addComponent(ConsultationsMenuButton)
                .addComponent(notesMenuButton)
                .addComponent(viewConsultationsMenuButton)
);

layout.setVerticalGroup(
        layout.createSequentialGroup()
                .addComponent(homeMenuButton)
                .addComponent(DoctorMenuButton)
                .addComponent(ConsultationsMenuButton)
                .addComponent(notesMenuButton)
                .addComponent(viewConsultationsMenuButton)
);

GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
mainPanel.add(buttonPanel, gbc);

I tried adding BorderLayout "west" constraint and failed.


问:
How to set json:Type="Decimal" Attribute in XMLNode C#
I want to set the attribute json:Type="Decimal" into a XML Node.

I have the XML Document

```<code><root>
 <a>12.55</a>
 <b>Test</b>
</root>
</code>```

Now I want to set the attribute

```<code>json:Type="Decimal"
</code>```

in the XML Node

```<code><a>12.55</a>
</code>```

that it looks like

```<code><a json:Type="Decimal">12.55</a>
</code>```

I tried with the following Code

```<code>XmlAttribute att = Doc.CreateAttribute("Type");
att.Prefix = "json";
att.Value = "Decimal";
node.Attributes.Append(att);
</code>```

but the result is

```<code><a Type="Decimal">12.55</a>
</code>```

Who can help me!

The original question is from here

Body:
I want to set the attribute json:Type="Decimal" into a XML Node.

I have the XML Document

<root>
 12.55
 Test
</root>

Now I want to set the attribute

json:Type="Decimal"

in the XML Node

12.55

that it looks like

12.55

I tried with the following Code

XmlAttribute att = Doc.CreateAttribute("Type");
att.Prefix = "json";
att.Value = "Decimal";
node.Attributes.Append(att);

but the result is

12.55

Who can help me!

The original question is from here


问:
Login issues of the services registered with AWS Load Balancer
I have load balancer listening on two ports one abc and other xyz. These port redirect them to the different instances. But the instance are running the same application but with different data. The application has login page. The issue is when i access Lb with abc port and login to the application its logging out the existing application running on the other port xyz. Is there any way to make these both sessions active. Note both the instances are running same application but has different data.

The possible solution to overcome this problem


问:
Deleting a row with VBA in Excel gives invalid reference in another table
I have an Excel Workbook with 2 sheets. Each sheet contains a formatted table.

The tables start at row2 and feature an internal numbering in columnA achieved by the formulas

```<code>=Row()-Row(talble1)+1 and =Row()-Row(talble2)+1
</code>```

sheet2:
In table2/columnB I concatenate 2 of the internal row indices from table1 using the formulas

```<code>table2/internal row1: =CONCATENATE(sheet1!A2;";";sheet1!A3;";")
table2/internal row2: =CONCATENATE(sheet1!A4;";";sheet1!A5;";")
table2/internal row3: =CONCATENATE(sheet1!A6;";";sheet1!A7;";")
table2/internal row4: (...)
</code>```

It looks like this:

```<code>sheet1/table1:                   sheet2/table2:

     A    B     C                     A    B     C
1                                1
2    1                           2    1    1;2
3    2                           3    2    3;4
4    3                           4    3    5;6
5    4                           5
6    5                           6
7    6                           7
8                                8
9                                9
</code>```

If I "manually" delete the 2 rows with internal indices 3 and 4 in table1, the numbering automatically adjusts. Also, the references in internal row2/columnB of table2 become invalid, which makes total sense. The formula of internal row3 in table2 automatically adjusts to the deletion in table1 and remains valid.

It then looks like this:

```<code>sheet1/table1:                   sheet2/table2:

     A    B     C                     A    B     C
1                                1
2    1                           2    1    1;2
3    2                           3    2    invalid
4    3                           4    3    3;4
5    4                           5    4
6                                6    5
7                                7    6
8                                8
9                                9
</code>```

Now comes the issue:

If I do the deletion described above using a VBA macro, the references in internal row3 of table2 become invalid as well! When I check the formula I see that it still references cells A6 and A7 which don't exist anymore in table1.

I used the code

```<code>sheet1.ListObjects("table1").DataBodyRange.Rows(4).Delete Shift:=xlUp
sheet1.ListObjects("table1").DataBodyRange.Rows(3).Delete Shift:=xlUp
</code>```

It looks like this:

```<code>sheet1/table1:                   sheet2/table2:

     A    B     C                     A    B     C
1                                1
2    1                           2    1    1;2
3    2                           3    2    invalid
4    3                           4    3    invalid
5    4                           5    4
6                                6    5
7                                7    6
8                                8
9                                9
</code>```

What is the explanation for the different behaviour of deleting a row in table1 manually or by VBA code?

I also recorded macros when deleting the rows manually and I could not detect anything that explains why my macro code leads to the invalid references in internal row3 of table2.

Body:
I have an Excel Workbook with 2 sheets. Each sheet contains a formatted table.

The tables start at row2 and feature an internal numbering in columnA achieved by the formulas

=Row()-Row(talble1)+1 and =Row()-Row(talble2)+1

sheet2:
In table2/columnB I concatenate 2 of the internal row indices from table1 using the formulas

table2/internal row1: =CONCATENATE(sheet1!A2;";";sheet1!A3;";")
table2/internal row2: =CONCATENATE(sheet1!A4;";";sheet1!A5;";")
table2/internal row3: =CONCATENATE(sheet1!A6;";";sheet1!A7;";")
table2/internal row4: (...)

It looks like this:

sheet1/table1:                   sheet2/table2:

     A    B     C                     A    B     C
1                                1
2    1                           2    1    1;2
3    2                           3    2    3;4
4    3                           4    3    5;6
5    4                           5
6    5                           6
7    6                           7
8                                8
9                                9

If I "manually" delete the 2 rows with internal indices 3 and 4 in table1, the numbering automatically adjusts. Also, the references in internal row2/columnB of table2 become invalid, which makes total sense. The formula of internal row3 in table2 automatically adjusts to the deletion in table1 and remains valid.

It then looks like this:

sheet1/table1:                   sheet2/table2:

     A    B     C                     A    B     C
1                                1
2    1                           2    1    1;2
3    2                           3    2    invalid
4    3                           4    3    3;4
5    4                           5    4
6                                6    5
7                                7    6
8                                8
9                                9

Now comes the issue:

If I do the deletion described above using a VBA macro, the references in internal row3 of table2 become invalid as well! When I check the formula I see that it still references cells A6 and A7 which don't exist anymore in table1.

I used the code

sheet1.ListObjects("table1").DataBodyRange.Rows(4).Delete Shift:=xlUp
sheet1.ListObjects("table1").DataBodyRange.Rows(3).Delete Shift:=xlUp

It looks like this:

sheet1/table1:                   sheet2/table2:

     A    B     C                     A    B     C
1                                1
2    1                           2    1    1;2
3    2                           3    2    invalid
4    3                           4    3    invalid
5    4                           5    4
6                                6    5
7                                7    6
8                                8
9                                9

What is the explanation for the different behaviour of deleting a row in table1 manually or by VBA code?

I also recorded macros when deleting the rows manually and I could not detect anything that explains why my macro code leads to the invalid references in internal row3 of table2.


问:
How do i write a spark sql query which doesn't fail if a field is not present in the json data
I am writing a Spark SQL job to process JSON data daily. Someday, a field is not present at all in the JSON. In this case, a defined column is not present in inferred schema from JSON. Is there a way to get around this.

```<code>select col1, col2, col3.data from table1
</code>```

When col3.data is not present, the job fails. How to gracefully handle this.

I tried using below to handle this:

```<code>* COALESCE(col3.data, 'dummyData')
</code>```

This works for NULL value of data not when data field itself is not present.

Body:
I am writing a Spark SQL job to process JSON data daily. Someday, a field is not present at all in the JSON. In this case, a defined column is not present in inferred schema from JSON. Is there a way to get around this.

select col1, col2, col3.data from table1

When col3.data is not present, the job fails. How to gracefully handle this.

I tried using below to handle this:

* COALESCE(col3.data, 'dummyData')

This works for NULL value of data not when data field itself is not present.


问:
where can find VoxCeleb2 dataset? the origin website's dataset are no longer available
where can find VoxCeleb2 dataset? the origin website's dataset are no longer available

can you give me a link-site that can get voxceleb2 dataset.I really need that.


问:
terminate python script with key press outside of console window (on windows)
I am writing a script to automate stuff in another program (let's call it the main program) on Windows (the main program is only available for Windows). The script reacts to certain visual elements in the main program by clicking on them. Now I would like to add some way of terminating the script while I'm in fullscreen mode in the main program. Right now I have to alt-tab into the console where my script is running and press ctr+c. The problem here is, that if I alt-tab while my script is running, it might click some random stuff on my desktop.

Ideally, I would like to add some key combination that I have to press while I'm in the main program that would terminate (or pause) the script. I tried to do this with pynput.keyboard, but windows defender marks it as a keylogger (which it technically is) and removes my script. Is there a way of doing this without triggering windows defender?

Alternatively, I guess I could automatically pause my script, whenever the active window is not the main program. I am wondering whether this might be the common approach for cases like mine?


问:
Snippet expansion without pressing Tab or similar completion/expansion/trigger keys
I have been using Vim with VimTeX and Ultisnips plugins as my LaTeX front end and I would now like to try VSCode and LaTeX-Workshop extension out.

Is the equivalent of the following possible via VSCode snippets?

```<code>snippet mm "Inline Math" wA
\\( $1 \\) $0
endsnippet

</code>```

This snippet has option wA and the functionality here is that if the user types mm in any line (the wA option stands for the beginning of a new word and the expansion is automatic with no need to press a snippet trigger/expansion/completion (e.g., Tab) key.  Within a line, this provides the \( | \) inline math environment.

My initial thought was to have the following in latex.json snippets file:

```<code>"mm": {
        "prefix": "mm",
        "body": [
            "\( $1 \)"
        ],
        "description": "inline math"
}
</code>```

but this needs the snippet expansion/completion/trigger key which is the Tab key pressed after mm

I think this is not possible -- every snippet expansion seems to require the snippet trigger/expansion/completion key. I would like to confirm that it is indeed possible/not possible within VSCode.

The use case is that pressing mm is a lot easier since the keys are close to the home row rather than pressing any other snippet trigger/expansion/completion key.

ETA: I got confirmation that this is currently not possible in VSCode. See here

20 upvotes on VSCode Github page is likely to get work started for eventual completion in several years.

Body:
I have been using Vim with VimTeX and Ultisnips plugins as my LaTeX front end and I would now like to try VSCode and LaTeX-Workshop extension out.

Is the equivalent of the following possible via VSCode snippets?

snippet mm "Inline Math" wA
\\( $1 \\) $0
endsnippet

This snippet has option wA and the functionality here is that if the user types mm in any line (the wA option stands for the beginning of a new word and the expansion is automatic with no need to press a snippet trigger/expansion/completion (e.g., Tab) key.  Within a line, this provides the \( | \) inline math environment.

My initial thought was to have the following in latex.json snippets file:

"mm": {
        "prefix": "mm",
        "body": [
            "\( $1 \)"
        ],
        "description": "inline math"
}

but this needs the snippet expansion/completion/trigger key which is the Tab key pressed after mm

I think this is not possible -- every snippet expansion seems to require the snippet trigger/expansion/completion key. I would like to confirm that it is indeed possible/not possible within VSCode.

The use case is that pressing mm is a lot easier since the keys are close to the home row rather than pressing any other snippet trigger/expansion/completion key.

ETA: I got confirmation that this is currently not possible in VSCode. See here

20 upvotes on VSCode Github page is likely to get work started for eventual completion in several years.


问:
Receiving error when performing transition although it works fine - validator postfunction
I am using scriptrunner postfunction and validator to perform 3 transitions back to back. The problem is that I receive an error message saying

[comment:Please, add a comment.] although a comment has actually been adde as you can see in the screenshot

Here is the code I have used, anyone knows how to fix this?

```<code>package CombineTransitions

import com.onresolve.scriptrunner.runner.util.UserMessageUtil

import com.atlassian.jira.issue.Issue;

import org.apache.log4j.Logger

import com.atlassian.jira.bc.issue.IssueService

import com.atlassian.jira.issue.Issue;

import CombineTransitions.Configuration_CombineTransitions

import com.atlassian.jira.bc.issue.IssueService.IssueResult

import com.atlassian.jira.bc.issue.IssueService.TransitionValidationResult

import com.atlassian.jira.event.type.EventDispatchOption

import  java.util.concurrent.TimeUnit

import  java.util.concurrent.ScheduledExecutorService

import java.util.concurrent.Executors

import com.atlassian.jira.component.ComponentAccessor

import com.atlassian.jira.issue.MutableIssue

import com.atlassian.jira.workflow.WorkflowTransitionUtil

import com.opensymphony.workflow.WorkflowContext;

import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl;

import com.atlassian.jira.util.JiraUtils;

import com.atlassian.jira.issue.MutableIssue;

import com.atlassian.jira.util.ErrorCollection

import com.atlassian.jira.workflow.WorkflowException

import com.atlassian.jira.issue.fields.CustomField

import com.onresolve.jira.groovy.user.FormField

import com.atlassian.jira.issue.CustomFieldManager

import com.atlassian.jira.component.ComponentAccessor

import com.opensymphony.workflow.InvalidInputException

import com.atlassian.jira.component.ComponentAccessor;

import com.atlassian.jira.issue.MutableIssue;

import com.atlassian.jira.issue.fields.screen.FieldScreenRenderLayoutItem;

import com.atlassian.jira.issue.fields.screen.FieldScreenRenderTab;

import com.atlassian.jira.issue.fields.screen.FieldScreenRenderer;

def log1 = Logger.getLogger("atlassian-jira.log")

def combineTransitionsHashMap= Configuration_CombineTransitions.getCombineTransitionsHashMap()

def issueStatusTypeId = combineTransitionsHashMap["issueStatusTypeId"] as String;

def transitionFromOpentoFixed = combineTransitionsHashMap["transitionFromOpentoFixed"] as Integer;

def transitionFromFixedToTested = combineTransitionsHashMap["transitionFromFixedToTested"] as Integer;

def transitionFromTestedToCompleted = combineTransitionsHashMap["transitionFromTestedToCompleted"] as Integer;

def fixedStatusName = combineTransitionsHashMap["fixedStatusName"] as String;

def testedStatusName = combineTransitionsHashMap["testedStatusName"] as String;

def completedStatusName = combineTransitionsHashMap["completedStatusName"] as String;

def fixedStatusId = combineTransitionsHashMap["fixedStatusId"] as String;

def testedStatusId = combineTransitionsHashMap["testedStatusId"] as String;

def completedStatusId = combineTransitionsHashMap["completedStatusId"] as String;

def errorMessage = combineTransitionsHashMap["errorMessage"] as String;

if (issue.getStatus().getSimpleStatus().getId().equals(issueStatusTypeId)) {

        def ok = false

         ok=performTransition(transitionFromOpentoFixed, fixedStatusName, fixedStatusId, errorMessage);

         log.warn("MOUNA first boolean "+ok +" "+fixedStatusName)

   if(ok){

         ok= performTransition(transitionFromFixedToTested, testedStatusName, testedStatusId, errorMessage);

         log.warn("MOUNA second boolean "+ok +" "+testedStatusName)

         if(ok){

          ok= performTransition(transitionFromTestedToCompleted, completedStatusName, completedStatusId, errorMessage);

          log.warn("MOUNA third boolean "+ok +" "+completedStatusName)

         }

  }

}

def  performTransition(int transitionToBeDone, String destinationStatus, String statusId , String errorMessage) {

  log.warn("MOUNA  ORIGINAL STATUS "+ issue.getStatus()  + "DEST STATUS "+ destinationStatus)

//issue = ComponentAccessor.getIssueManager().getIssueObject(issue.id)

issue = transientVars.get("issue");

  def currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()

  String issueKey = issue.getKey()

  IssueService issueService = ComponentAccessor.getIssueService()

  def issueInputParameters = issueService.newIssueInputParameters()

  issueInputParameters.setComment("Transitioning issue from status "+ issue.getStatus().getName()+" to status "+ destinationStatus );

WorkflowTransitionUtil workflowTransitionUtil = (WorkflowTransitionUtil) JiraUtils.loadComponent(WorkflowTransitionUtilImpl.class)

workflowTransitionUtil.setIssue(issue)

workflowTransitionUtil.setAction(transitionToBeDone)

//workflowTransitionUtil.addAdditionalInput(transientVars.get("comment"))

log.warn("MOUNA "+transientVars)

ErrorCollection errorCollection=workflowTransitionUtil.validate()

if (errorCollection.hasAnyErrors()) {

    log.warn("MOUNA here 1 "+errorCollection.getErrorMessages().toString())

    throw new InvalidInputException(errorCollection.getErrors().toString())

return false;

}else{

    ErrorCollection progressErrorCollection=workflowTransitionUtil.progress()

    if(progressErrorCollection.hasAnyErrors()){

        log.warn("MOUNA here 2 "+progressErrorCollection.getErrors().toString())

       throw new InvalidInputException(progressErrorCollection.getErrors().toString())

          return true;

    }else{

      return true;

    }

}

}

//@SuppressWarnings("rawtypes")

  //  Map getPopulatedFieldValuesHolder(WorkflowTransitionUtil workflowTransitionUtil, MutableIssue issue) throws Exception{

  //  Map fieldValuesHolder = new HashMap();

  //  FieldScreenRenderer fieldScreenRenderer = workflowTransitionUtil.getFieldScreenRenderer();

  //  for (FieldScreenRenderTab fieldScreenRenderTab in fieldScreenRenderer.getFieldScreenRenderTabs())

  //    for (FieldScreenRenderLayoutItem fieldScreenRenderLayoutItem in fieldScreenRenderTab.getFieldScreenRenderLayoutItems())

  //      if (fieldScreenRenderLayoutItem.isShow(issue)) {

  //                   fieldScreenRenderLayoutItem.populateFromIssue(fieldValuesHolder, issue);

  //                     log.warn("fieldScreenRenderLayoutItem MOUNA "+fieldScreenRenderLayoutItem.getFieldScreenLayoutItem().getFieldScreenTab().getFieldScreen().getName())

  //       }

  //       return fieldValuesHolder;

  //   }

// String getError(String error){

//   return error;

// }

</code>```

Body:
I am using scriptrunner postfunction and validator to perform 3 transitions back to back. The problem is that I receive an error message saying

[comment:Please, add a comment.] although a comment has actually been adde as you can see in the screenshot

Here is the code I have used, anyone knows how to fix this?

package CombineTransitions

import com.onresolve.scriptrunner.runner.util.UserMessageUtil

import com.atlassian.jira.issue.Issue;

import org.apache.log4j.Logger

import com.atlassian.jira.bc.issue.IssueService

import com.atlassian.jira.issue.Issue;

import CombineTransitions.Configuration_CombineTransitions

import com.atlassian.jira.bc.issue.IssueService.IssueResult

import com.atlassian.jira.bc.issue.IssueService.TransitionValidationResult

import com.atlassian.jira.event.type.EventDispatchOption

import  java.util.concurrent.TimeUnit

import  java.util.concurrent.ScheduledExecutorService

import java.util.concurrent.Executors

import com.atlassian.jira.component.ComponentAccessor

import com.atlassian.jira.issue.MutableIssue

import com.atlassian.jira.workflow.WorkflowTransitionUtil

import com.opensymphony.workflow.WorkflowContext;

import com.atlassian.jira.workflow.WorkflowTransitionUtilImpl;

import com.atlassian.jira.util.JiraUtils;

import com.atlassian.jira.issue.MutableIssue;

import com.atlassian.jira.util.ErrorCollection

import com.atlassian.jira.workflow.WorkflowException

import com.atlassian.jira.issue.fields.CustomField

import com.onresolve.jira.groovy.user.FormField

import com.atlassian.jira.issue.CustomFieldManager

import com.atlassian.jira.component.ComponentAccessor

import com.opensymphony.workflow.InvalidInputException

import com.atlassian.jira.component.ComponentAccessor;

import com.atlassian.jira.issue.MutableIssue;

import com.atlassian.jira.issue.fields.screen.FieldScreenRenderLayoutItem;

import com.atlassian.jira.issue.fields.screen.FieldScreenRenderTab;

import com.atlassian.jira.issue.fields.screen.FieldScreenRenderer;

def log1 = Logger.getLogger("atlassian-jira.log")

def combineTransitionsHashMap= Configuration_CombineTransitions.getCombineTransitionsHashMap()

def issueStatusTypeId = combineTransitionsHashMap["issueStatusTypeId"] as String;

def transitionFromOpentoFixed = combineTransitionsHashMap["transitionFromOpentoFixed"] as Integer;

def transitionFromFixedToTested = combineTransitionsHashMap["transitionFromFixedToTested"] as Integer;

def transitionFromTestedToCompleted = combineTransitionsHashMap["transitionFromTestedToCompleted"] as Integer;

def fixedStatusName = combineTransitionsHashMap["fixedStatusName"] as String;

def testedStatusName = combineTransitionsHashMap["testedStatusName"] as String;

def completedStatusName = combineTransitionsHashMap["completedStatusName"] as String;

def fixedStatusId = combineTransitionsHashMap["fixedStatusId"] as String;

def testedStatusId = combineTransitionsHashMap["testedStatusId"] as String;

def completedStatusId = combineTransitionsHashMap["completedStatusId"] as String;

def errorMessage = combineTransitionsHashMap["errorMessage"] as String;

if (issue.getStatus().getSimpleStatus().getId().equals(issueStatusTypeId)) {

        def ok = false

         ok=performTransition(transitionFromOpentoFixed, fixedStatusName, fixedStatusId, errorMessage);

         log.warn("MOUNA first boolean "+ok +" "+fixedStatusName)

   if(ok){

         ok= performTransition(transitionFromFixedToTested, testedStatusName, testedStatusId, errorMessage);

         log.warn("MOUNA second boolean "+ok +" "+testedStatusName)

         if(ok){

          ok= performTransition(transitionFromTestedToCompleted, completedStatusName, completedStatusId, errorMessage);

          log.warn("MOUNA third boolean "+ok +" "+completedStatusName)

         }

  }

}

def  performTransition(int transitionToBeDone, String destinationStatus, String statusId , String errorMessage) {

  log.warn("MOUNA  ORIGINAL STATUS "+ issue.getStatus()  + "DEST STATUS "+ destinationStatus)

//issue = ComponentAccessor.getIssueManager().getIssueObject(issue.id)

issue = transientVars.get("issue");

  def currentUser = ComponentAccessor.getJiraAuthenticationContext().getLoggedInUser()

  String issueKey = issue.getKey()

  IssueService issueService = ComponentAccessor.getIssueService()

  def issueInputParameters = issueService.newIssueInputParameters()

  issueInputParameters.setComment("Transitioning issue from status "+ issue.getStatus().getName()+" to status "+ destinationStatus );

WorkflowTransitionUtil workflowTransitionUtil = (WorkflowTransitionUtil) JiraUtils.loadComponent(WorkflowTransitionUtilImpl.class)

workflowTransitionUtil.setIssue(issue)

workflowTransitionUtil.setAction(transitionToBeDone)

//workflowTransitionUtil.addAdditionalInput(transientVars.get("comment"))

log.warn("MOUNA "+transientVars)

ErrorCollection errorCollection=workflowTransitionUtil.validate()

if (errorCollection.hasAnyErrors()) {

    log.warn("MOUNA here 1 "+errorCollection.getErrorMessages().toString())

    throw new InvalidInputException(errorCollection.getErrors().toString())

return false;

}else{

    ErrorCollection progressErrorCollection=workflowTransitionUtil.progress()

    if(progressErrorCollection.hasAnyErrors()){

        log.warn("MOUNA here 2 "+progressErrorCollection.getErrors().toString())

       throw new InvalidInputException(progressErrorCollection.getErrors().toString())

          return true;

    }else{

      return true;

    }

}

}

//@SuppressWarnings("rawtypes")

  //  Map getPopulatedFieldValuesHolder(WorkflowTransitionUtil workflowTransitionUtil, MutableIssue issue) throws Exception{

  //  Map fieldValuesHolder = new HashMap();

  //  FieldScreenRenderer fieldScreenRenderer = workflowTransitionUtil.getFieldScreenRenderer();

  //  for (FieldScreenRenderTab fieldScreenRenderTab in fieldScreenRenderer.getFieldScreenRenderTabs())

  //    for (FieldScreenRenderLayoutItem fieldScreenRenderLayoutItem in fieldScreenRenderTab.getFieldScreenRenderLayoutItems())

  //      if (fieldScreenRenderLayoutItem.isShow(issue)) {

  //                   fieldScreenRenderLayoutItem.populateFromIssue(fieldValuesHolder, issue);

  //                     log.warn("fieldScreenRenderLayoutItem MOUNA "+fieldScreenRenderLayoutItem.getFieldScreenLayoutItem().getFieldScreenTab().getFieldScreen().getName())

  //       }

  //       return fieldValuesHolder;

  //   }

// String getError(String error){

//   return error;

// }


问:
AWS MWAA remote logging not visible on Airflow UI
AWS MWAA is configured for remote logging to a given S3 path.

While running tasks(preferably long and time-consuming) in any DAG, we can not see logs either on Airflow UI or the S3 path.

Whenever a task ends(success or failure), we are able to see logs at both places.

Is there any way to see logs while running tasks in case of remote logging?


问:
How to identify screen and canvas coordinates for performing draganddrop using selenium and gojs
I want to perform drag and drop action on a canvas using selenium.
Where the element to be dragged is outside the canvas(i.e., element is outside the canvas panel).

Using .draganddrop() function I see that the element is dragged and is held on the mouse pointer without being dropped. The element is not dropped after providing the canvas id/ canvas coordinates.

I tried performing the drop by providing the browser screen coordinates but understood that the browser coordinates and canvas coordinates differ, so the drop action is not taking place.

Can anyone help be with a solution here.


问:
How to prevent loading of SRC on responsive image
I have issue with my amp-img, that load images from src on any screen sizes againgst from srcset. My code:

```<code>       <amp-img alt="alty"
                 title="title"
                 src="img-1200.webp"
                 width="1280"
                 height="720"
                 layout="responsive"
                 srcset="img-400.webp 400w,  img-856.webp 856w,   img-1200.webp 1200w"
                 sizes="(max-width:700px) calc(100vw-42px), 658px">
                <amp-img alt="alty"
                         title="title"
                         src="img-1200.jpg"
                         fallback
                         width="1280"
                         height="720"
                         layout="responsive"
                         srcset="img-400.jpg  400w,  img-856.jpg 856w,   img-1200.jpg 1200w">

                </amp-img>
        </amp-img>
</code>```

So when site loading, image from preload srcset loaded and image from src loaded. What am I doing wrong?

Body:
I have issue with my amp-img, that load images from src on any screen sizes againgst from srcset. My code:

       <amp-img alt="alty"
                 title="title"
                 src="img-1200.webp"
                 width="1280"
                 height="720"
                 layout="responsive"
                 srcset="img-400.webp 400w,  img-856.webp 856w,   img-1200.webp 1200w"
                 sizes="(max-width:700px) calc(100vw-42px), 658px">
                <amp-img alt="alty"
                         title="title"
                         src="img-1200.jpg"
                         fallback
                         width="1280"
                         height="720"
                         layout="responsive"
                         srcset="img-400.jpg  400w,  img-856.jpg 856w,   img-1200.jpg 1200w">

                </amp-img>
        </amp-img>

So when site loading, image from preload srcset loaded and image from src loaded. What am I doing wrong?


问:
Using the HttpClient from WebApplicationFactory in .NET 6.0 always returns 'Not found' on calling the SendAsync method
We're having an .NET 6.0 WebAPI and are building unittests for it. But somehow the SendAsync method in the UnitTest always returns 'Not found'.
Here's the relevant code:

```<code>      [TestMethod]
        public async Task TestActiviteitCRUD()
        {
            WebApplicationFactory<Program> applicationFactory = new WebApplicationFactory<Program>();
            var client = applicationFactory.CreateClient();
// Activiteit toevoegen
            var testActiviteit = new ActiviteitInsertMetConflicten
            {
                conflicten = new List<Conflict>(),
                activiteitInsert = new ActiviteitInsert
                {
                    Startdatumtijd = System.DateTime.Now.AddDays(1),
                    Einddatumtijd = System.DateTime.Now.AddDays(1).AddMinutes(60),
                    ActiviteittypeId = 9,
                    SpecialistId = 1,
                    SpecialismeId = 1,
                    StandaardtijdblokId = null,
                    ExtraTijd = false,
                    IsHeleDag = false,
                    AandachtsgebiedId = 1,
                    PLANstatusId = 0,
                    HeeftPlanningsConflict = false
                }
            };
            var jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };
            var response = await client.PostAsJsonAsync("/Activiteit", testActiviteit);
            response.EnsureSuccessStatusCode();

</code>```

PostAsJsonAsync works fine (and PutAsJsonAsync also), but further on:

```<code>var actdel = new ActiviteitDeleteMetVraagEnAntwoord();
            actdel.activiteitId = id;
            List<VraagEnAntwoord> vragenEnAntwoorden = new List<VraagEnAntwoord>();
            actdel.vragenEnAntwoorden = vragenEnAntwoorden;
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Delete;
            request.RequestUri = client.BaseAddress;
            request.Content = new StringContent(JsonSerializer.Serialize(actdel), Encoding.UTF8, "application/json");
            response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
</code>```

The last line (response.EnsureSuccessStatusCode();) always returns a 'not found'. And while debugging the UnitTest we can see that the routine to Delete the object is indeed not hit.

But it works fine when we delete an object in another application which calls the same delete-routine in the same web api. In that other application we don't use WebApplicationFactory.
When we use Swagger to test the WebApi it works fine also.
So only in the UnitTest using WebApplicationFactory, we cannot use the SendAsync. What's wrong?
(We cannot use the DeleteAsync method since we need to send a whole object)

Body:
We're having an .NET 6.0 WebAPI and are building unittests for it. But somehow the SendAsync method in the UnitTest always returns 'Not found'.
Here's the relevant code:

      [TestMethod]
        public async Task TestActiviteitCRUD()
        {
            WebApplicationFactory<Program> applicationFactory = new WebApplicationFactory<Program>();
            var client = applicationFactory.CreateClient();
// Activiteit toevoegen
            var testActiviteit = new ActiviteitInsertMetConflicten
            {
                conflicten = new List<Conflict>(),
                activiteitInsert = new ActiviteitInsert
                {
                    Startdatumtijd = System.DateTime.Now.AddDays(1),
                    Einddatumtijd = System.DateTime.Now.AddDays(1).AddMinutes(60),
                    ActiviteittypeId = 9,
                    SpecialistId = 1,
                    SpecialismeId = 1,
                    StandaardtijdblokId = null,
                    ExtraTijd = false,
                    IsHeleDag = false,
                    AandachtsgebiedId = 1,
                    PLANstatusId = 0,
                    HeeftPlanningsConflict = false
                }
            };
            var jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };
            var response = await client.PostAsJsonAsync("/Activiteit", testActiviteit);
            response.EnsureSuccessStatusCode();

PostAsJsonAsync works fine (and PutAsJsonAsync also), but further on:

var actdel = new ActiviteitDeleteMetVraagEnAntwoord();
            actdel.activiteitId = id;
            List<VraagEnAntwoord> vragenEnAntwoorden = new List<VraagEnAntwoord>();
            actdel.vragenEnAntwoorden = vragenEnAntwoorden;
            var request = new HttpRequestMessage();
            request.Method = HttpMethod.Delete;
            request.RequestUri = client.BaseAddress;
            request.Content = new StringContent(JsonSerializer.Serialize(actdel), Encoding.UTF8, "application/json");
            response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();

The last line (response.EnsureSuccessStatusCode();) always returns a 'not found'. And while debugging the UnitTest we can see that the routine to Delete the object is indeed not hit.

But it works fine when we delete an object in another application which calls the same delete-routine in the same web api. In that other application we don't use WebApplicationFactory.
When we use Swagger to test the WebApi it works fine also.
So only in the UnitTest using WebApplicationFactory, we cannot use the SendAsync. What's wrong?
(We cannot use the DeleteAsync method since we need to send a whole object)


问:
Visual Studio Code: Markdown: How can I enclose a highlighted word with backticks?
If I select a word (e.g. by double-clicking on the word) in order to then enclose it with backticks, the word is deleted as soon as I type a backtick, and only when I press Cmd+z do I get the desired effect. How can I avoid the Cmd+z and when pressing backtick directly get the word wrapped with backticks? I use a Mac and a German keyboard.</p>