问:
How do I make an api call to the existing event route in react.js?

const dashboardRoutes = []
let userListing = []
let reg_users = []

const useStyles = makeStyles(styles)

// Build the Registrants Listing Page
export default function RegistrantsListingPage(props) {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [usersPerPage, setUsersPerPage] = useState(10)
  const [offset, setOffset] = useState(0)
  const [totalUsers, setTotalUsers] = useState(0)
  const [isOrganizer, checkOrganizer] = useState(false)

  const { eventid } = props.location.state
  const { theUser } = props.location.state
  const classes = useStyles()
  const { ...rest } = props
  const eventQuery = /[^-]*$/.exec(eventid)[0]
  // get current data
  const indexOfLastUser = currentPage * usersPerPage
  const indexOfFirstUser = indexOfLastUser - usersPerPage

  // change page
  const paginate = async pageNumber => {
    setCurrentPage(pageNumber)
    let newOffset = (pageNumber - 1) * parseInt(usersPerPage)
    setOffset(newOffset)
    setLoading(true)
    await getAPageOfUsers(usersPerPage, newOffset)
    setLoading(false)
  }

  const nextPage = async pageNumber => {
    setCurrentPage(pageNumber + 1)
    let newOffset = parseInt(offset) + parseInt(usersPerPage)
    setOffset(newOffset)
    setLoading(true)
    await getAPageOfUsers(usersPerPage, newOffset)
    setLoading(false)
  }

  const prevPage = async pageNumber => {
    setCurrentPage(pageNumber - 1)
    let newOffset = parseInt(offset) - parseInt(usersPerPage)
    setOffset(newOffset)
    setLoading(true)
    await getAPageOfUsers(usersPerPage, newOffset)
    setLoading(false)
  }

  // change number of users per page
  const changeNumberOfUsersPerPage = async e => {
    setCurrentPage(1)
    const limit = e.target.value
    setUsersPerPage(limit)
    setOffset(0)
    setLoading(true)
    await getAPageOfUsers(usersPerPage, 0)
    setLoading(false)
  }

  // get data of the page,
  // check if the user is event organizer and get a listing of all registered users
  const getData = async (usersPerPage, offset) => {
    try {
      const response = await axios.post(process.env.REACT_APP_API_ADDRESS + 'api/events/query', {
        id: eventQuery,
      })

      // check if the user is event organizer
      determineOrganizer(response.data[0].organizer)

      // get registered users data
      if (response.data[0].registered_users) {
        await buildUserList(response.data[0].registered_users, usersPerPage, offset)
      }
    } catch (error) {
      console.error(error)
    }
  }

  const determineOrganizer = organizers => {
    if (organizers) {
      let organizer_list = organizers
      // Convert String to array
      organizer_list = organizer_list.replaceAll('[', '').replaceAll(']', '').replaceAll("'", '').split(', ')
      for (var i = 0; i < organizer_list.length; i++) {
        if (organizer_list[i] == theUser?.sub) {
          checkOrganizer(true)
        }
      }
    }
  }

  const buildUserList = async (registered_users, usersPerPage, offset) => {
    registered_users = registered_users.slice(5)
    // Convert String to array
    reg_users = registered_users.replaceAll('[', '').replaceAll(']', '').replaceAll("'", '').split(', ')
    await getAPageOfUsers(usersPerPage, offset)
    setTotalUsers(reg_users.length)
  }

  // get a list of users that will be display in current page
  const getAPageOfUsers = async (usersPerPage, offset) => {
    var aPageOfList = []
    for (var i = offset; i < offset + usersPerPage; i++) {
      if (reg_users[i]) {
        aPageOfList.push(reg_users[i])
      } else {
        break
      }
    }
    await getRegisteredUserData(aPageOfList)
  }

  const getRegisteredUserData = async users => {
    try {
      const response = await axios.post(process.env.REACT_APP_API_ADDRESS + 'api/users_multiquery_by_id', {
        user_list: users,
      })
      setData(response.data)
    } catch (error) {
      console.error(error)
    }
  }

  useEffect(async () => {
    try {
      // set loading to true before getting the data
      setLoading(true)
      await getData(usersPerPage, offset)
      // switch loading to false after getting the data
      setLoading(false)
    } catch (error) {
      // add error handling here
      setLoading(false)
    }
  }, [usersPerPage])

  if (data) {
    userListing = Object.values(data).map((data, i) => (

        <Link to={`/user/${data.username}`}>

        </Link>

{data.username}

        {isOrganizer ?
{data.email}
 : <></>}

    ))
  }
  return (
    <>
      {loading ? (

      ) : (
        <>
          <Header
            color='transparent'
            routes={dashboardRoutes}
            brand='Guild Gaming'
            rightLinks={<HeaderLinks />}
            fixed
            changeColorOnScroll={{
              height: 400,
              color: 'white',
            }}
            {...rest}
          />
          <Parallax filter image={require('assets/img/TempHome/GG_Home_Hero_Background.png').default}></Parallax>

                    Page {currentPage} (results {indexOfFirstUser + 1}-{totalUsers > usersPerPage ? indexOfLastUser : totalUsers} of {totalUsers})

                  <Pages
                    perPage={usersPerPage}
                    total={totalUsers}
                    paginate={paginate}
                    currentPage={currentPage}
                    prevPage={prevPage}
                    nextPage={nextPage}
                  />

USERNAME

                  {isOrganizer ?
EMAIL
 : <></>}

                {userListing}

                    Page {currentPage} (results {indexOfFirstUser + 1}-{totalUsers > usersPerPage ? indexOfLastUser : totalUsers} of {totalUsers})

                  <Pages
                    perPage={usersPerPage}
                    total={totalUsers}
                    paginate={paginate}
                    currentPage={currentPage}
                    prevPage={prevPage}
                    nextPage={nextPage}
                  />

        </>
      )}
    </>
  )
}```

Working on a site and users can create an event. Other users can register for the event. you can click on created events to get more detail. there is a box that displays registrants with a "view more' button. When you click "view more" on an event's registrants it takes you to a page that properly shows who is registered. However, this is not a unique URL and thus can not be shared. It must be accessed by clicking "View More".  How can you make the registrants page a unique url?

I'll most likely need the registrants page to do an api call to the existing event route that way you can access the registrants. I'm just not sure how. got some code snippets from the registrants page.

Body:
const dashboardRoutes = []
let userListing = []
let reg_users = []

const useStyles = makeStyles(styles)

// Build the Registrants Listing Page
export default function RegistrantsListingPage(props) {
  const [loading, setLoading] = useState(true)
  const [data, setData] = useState(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [usersPerPage, setUsersPerPage] = useState(10)
  const [offset, setOffset] = useState(0)
  const [totalUsers, setTotalUsers] = useState(0)
  const [isOrganizer, checkOrganizer] = useState(false)

  const { eventid } = props.location.state
  const { theUser } = props.location.state
  const classes = useStyles()
  const { ...rest } = props
  const eventQuery = /[^-]*$/.exec(eventid)[0]
  // get current data
  const indexOfLastUser = currentPage * usersPerPage
  const indexOfFirstUser = indexOfLastUser - usersPerPage

  // change page
  const paginate = async pageNumber => {
    setCurrentPage(pageNumber)
    let newOffset = (pageNumber - 1) * parseInt(usersPerPage)
    setOffset(newOffset)
    setLoading(true)
    await getAPageOfUsers(usersPerPage, newOffset)
    setLoading(false)
  }

  const nextPage = async pageNumber => {
    setCurrentPage(pageNumber + 1)
    let newOffset = parseInt(offset) + parseInt(usersPerPage)
    setOffset(newOffset)
    setLoading(true)
    await getAPageOfUsers(usersPerPage, newOffset)
    setLoading(false)
  }

  const prevPage = async pageNumber => {
    setCurrentPage(pageNumber - 1)
    let newOffset = parseInt(offset) - parseInt(usersPerPage)
    setOffset(newOffset)
    setLoading(true)
    await getAPageOfUsers(usersPerPage, newOffset)
    setLoading(false)
  }

  // change number of users per page
  const changeNumberOfUsersPerPage = async e => {
    setCurrentPage(1)
    const limit = e.target.value
    setUsersPerPage(limit)
    setOffset(0)
    setLoading(true)
    await getAPageOfUsers(usersPerPage, 0)
    setLoading(false)
  }

  // get data of the page,
  // check if the user is event organizer and get a listing of all registered users
  const getData = async (usersPerPage, offset) => {
    try {
      const response = await axios.post(process.env.REACT_APP_API_ADDRESS + 'api/events/query', {
        id: eventQuery,
      })

      // check if the user is event organizer
      determineOrganizer(response.data[0].organizer)

      // get registered users data
      if (response.data[0].registered_users) {
        await buildUserList(response.data[0].registered_users, usersPerPage, offset)
      }
    } catch (error) {
      console.error(error)
    }
  }

  const determineOrganizer = organizers => {
    if (organizers) {
      let organizer_list = organizers
      // Convert String to array
      organizer_list = organizer_list.replaceAll('[', '').replaceAll(']', '').replaceAll("'", '').split(', ')
      for (var i = 0; i < organizer_list.length; i++) {
        if (organizer_list[i] == theUser?.sub) {
          checkOrganizer(true)
        }
      }
    }
  }

  const buildUserList = async (registered_users, usersPerPage, offset) => {
    registered_users = registered_users.slice(5)
    // Convert String to array
    reg_users = registered_users.replaceAll('[', '').replaceAll(']', '').replaceAll("'", '').split(', ')
    await getAPageOfUsers(usersPerPage, offset)
    setTotalUsers(reg_users.length)
  }

  // get a list of users that will be display in current page
  const getAPageOfUsers = async (usersPerPage, offset) => {
    var aPageOfList = []
    for (var i = offset; i < offset + usersPerPage; i++) {
      if (reg_users[i]) {
        aPageOfList.push(reg_users[i])
      } else {
        break
      }
    }
    await getRegisteredUserData(aPageOfList)
  }

  const getRegisteredUserData = async users => {
    try {
      const response = await axios.post(process.env.REACT_APP_API_ADDRESS + 'api/users_multiquery_by_id', {
        user_list: users,
      })
      setData(response.data)
    } catch (error) {
      console.error(error)
    }
  }

  useEffect(async () => {
    try {
      // set loading to true before getting the data
      setLoading(true)
      await getData(usersPerPage, offset)
      // switch loading to false after getting the data
      setLoading(false)
    } catch (error) {
      // add error handling here
      setLoading(false)
    }
  }, [usersPerPage])

  if (data) {
    userListing = Object.values(data).map((data, i) => (

        <Link to={`/user/${data.username}`}>

        </Link>

{data.username}

        {isOrganizer ?
{data.email}
 : <></>}

    ))
  }
  return (
    <>
      {loading ? (

      ) : (
        <>
          <Header
            color='transparent'
            routes={dashboardRoutes}
            brand='Guild Gaming'
            rightLinks={<HeaderLinks />}
            fixed
            changeColorOnScroll={{
              height: 400,
              color: 'white',
            }}
            {...rest}
          />
          <Parallax filter image={require('assets/img/TempHome/GG_Home_Hero_Background.png').default}></Parallax>

                    Page {currentPage} (results {indexOfFirstUser + 1}-{totalUsers > usersPerPage ? indexOfLastUser : totalUsers} of {totalUsers})

                  <Pages
                    perPage={usersPerPage}
                    total={totalUsers}
                    paginate={paginate}
                    currentPage={currentPage}
                    prevPage={prevPage}
                    nextPage={nextPage}
                  />

USERNAME

                  {isOrganizer ?
EMAIL
 : <></>}

                {userListing}

                    Page {currentPage} (results {indexOfFirstUser + 1}-{totalUsers > usersPerPage ? indexOfLastUser : totalUsers} of {totalUsers})

                  <Pages
                    perPage={usersPerPage}
                    total={totalUsers}
                    paginate={paginate}
                    currentPage={currentPage}
                    prevPage={prevPage}
                    nextPage={nextPage}
                  />

        </>
      )}
    </>
  )
}

Working on a site and users can create an event. Other users can register for the event. you can click on created events to get more detail. there is a box that displays registrants with a "view more' button. When you click "view more" on an event's registrants it takes you to a page that properly shows who is registered. However, this is not a unique URL and thus can not be shared. It must be accessed by clicking "View More".  How can you make the registrants page a unique url?

I'll most likely need the registrants page to do an api call to the existing event route that way you can access the registrants. I'm just not sure how. got some code snippets from the registrants page.


来源: stackexchange

问:
I dont run app with Xcode 12.2 in my Apple Mini (M1)
I'm trying to run the app Flutter in Xcode, but I can't resolve this error. Can anyone help me, I really need it!

Version of Xcode is 14.2
flutter version 3.3.10

Message error is: failed to emit precompiled header '/Users/user/Library/Developer/Xcode/DerivedData/Runner-ahobejjqxbhfiqgqrlaokhilvbqh/Build/Intermediates.noindex/PrecompiledHeaders/Runner-Bridging-Header-swift_2W9KP0PRUO8P6-clang_3VZ8C5641AQ68.pch' for bridging header '/Users/user/Documents/develop/my_project/ios/Runner/Runner-Bridging-Header.h'

and
/Users/user/Documents/develop/my_project/ios/Runner/GeneratedPluginRegistrant.h:10:9 'Flutter/Flutter.h' file not found

[✓] Flutter (Channel stable, 3.3.10, on macOS 13.0.1 22A400 darwin-arm, locale
pt-BR)
• Flutter version 3.3.10 on channel stable at
/Users/user/Downloads/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 135454af32 (4 weeks ago), 2022-12-15 07:36:55 -0800
• Engine revision 3316dd8728
• Dart version 2.18.6
• DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
• Android SDK at /Users/user/Library/Android/sdk
• Platform android-33-ext4, build-tools 33.0.1
• Java binary at: /Applications/Android
Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 14C18
• CocoaPods version 1.11.3

[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.3)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)

[✓] VS Code (version 1.74.2)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.56.0

[✓] VS Code (version 1.74.2)
• VS Code at /Users/user/Downloads/Visual Studio Code.app/Contents
• Flutter extension version 3.56.0

[✓] Connected device (5 available)
• sdk gphone64 arm64 (mobile) • emulator-5554                            •
android-arm64  • Android 13 (API 33) (emulator)

ios            • iOS 15.7.1 19H117
• iPhone 14 Pro Max (mobile)   •
ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator)
• macOS (desktop)             • macos                         •
darwin-arm64   • macOS 13.0.1 22A400 darwin-arm
• Chrome (web)                • chrome                                   •
web-javascript • Google Chrome

[✓] HTTP Host Availability
• All required HTTP hosts are available

enter image description here

i  try run my app with commands

```<code>flutter clean
flutter pub get
cd ios
pod install
pod repo update
rm -Rf Flutter\flutter.podspec
pod install
</code>```

but nothing worked

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to run the app Flutter in Xcode, but I can't resolve this error. Can anyone help me, I really need it!

Version of Xcode is 14.2
flutter version 3.3.10

Message error is: failed to emit precompiled header '/Users/user/Library/Developer/Xcode/DerivedData/Runner-ahobejjqxbhfiqgqrlaokhilvbqh/Build/Intermediates.noindex/PrecompiledHeaders/Runner-Bridging-Header-swift_2W9KP0PRUO8P6-clang_3VZ8C5641AQ68.pch' for bridging header '/Users/user/Documents/develop/my_project/ios/Runner/Runner-Bridging-Header.h'

and
/Users/user/Documents/develop/my_project/ios/Runner/GeneratedPluginRegistrant.h:10:9 'Flutter/Flutter.h' file not found

[✓] Flutter (Channel stable, 3.3.10, on macOS 13.0.1 22A400 darwin-arm, locale
pt-BR)
• Flutter version 3.3.10 on channel stable at
/Users/user/Downloads/flutter
• Upstream repository https://github.com/flutter/flutter.git
• Framework revision 135454af32 (4 weeks ago), 2022-12-15 07:36:55 -0800
• Engine revision 3316dd8728
• Dart version 2.18.6
• DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
• Android SDK at /Users/user/Library/Android/sdk
• Platform android-33-ext4, build-tools 33.0.1
• Java binary at: /Applications/Android
Studio.app/Contents/jre/Contents/Home/bin/java
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)
• All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
• Xcode at /Applications/Xcode.app/Contents/Developer
• Build 14C18
• CocoaPods version 1.11.3

[✓] Chrome - develop for the web
• Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.3)
• Android Studio at /Applications/Android Studio.app/Contents
• Flutter plugin can be installed from:
 https://plugins.jetbrains.com/plugin/9212-flutter
• Dart plugin can be installed from:
 https://plugins.jetbrains.com/plugin/6351-dart
• Java version OpenJDK Runtime Environment (build
11.0.13+0-b1751.21-8125866)

[✓] VS Code (version 1.74.2)
• VS Code at /Applications/Visual Studio Code.app/Contents
• Flutter extension version 3.56.0

[✓] VS Code (version 1.74.2)
• VS Code at /Users/user/Downloads/Visual Studio Code.app/Contents
• Flutter extension version 3.56.0

[✓] Connected device (5 available)
• sdk gphone64 arm64 (mobile) • emulator-5554                            •
android-arm64  • Android 13 (API 33) (emulator)

ios            • iOS 15.7.1 19H117
• iPhone 14 Pro Max (mobile)   •
ios            • com.apple.CoreSimulator.SimRuntime.iOS-16-2 (simulator)
• macOS (desktop)             • macos                         •
darwin-arm64   • macOS 13.0.1 22A400 darwin-arm
• Chrome (web)                • chrome                                   •
web-javascript • Google Chrome

[✓] HTTP Host Availability
• All required HTTP hosts are available

enter image description here

i  try run my app with commands

flutter clean
flutter pub get
cd ios
pod install
pod repo update
rm -Rf Flutter\flutter.podspec
pod install

but nothing worked


问:
Disable screenshot of a pdf in React (web)
In our web application, we are using react-pdf to display different PDFs.

For one of the PDF, there is a requirement that we should not allow user to take screenshot. We are not using React-native.

Now I know that we cannot stop user from taking screenshot as it is not handled by browser, but can we show a black or white screen when the user views the screenshot.

Currently, I have disabled right click and save via print, but the screenshot part is tricky.

This is what happens in Netflix and Prime video, but I want to implement it for PDF.

If anyone has implemented or have any ideas about such functionality, please help.

Read about DRM as well but not sure how to implement it and if it will work for PDF

Edit
The purpose is not to edit pdf but to provide a black screen when user views the screenshot taken


问:
Swiper Angular slideNext() not going to next slide with given duration
I'm attempting to use Angular Swiper to do a custom slideshow. Some of the elements on the slideshow can include images, videos and text.

Currently using a for loop with a setInterval to go through the slides and their given duration.
Problem: It applies the first element's duration to all the slides and not the current slides' duration.

For example, if the array starts with a video and the duration is 30 seconds, all the slides will have a duration of 30 seconds. What's odd is that, every element on the array (confirmed by logs, still keeps it's duration) however, the interval only goes based on the first one.

Here's the startSlideShow function that configures the interval and display:

```<code>startSlideshow() {

    //var
    let shuffledSlides = this.shuffle(this.slides);
    //var

    console.log("Start Slideshow.");
    console.log(this.slides);

    for (let i = 0; i < shuffledSlides.length; i++) {
      setInterval(() => {

        console.log("this.slides[i].duration");
        console.log(shuffledSlides[i].duration);

        if (this.componentRef && this.componentRef.swiperRef) {
          this.componentRef.swiperRef.slideNext();
        }
      }, shuffledSlides[i].duration);
    }

  }
</code>```

Body:
I'm attempting to use Angular Swiper to do a custom slideshow. Some of the elements on the slideshow can include images, videos and text.

Currently using a for loop with a setInterval to go through the slides and their given duration.
Problem: It applies the first element's duration to all the slides and not the current slides' duration.

For example, if the array starts with a video and the duration is 30 seconds, all the slides will have a duration of 30 seconds. What's odd is that, every element on the array (confirmed by logs, still keeps it's duration) however, the interval only goes based on the first one.

Here's the startSlideShow function that configures the interval and display:

startSlideshow() {

    //var
    let shuffledSlides = this.shuffle(this.slides);
    //var

    console.log("Start Slideshow.");
    console.log(this.slides);

    for (let i = 0; i < shuffledSlides.length; i++) {
      setInterval(() => {

        console.log("this.slides[i].duration");
        console.log(shuffledSlides[i].duration);

        if (this.componentRef && this.componentRef.swiperRef) {
          this.componentRef.swiperRef.slideNext();
        }
      }, shuffledSlides[i].duration);
    }

  }


问:
Override GridActionsCellItem showInMenu icon
How can I change the 3 dots icon generated by showInMenu so it's a text button instead?

Currently the DataGrid shows:

I want to replace the 3 dots with:

To arrive at the same result for the drop down:

Code:

```<code>    const toggleAdmin = useCallback(
        (id) => () => {
            setRows((prevRows) =>
                prevRows.map((row) =>
                    row.id === id ? { ...row, isAdmin: !row.isAdmin } : row,
                ),
            );
        },
        [],
    );

    const duplicateUser = useCallback(
        (id) => () => {
            setRows((prevRows) => {
                const rowToDuplicate = prevRows.find((row) => row.id === id);
                return [...prevRows, { ...rowToDuplicate, id: Date.now() }];
            });
        },
        [],
    );

    const columns = useMemo(
        () => [
        {
            field: 'actions',
            headerName: "Action",
            type: 'actions',
            width: 80,
            getActions: (params) => [
                <GridActionsCellItem
                    icon={<SomeIcon />}
                    label="Option 1"
                    onClick={toggleAdmin(params.id)}
                    showInMenu
                />
                <GridActionsCellItem
                    icon={<SomeIcon/>}
                    label="Option 2"
                    onClick={duplicateUser(params.id)}
                    showInMenu
                />,
            ],
        },
        ],
        [toggleAdmin, duplicateUser],
    );

    <DataGrid columns={columns} rows={someRows} components={{ Toolbar: GridToolbar }}/>

</code>```

Body:
How can I change the 3 dots icon generated by showInMenu so it's a text button instead?

Currently the DataGrid shows:

I want to replace the 3 dots with:

To arrive at the same result for the drop down:

Code:

    const toggleAdmin = useCallback(
        (id) => () => {
            setRows((prevRows) =>
                prevRows.map((row) =>
                    row.id === id ? { ...row, isAdmin: !row.isAdmin } : row,
                ),
            );
        },
        [],
    );

    const duplicateUser = useCallback(
        (id) => () => {
            setRows((prevRows) => {
                const rowToDuplicate = prevRows.find((row) => row.id === id);
                return [...prevRows, { ...rowToDuplicate, id: Date.now() }];
            });
        },
        [],
    );

    const columns = useMemo(
        () => [
        {
            field: 'actions',
            headerName: "Action",
            type: 'actions',
            width: 80,
            getActions: (params) => [
                <GridActionsCellItem
                    icon={<SomeIcon />}
                    label="Option 1"
                    onClick={toggleAdmin(params.id)}
                    showInMenu
                />
                <GridActionsCellItem
                    icon={<SomeIcon/>}
                    label="Option 2"
                    onClick={duplicateUser(params.id)}
                    showInMenu
                />,
            ],
        },
        ],
        [toggleAdmin, duplicateUser],
    );

    <DataGrid columns={columns} rows={someRows} components={{ Toolbar: GridToolbar }}/>


问:
When I'm pressing the "log in" tab, its returning, and I cant log in
This is my controller:

```<code>namespace MyNewStore.Controllers
{
  public class UserAuthenticationController : Controller
  {
    private IUserAuthenticationService authService;
    public UserAuthenticationController(IUserAuthenticationService authService)
    {
        this.authService = authService;
    }

    public async Task<IActionResult> Resgister()
    {
       var model = new Registration
        {
           Email = "admin@gmail.com",
           Username = "admin",
            Name = "Zeinab",
            Password = "Admin@123",
            PasswordConfirm = "Admin@123",
            Role = "Admin"
        };
       // if we want to register with user, we can change the Role, Role="User"
        var result = await authService.RegisterAsync(model);
        return Ok(result.Message);
    }

  public async Task<IActionResult> Login()
  {
   return View();
  }

    [HttpPost]
   public async Task<IActionResult> Login(Login model)
   {
       if (!ModelState.IsValid)
            return View(model);

        var result = await authService.LoginAsync(model);
        if (result.StatusCode == 1)
            return RedirectToAction("Index", "Home");

        else
        {
            TempData["msg"] = "Could not logged in.";
            return RedirectToAction(nameof(Login));
        }
   }

    public async Task<IActionResult> Logout()
    {
        await authService.LogoutAsync();
        return RedirectToAction(nameof(Login));
    }
  }
}
</code>```

When I'm pressing log in, its taking me back, and never log in, is there anyone who can help me with it?

I tried on YouTube
I asked my colleagues
Even I watched many demonstration videos but it didn't help

Body:
This is my controller:

namespace MyNewStore.Controllers
{
  public class UserAuthenticationController : Controller
  {
    private IUserAuthenticationService authService;
    public UserAuthenticationController(IUserAuthenticationService authService)
    {
        this.authService = authService;
    }

    public async Task<IActionResult> Resgister()
    {
       var model = new Registration
        {
           Email = "admin@gmail.com",
           Username = "admin",
            Name = "Zeinab",
            Password = "Admin@123",
            PasswordConfirm = "Admin@123",
            Role = "Admin"
        };
       // if we want to register with user, we can change the Role, Role="User"
        var result = await authService.RegisterAsync(model);
        return Ok(result.Message);
    }

  public async Task<IActionResult> Login()
  {
   return View();
  }

    [HttpPost]
   public async Task<IActionResult> Login(Login model)
   {
       if (!ModelState.IsValid)
            return View(model);

        var result = await authService.LoginAsync(model);
        if (result.StatusCode == 1)
            return RedirectToAction("Index", "Home");

        else
        {
            TempData["msg"] = "Could not logged in.";
            return RedirectToAction(nameof(Login));
        }
   }

    public async Task<IActionResult> Logout()
    {
        await authService.LogoutAsync();
        return RedirectToAction(nameof(Login));
    }
  }
}

When I'm pressing log in, its taking me back, and never log in, is there anyone who can help me with it?

I tried on YouTube
I asked my colleagues
Even I watched many demonstration videos but it didn't help


问:
How to fetch prayer time data from Jakim-API and display to textview in android studio (java)
hello i'm new to programming and android studio. i currently trying to build an apps which will display prayer time based on current location. i don't know how to fetch the data from this API
https://zaimramlan.github.io/waktu-solat-api/#apiprayer_times_list

the apps will display muslim prayer time based on location.
user required to click a button to detect the location, then the prayer time of subuh, zuhr, asar, magrib and isya will be displayed as textview.

can anybody help me show step by step on how to fetch the data from this API. i've tried volley and retrofit. but i dont know how to

JAKIM waktu solat API - https://zaimramlan.github.io/waktu-solat-api/#apiprayer_times_list


问:
ADF Copy Data activity fails with a misleading error message
I have a tab-delimited txt file that has 1.8 million rows. I am converting the txt file to parquet on the azure datalake storage.

ADF throws an error when reading a line around 505k line; however when I split the file into 3 files with 600k lines, everything goes through without any problem.

I was wondering if this is a bug and anyone has encountered this before and if so, whether there is a workaround to convert the file in one shot instead of splitting?

this is the error message:

found more columns than expected column count 156


问:
Shopify Turbo theme Collection colour swatches
I've been trying to add the colour swatches from a product variant on the collection pages in Shopify- enabling in theme settings does not work. so its clearly not coded into the liquid files.

I tried adding:

```<code>{% render 'collection_swatch' %}
</code>```

to the product-loop.liquid file - right under the thumbnail. where it should appear, and this does not work.

Oddly, it does show up on featured items on home page, but not on any collection pages.

the contents of the collection_swatch snippet appear to be correct:

```<code>{% if settings.collection_swatches %}
{%- assign file_extension = 'png' -%}

{% for option in product.options %}
{%- assign downcased_option = option | downcase -%}

{% if downcased_option contains 'color' or downcased_option contains 'colour' %}
  {%- assign option_index = forloop.index0 -%}
  {%- assign values = '' -%}

  <div class="collection_swatches">
    {% for variant in product.variants %}
      {%- assign value = variant.options[option_index] -%}

      {% unless values contains value %}
        {%- assign values = values | join: ',' -%}
        {%- assign values = values | append: ',' | append: value -%}
        {%- assign values = values | split: ',' -%}

        <a href="{{ variant.url | within: collection }}" class="swatch" data-swatch-name="meta-{{ downcased_option }}_{{ value | replace: ' ', '_' | downcase }}">
          <span {% if section.settings.products_per_row == 2 %}data-image="{{ variant.featured_image | product_img_url: '600x' }}"{% elsif section.settings.products_per_row == 3 %}data-image="{{ variant.featured_image | product_img_url: '500x' }}"{% else %}data-image="{{ variant.featured_image | product_img_url: '400x' }}"{% endif %} style="background-image: url({{ value | handle | append: '.' | append: file_extension | asset_img_url: '50x' | prepend: 'https:' }}); background-color: {{ value | split: ' ' | last | handle }};">
          </span>
        </a>
      {% endunless %}
    {% endfor %}
  </div>
{% endif %}
</code>```

{% endfor %}
{% endif %}

So the swatches do appear in other places, but not on the collection pages.
Any thoughts would be appreciated, thanks!

Body:
I've been trying to add the colour swatches from a product variant on the collection pages in Shopify- enabling in theme settings does not work. so its clearly not coded into the liquid files.

I tried adding:

{% render 'collection_swatch' %}

to the product-loop.liquid file - right under the thumbnail. where it should appear, and this does not work.

Oddly, it does show up on featured items on home page, but not on any collection pages.

the contents of the collection_swatch snippet appear to be correct:

{% if settings.collection_swatches %}
{%- assign file_extension = 'png' -%}

{% for option in product.options %}
{%- assign downcased_option = option | downcase -%}

{% if downcased_option contains 'color' or downcased_option contains 'colour' %}
  {%- assign option_index = forloop.index0 -%}
  {%- assign values = '' -%}

    {% for variant in product.variants %}
      {%- assign value = variant.options[option_index] -%}

      {% unless values contains value %}
        {%- assign values = values | join: ',' -%}
        {%- assign values = values | append: ',' | append: value -%}
        {%- assign values = values | split: ',' -%}

          <span {% if section.settings.products_per_row == 2 %}data-image="{{ variant.featured_image | product_img_url: '600x' }}"{% elsif section.settings.products_per_row == 3 %}data-image="{{ variant.featured_image | product_img_url: '500x' }}"{% else %}data-image="{{ variant.featured_image | product_img_url: '400x' }}"{% endif %} style="background-image: url({{ value | handle | append: '.' | append: file_extension | asset_img_url: '50x' | prepend: 'https:' }}); background-color: {{ value | split: ' ' | last | handle }};">

      {% endunless %}
    {% endfor %}

{% endif %}

{% endfor %}
{% endif %}

So the swatches do appear in other places, but not on the collection pages.
Any thoughts would be appreciated, thanks!


问:
API Call using Boilerplate code in Flutter
I'm trying to move towards writing structured Flutter code and this is my first attempt at it. My idea is to create a Boilerplate API class that will make API calls as per the endpoints passed and return a response accordingly. However, right now I'm facing a couple of issues. Here is my code:

The boilerplate API Class:

```<code>class NetworkServices {
  Future<dynamic> postLoginRequest(
      String url, dynamic data, BuildContext context) async {
    var jsonResponse;

    try {
      final response = await http.post(Uri.parse(url),
          body: json.encode(data),
          headers: {
            'Content-Type': 'application/json'
          }).timeout(const Duration(seconds: 30));
      jsonResponse = returnResponse(response);
      print('FROM NETWORK: $jsonResponse');   //Error message given below

    } on SocketException {
      Flushbar(
        leftBarIndicatorColor: Colors.red,
        icon: const Icon(Icons.warning, color: Colors.white),
        message: 'Ooops!!! Something went wrong',
      ).show(context);
    }
    return jsonResponse;
  }

  dynamic returnResponse(http.Response response) {
    if (response.statusCode >= 200 && response.statusCode <= 300) {
      dynamic jsonResponse = json.decode(response.body);
      return jsonResponse;
    } else if (response.statusCode >= 400 || response.statusCode == 404) {
      return 'An Error Occured';
    } else if (response.statusCode >= 404) {
      return 'Invalid Request';
    } else {
      return 'Error Occured While Communicating with Servers!!! Please try again later';
    }
  }
}
</code>```

The API call always tends to think that the API had a status call of 400 or 404. Although, this API works fine elsewhere. This is what it prints:

```<code>I/flutter (19427): FROM NETWORK: An Error Occured
</code>```

This here is the Controller Class:

```<code>class LoginController with ChangeNotifier {
  NetworkServices networkServices = NetworkServices();
  dynamic _loginResponse;

  dynamic get loginResponse {
    return _loginResponse;
  }

  Future<void> login(dynamic data, BuildContext context) async {
    Loader(true);
    networkServices
        .postLoginRequest(ApiUrl.loginUrl, data, context)
        .then((value) {
      Loader(false);
      _loginResponse = value;
      print('SUCCESS $_loginResponse');      //SUCCESS Message
      Flushbar(
        message: _loginResponse['data']['access_token'],
      ).show(context);
    }).onError((error, stackTrace) {
      Loader(false);
      print('ERRROR: $error');         //ERROR Message

      Flushbar(
        leftBarIndicatorColor: AppColors.buttonColor,
        message: error.toString(),
      ).show(context);
    });
    notifyListeners();
  }
}
</code>```

In the controller class, for some strange reason, both the SUCCESS AND ERROR Messages get printed contradicting my idea that only a portion of it would get printed depending on whether the API call was successful or failed.
The messages I get for both says:

```<code>I/flutter (19427): SUCCESS An Error Occured
I/flutter (19427): ERRROR: type 'String' is not a subtype of type 'int' of 'index'
</code>```

This is the code for the UI where it all gets called:

```<code>class LoginScreen extends StatelessWidget {
  GlobalKey<FormState> _key = GlobalKey<FormState>();
  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Form(
            key: key,
            child: Column(
              children: [
                TextFormField(
                  controller: usernameController,
                ),
                SizedBox(height: MediaQuerySetter.getHeight(context) * 0.05),
                TextFormField(
                  controller: passwordController,
                )
              ],
            ),
          ),
                SizedBox(height: MediaQuerySetter.getHeight(context) * 0.05),

          ButtonDesign('Login', () {
            Map<String, dynamic> data = {
              'email': usernameController.text,
              'password': passwordController.text
            };

            Provider.of<LoginController>(context, listen: false)
                .login(data, context);
          })
        ],
      ),
    );
  }
}
</code>```

I intend to use a common button widget throughout the app:

```<code>class ButtonDesign extends StatelessWidget {
  final String title;
  final VoidCallback function;

  ButtonDesign(this.title, this.function);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return InkWell(
      onTap: function,
      child: Container(
        width: MediaQuerySetter.getWidth(context) * 0.8,
        height: MediaQuerySetter.getHeight(context) * 0.05,
        color: AppColors.buttonColor,
        child: Center(
          child: Text(title),
        ),
      ),
    );
  }
}
</code>```

I would like to know what I can do to get this fixed.

Body:
I'm trying to move towards writing structured Flutter code and this is my first attempt at it. My idea is to create a Boilerplate API class that will make API calls as per the endpoints passed and return a response accordingly. However, right now I'm facing a couple of issues. Here is my code:

The boilerplate API Class:

class NetworkServices {
  Future<dynamic> postLoginRequest(
      String url, dynamic data, BuildContext context) async {
    var jsonResponse;

    try {
      final response = await http.post(Uri.parse(url),
          body: json.encode(data),
          headers: {
            'Content-Type': 'application/json'
          }).timeout(const Duration(seconds: 30));
      jsonResponse = returnResponse(response);
      print('FROM NETWORK: $jsonResponse');   //Error message given below

    } on SocketException {
      Flushbar(
        leftBarIndicatorColor: Colors.red,
        icon: const Icon(Icons.warning, color: Colors.white),
        message: 'Ooops!!! Something went wrong',
      ).show(context);
    }
    return jsonResponse;
  }

  dynamic returnResponse(http.Response response) {
    if (response.statusCode >= 200 && response.statusCode <= 300) {
      dynamic jsonResponse = json.decode(response.body);
      return jsonResponse;
    } else if (response.statusCode >= 400 || response.statusCode == 404) {
      return 'An Error Occured';
    } else if (response.statusCode >= 404) {
      return 'Invalid Request';
    } else {
      return 'Error Occured While Communicating with Servers!!! Please try again later';
    }
  }
}

The API call always tends to think that the API had a status call of 400 or 404. Although, this API works fine elsewhere. This is what it prints:

I/flutter (19427): FROM NETWORK: An Error Occured

This here is the Controller Class:

class LoginController with ChangeNotifier {
  NetworkServices networkServices = NetworkServices();
  dynamic _loginResponse;

  dynamic get loginResponse {
    return _loginResponse;
  }

  Future<void> login(dynamic data, BuildContext context) async {
    Loader(true);
    networkServices
        .postLoginRequest(ApiUrl.loginUrl, data, context)
        .then((value) {
      Loader(false);
      _loginResponse = value;
      print('SUCCESS $_loginResponse');      //SUCCESS Message
      Flushbar(
        message: _loginResponse['data']['access_token'],
      ).show(context);
    }).onError((error, stackTrace) {
      Loader(false);
      print('ERRROR: $error');         //ERROR Message

      Flushbar(
        leftBarIndicatorColor: AppColors.buttonColor,
        message: error.toString(),
      ).show(context);
    });
    notifyListeners();
  }
}

In the controller class, for some strange reason, both the SUCCESS AND ERROR Messages get printed contradicting my idea that only a portion of it would get printed depending on whether the API call was successful or failed.
The messages I get for both says:

I/flutter (19427): SUCCESS An Error Occured
I/flutter (19427): ERRROR: type 'String' is not a subtype of type 'int' of 'index'

This is the code for the UI where it all gets called:

class LoginScreen extends StatelessWidget {
  GlobalKey<FormState> _key = GlobalKey<FormState>();
  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Form(
            key: key,
            child: Column(
              children: [
                TextFormField(
                  controller: usernameController,
                ),
                SizedBox(height: MediaQuerySetter.getHeight(context) * 0.05),
                TextFormField(
                  controller: passwordController,
                )
              ],
            ),
          ),
                SizedBox(height: MediaQuerySetter.getHeight(context) * 0.05),

          ButtonDesign('Login', () {
            Map<String, dynamic> data = {
              'email': usernameController.text,
              'password': passwordController.text
            };

            Provider.of<LoginController>(context, listen: false)
                .login(data, context);
          })
        ],
      ),
    );
  }
}

I intend to use a common button widget throughout the app:

class ButtonDesign extends StatelessWidget {
  final String title;
  final VoidCallback function;

  ButtonDesign(this.title, this.function);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return InkWell(
      onTap: function,
      child: Container(
        width: MediaQuerySetter.getWidth(context) * 0.8,
        height: MediaQuerySetter.getHeight(context) * 0.05,
        color: AppColors.buttonColor,
        child: Center(
          child: Text(title),
        ),
      ),
    );
  }
}

I would like to know what I can do to get this fixed.


问:
How can i run a script (webvr.js from Krpano), inside iOS, in a app via Cordova, that checks if it is running HTTPS on localhost?
I am trying to create a offline version of my tour, created using Krpano. Everything works fine in Android, the tour works fine too in iOS. But when I try to use vr mode in iOS(that uses webvr.js), this script don't work, the tour doesn't enter in VR mode, asking for a HTTPS way to execute it. The code from this file is encripted, so I can't understand why it requests a HTTPS connection from localhost. All other things are working just fine, except this VR mode.

Tried several plugins from Cordova just to access the tour. Everything ok, except vr mode. Just don't know how to make this script run or bypass using https.

I am using:
krpano 1.20.11
cordova-ios 6.1.0

I really don't want to use a local https server just for this, just to avoid any security problems.

Any suggestions?

Sorry for my rusty english ;(


问:
Spring Boot 3 @SpringBootTest-annotated tests does not execute gateway auto-configuration
I have a very simple test:

```<code>@SpringBootTest(properties = {"instance.role=GATEWAY", "instance.name=test-instance", "debug=true"})
@TestPropertySource(locations = {"classpath:application.yaml"})
class GatewayWiringTest {

    @Autowired
    private MySpringBootApplication application;

    @Test
    void gatewayConfigLoads() {
        assertThat(application).isNotNull();
    }
}
</code>```

Since my application starts with different bean configurations, depending on the role it gets assigned, I use such tests to test that each configuration is loadable.

It did run without problems with Spring Boot 2.7. It doesn't run with Spring Boot 3.0 (obviously, after having updated Java to version 17 too, not just the spring/spring boot dependencies). The root cause of the error is:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder' available: expected at least 1 bean which qualifies as autowire candidate.

I have traced the problem to the class GatewayAutoConfiguration from the spring cloud gateway server dependency not being evaluated for loading - this is the autoconfiguration class that should provide the missing bean.

I have also verified that the class is on the classpath when the test is executed, by running the test with mvn -X and looking at the classpath. The problem isn't that one of the two conditions for loading the class evaluates to false, the problem is that those conditions never get evaluated in the first place - running the test with --debug generated the conditions evaluation report, and the class GatewayAutoConfiguration doesn't appear in either of the two lists - matched and unmatched conditions.

Why doesn't it get processed? What do I need to do differently with Spring Boot 3.0 compared to Spring Boot 2.7, in this regard specifically?

Body:
I have a very simple test:

@SpringBootTest(properties = {"instance.role=GATEWAY", "instance.name=test-instance", "debug=true"})
@TestPropertySource(locations = {"classpath:application.yaml"})
class GatewayWiringTest {

    @Autowired
    private MySpringBootApplication application;

    @Test
    void gatewayConfigLoads() {
        assertThat(application).isNotNull();
    }
}

Since my application starts with different bean configurations, depending on the role it gets assigned, I use such tests to test that each configuration is loadable.

It did run without problems with Spring Boot 2.7. It doesn't run with Spring Boot 3.0 (obviously, after having updated Java to version 17 too, not just the spring/spring boot dependencies). The root cause of the error is:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder' available: expected at least 1 bean which qualifies as autowire candidate.

I have traced the problem to the class GatewayAutoConfiguration from the spring cloud gateway server dependency not being evaluated for loading - this is the autoconfiguration class that should provide the missing bean.

I have also verified that the class is on the classpath when the test is executed, by running the test with mvn -X and looking at the classpath. The problem isn't that one of the two conditions for loading the class evaluates to false, the problem is that those conditions never get evaluated in the first place - running the test with --debug generated the conditions evaluation report, and the class GatewayAutoConfiguration doesn't appear in either of the two lists - matched and unmatched conditions.

Why doesn't it get processed? What do I need to do differently with Spring Boot 3.0 compared to Spring Boot 2.7, in this regard specifically?


问:
How to use custom express server with sveltekit in dev
I was able to set up a custom express server in sveltekit, but it only works in build with adapter node. How can I use it in dev?

I can't find anything useful on google.


问:
VBA macro is running too slow when writing data in excel from array/dictionary
I have been trying to speed up writing data to excel but it's taking a long time with only 800 rows.

```<code>Sub WriteData(Response, Trw)
Application.StatusBar = "Parsing Json (Response)"

Response = Mid(Response, 11)

Response = Mid(Response, 1, Len(Response) - 1)

Dim Allresponse As Object
Dim Results As Collection

 Set Allresponse = ParseJson(Response)
 Debug.Print "P2 CID: " & Allresponse("correlationId")

   Set Results = Allresponse("mappings")

   Dim resultD As Variant, rw As Long
   Worksheets("Output").Select
   Application.StatusBar = "Saving - 0% Completed"
   rw = 2
   For Each resultD In Results
     Range("A1")(rw, 1) = resultD("Id")
     Range("A1")(rw, 20) = resultD("firstReference")
     Range("A1")(rw, 21) = resultD("secondReference")
     rw = rw + 1
     If rw / 50 = Int(rw / 50) Then
       Application.StatusBar = "Saving - " & Format(rw / Trw, "0%") & " Completed"
     End If
   Next

End Sub
</code>```

I tried declaring resultD in both Variant and dictionary but it is still taking a long time to run. Is there a way to write a block data instead of row by row? Thanks!

Body:
I have been trying to speed up writing data to excel but it's taking a long time with only 800 rows.

Sub WriteData(Response, Trw)
Application.StatusBar = "Parsing Json (Response)"

Response = Mid(Response, 11)

Response = Mid(Response, 1, Len(Response) - 1)

Dim Allresponse As Object
Dim Results As Collection

 Set Allresponse = ParseJson(Response)
 Debug.Print "P2 CID: " & Allresponse("correlationId")

   Set Results = Allresponse("mappings")

   Dim resultD As Variant, rw As Long
   Worksheets("Output").Select
   Application.StatusBar = "Saving - 0% Completed"
   rw = 2
   For Each resultD In Results
     Range("A1")(rw, 1) = resultD("Id")
     Range("A1")(rw, 20) = resultD("firstReference")
     Range("A1")(rw, 21) = resultD("secondReference")
     rw = rw + 1
     If rw / 50 = Int(rw / 50) Then
       Application.StatusBar = "Saving - " & Format(rw / Trw, "0%") & " Completed"
     End If
   Next

End Sub

I tried declaring resultD in both Variant and dictionary but it is still taking a long time to run. Is there a way to write a block data instead of row by row? Thanks!


问:
TS2339 warning from gRPC generated Typescript files
I generated a simple demo project using gRPC's but I am not able to use the generated setters. If I access the varables directly from the response I get a warning that reads. res.data.title

```<code>TS2339: Property 'title' does not exist on type 'TodoResponse'.
</code>```

However res.data.title will render correctly in the browser.

I generated the gRPC code two different ways with no avail. I thought maybe the plugin was the issue.

grpc_tools_node_protoc. Example of the command used to generate the files.

```<code># JavaScript code generation
cd view && yarn run grpc_tools_node_protoc \
    --plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts \
    --ts_out=grpc_js:${PROTO_DEST} \
    --js_out=import_style=commonjs:${PROTO_DEST} \
    --grpc_out=grpc_js:${PROTO_DEST} \
    -I ${PROJ_PATH}/proto \
    ${PROJ_PATH}/proto/*.proto
</code>```

Second approach.

```<code>protoc -I ${PROJ_PATH}/proto api.proto \
  --js_out=import_style=commonjs,binary:${PROJ_PATH}/view/${PROTO_DEST} \
  --plugin=protoc-gen-grpc-web=${PROJ_PATH}/view/node_modules/.bin/protoc-gen-grpc-web \
  --grpc-web_out=import_style=typescript,mode=grpcweb:${PROJ_PATH}/view/${PROTO_DEST}
</code>```

The files work fine, and I can render everything that I need. I just have these annoying errors all over which will cause the linter to fail. I should be able to use the TS getters but I cannot.

example:

If I use the getter with () I get. res.data.getTodoList()

```<code>errorTypeError: res.data.getTodoList() is not a function
</code>```

Without the ()

```<code>res.data.getTodoList undefined
</code>```

This is what I see in my IDE. Will still compile but render the values as long as I am not using a getter.

Why is this happening? When we declare a variable without specifying the type, it causes the TypeScript Compiler to infer its type for you. However, this is generated code that I thought was suppose to work with grpc-web.

TodoAllResponse

```<code> export class TodoAllResponse extends jspb.Message {
    clearTodoList(): void;
    getTodoList(): Array<Todo>;
    setTodoList(value: Array<Todo>): TodoAllResponse;
    addTodo(value?: Todo, index?: number): Todo;

    serializeBinary(): Uint8Array;
    toObject(includeInstance?: boolean): TodoAllResponse.AsObject;
    static toObject(includeInstance: boolean, msg: TodoAllResponse): TodoAllResponse.AsObject;
    static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
    static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
    static serializeBinaryToWriter(message: TodoAllResponse, writer: jspb.BinaryWriter): void;
    static deserializeBinary(bytes: Uint8Array): TodoAllResponse;
    static deserializeBinaryFromReader(message: TodoAllResponse, reader: jspb.BinaryReader): TodoAllResponse;
}
</code>```

I am not sure if I am missing a proto file command. At this point I am rather stumped

method

```<code> async getAllTodos() {
        try {
            return await grpcClient.get<TodoAllResponse>(`/v1/getAll?${qs.stringify({

            })}`).then(res => {
                console.log("res in getAll", res.data.getTodoList) <--- undefined
                return res.data
            })
        } catch (err) {
            console.log("error" + err);
        }
    },
</code>```

gRPC file

```<code>service ApiService {

    rpc GetAll(TodoRequest) returns (TodoAllResponse){
        option (google.api.http) = {
            get: "/v1/getAll"
        };
    }

}

message TodoRequest {
    string id = 1;
}

message Todo {
    string id = 1;
    string title = 2;
    string time = 3;
}

message TodoAllResponse {
    repeated Todo todo = 1;
}
</code>```

Advice?

--- update ---

I was able to get it to work by creating a custom TS object.

```<code>import { ITodo } from "./Todo";

export interface ITodoAllResponse {
    todo: ITodo[];
}
</code>```

--

```<code>export interface ITodo {
    id: string;
    title: string;
}
</code>```

then the axios call

```<code># JavaScript code generation
cd view && yarn run grpc_tools_node_protoc \
    --plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts \
    --ts_out=grpc_js:${PROTO_DEST} \
    --js_out=import_style=commonjs:${PROTO_DEST} \
    --grpc_out=grpc_js:${PROTO_DEST} \
    -I ${PROJ_PATH}/proto \
    ${PROJ_PATH}/proto/*.proto
</code>```0

and in my component

```<code># JavaScript code generation
cd view && yarn run grpc_tools_node_protoc \
    --plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts \
    --ts_out=grpc_js:${PROTO_DEST} \
    --js_out=import_style=commonjs:${PROTO_DEST} \
    --grpc_out=grpc_js:${PROTO_DEST} \
    -I ${PROJ_PATH}/proto \
    ${PROJ_PATH}/proto/*.proto
</code>```1

However I really want to use the generated gRPC typescript models. It appears there might be an issue with repeated Todo todo = 1; but I am not completely sure.

Body:
I generated a simple demo project using gRPC's but I am not able to use the generated setters. If I access the varables directly from the response I get a warning that reads. res.data.title

TS2339: Property 'title' does not exist on type 'TodoResponse'.

However res.data.title will render correctly in the browser.

I generated the gRPC code two different ways with no avail. I thought maybe the plugin was the issue.

grpc_tools_node_protoc. Example of the command used to generate the files.

# JavaScript code generation
cd view && yarn run grpc_tools_node_protoc \
    --plugin=protoc-gen-ts=./node_modules/.bin/protoc-gen-ts \
    --ts_out=grpc_js:${PROTO_DEST} \
    --js_out=import_style=commonjs:${PROTO_DEST} \
    --grpc_out=grpc_js:${PROTO_DEST} \
    -I ${PROJ_PATH}/proto \
    ${PROJ_PATH}/proto/*.proto

Second approach.

protoc -I ${PROJ_PATH}/proto api.proto \
  --js_out=import_style=commonjs,binary:${PROJ_PATH}/view/${PROTO_DEST} \
  --plugin=protoc-gen-grpc-web=${PROJ_PATH}/view/node_modules/.bin/protoc-gen-grpc-web \
  --grpc-web_out=import_style=typescript,mode=grpcweb:${PROJ_PATH}/view/${PROTO_DEST}

The files work fine, and I can render everything that I need. I just have these annoying errors all over which will cause the linter to fail. I should be able to use the TS getters but I cannot.

example:

If I use the getter with () I get. res.data.getTodoList()

errorTypeError: res.data.getTodoList() is not a function

Without the ()

res.data.getTodoList undefined

This is what I see in my IDE. Will still compile but render the values as long as I am not using a getter.

Why is this happening? When we declare a variable without specifying the type, it causes the TypeScript Compiler to infer its type for you. However, this is generated code that I thought was suppose to work with grpc-web.

TodoAllResponse

 export class TodoAllResponse extends jspb.Message {
    clearTodoList(): void;
    getTodoList(): Array<Todo>;
    setTodoList(value: Array<Todo>): TodoAllResponse;
    addTodo(value?: Todo, index?: number): Todo;

    serializeBinary(): Uint8Array;
    toObject(includeInstance?: boolean): TodoAllResponse.AsObject;
    static toObject(includeInstance: boolean, msg: TodoAllResponse): TodoAllResponse.AsObject;
    static extensions: {[key: number]: jspb.ExtensionFieldInfo<jspb.Message>};
    static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo<jspb.Message>};
    static serializeBinaryToWriter(message: TodoAllResponse, writer: jspb.BinaryWriter): void;
    static deserializeBinary(bytes: Uint8Array): TodoAllResponse;
    static deserializeBinaryFromReader(message: TodoAllResponse, reader: jspb.BinaryReader): TodoAllResponse;
}

I am not sure if I am missing a proto file command. At this point I am rather stumped

method

 async getAllTodos() {
        try {
            return await grpcClient.get<TodoAllResponse>(`/v1/getAll?${qs.stringify({

            })}`).then(res => {
                console.log("res in getAll", res.data.getTodoList) <--- undefined
                return res.data
            })
        } catch (err) {
            console.log("error" + err);
        }
    },

gRPC file

service ApiService {

    rpc GetAll(TodoRequest) returns (TodoAllResponse){
        option (google.api.http) = {
            get: "/v1/getAll"
        };
    }

}

message TodoRequest {
    string id = 1;
}

message Todo {
    string id = 1;
    string title = 2;
    string time = 3;
}

message TodoAllResponse {
    repeated Todo todo = 1;
}

Advice?

--- update ---

I was able to get it to work by creating a custom TS object.

import { ITodo } from "./Todo";

export interface ITodoAllResponse {
    todo: ITodo[];
}

--

export interface ITodo {
    id: string;
    title: string;
}

then the axios call

async getAllTodos() {
    try {
        return await grpcClient.get<ITodoAllResponse>(`/v1/getAll?${qs.stringify({
        })}`).then(res => {
            return res.data.todo
        })
    } catch (err) {
        console.log("error" + err);
    }
},

and in my component

const todoArr = ref<ITodo[]>()

However I really want to use the generated gRPC typescript models. It appears there might be an issue with repeated Todo todo = 1; but I am not completely sure.


问:
Is it possible to match a pattern inside an array in an eventBridge rule?
I'm trying to write an event rule for an event that matches with this :

```<code>{
   object1 : "",
   object2 : {
      array1: [
        {
            field1: "abcd",
            field2: "1234"
        },
        {
            field1: "pqrs",
            field2: "2345"
        }
     ]
}

</code>```

I'm trying to capture events for a particular combination of "field1" and "field2" ( within a same element ). Has anyone tried this before and can possibly share some pointers ?
Thanks in advance.

What I've tried till now is :

```<code>{
  "object1": ["value1"],
  "object2": {
    "array1": {
      "field1": ["pqrs"],
      "field2": ["2345"]
    }
  }
}
</code>```

Unfortunately, this is will match even if source event looks something like this :

```<code>{
   object1 : "",
   object2 : {
      array1: [
        {
            field1: "pqrs",
            field2: "1234"
        },
        {
            field1: "vxyz",
            field2: "2345"
        }
     ]
}

</code>```

*notice how field1 are different in this one ( but still the mentioned rule will match with both such events ).

Body:
I'm trying to write an event rule for an event that matches with this :

{
   object1 : "",
   object2 : {
      array1: [
        {
            field1: "abcd",
            field2: "1234"
        },
        {
            field1: "pqrs",
            field2: "2345"
        }
     ]
}

I'm trying to capture events for a particular combination of "field1" and "field2" ( within a same element ). Has anyone tried this before and can possibly share some pointers ?
Thanks in advance.

What I've tried till now is :

{
  "object1": ["value1"],
  "object2": {
    "array1": {
      "field1": ["pqrs"],
      "field2": ["2345"]
    }
  }
}

Unfortunately, this is will match even if source event looks something like this :

{
   object1 : "",
   object2 : {
      array1: [
        {
            field1: "pqrs",
            field2: "1234"
        },
        {
            field1: "vxyz",
            field2: "2345"
        }
     ]
}

*notice how field1 are different in this one ( but still the mentioned rule will match with both such events ).


问:
Multiselect from listbox with List<string>
So I have this test page: https://demo.seleniumeasy.com/basic-select-dropdown-demo.html

On the bottom there is a listbox, from which I should select some States and verify the selection with buttons below.

I tried doing this:

```<code>string expectedResult = "First selected option is : Florida";

List<string> selectedStates = new List<string> { "Florida", "New York", "Texas" };

foreach (string state in selectedStates)
{
BasicSelectDropdownDemo.SelectMultiElements(state);
}

BasicSelectDropdownDemo.ClickFirstSelectedButton();
string actualResult = BasicSelectDropdownDemo.GetMultipleSelectedMessage();

Assert.AreEqual(expectedResult, actualResult);
</code>```

But I get the result: "First selected option is : Texas"

Visually it seems that the selection is ok, all three States from the List  are selected, but practically it seems that only the last selection stays.

My "ClickFirstSelectedButton" methods looks like this:

```<code>public static void SelectMultiElements(string selectedState)
{
Common.MultiSelectByValue(selectStatesMultiSelectLocator, selectedState);
}
</code>```

Futher, my "MultiSelectByValue" looks like this:

```<code>SelectElement selectElement = GetSelectElement(locator);
Actions actions = new Actions(Driver.GetDriver());
actions.KeyDown(Keys.Control);
selectElement.SelectByValue(value);
actions.Perform();
</code>```

Maybe it is something wrong with my Actions code?

It may be a little confusing, as I have all my methods separated in other classes, but as I mentioned - visually it looks like I'm getting there, I'm getting the selection, but somehow only the last one stays in the end. I'm I missing something to "save" the previous selections? I guess that after actions.Perform(); the Driver "forgets" the selection and starts with each variable from scratch. But then again - on the screen I see the grey-out selections.

Body:
So I have this test page: https://demo.seleniumeasy.com/basic-select-dropdown-demo.html

On the bottom there is a listbox, from which I should select some States and verify the selection with buttons below.

I tried doing this:

string expectedResult = "First selected option is : Florida";

List<string> selectedStates = new List<string> { "Florida", "New York", "Texas" };

foreach (string state in selectedStates)
{
BasicSelectDropdownDemo.SelectMultiElements(state);
}

BasicSelectDropdownDemo.ClickFirstSelectedButton();
string actualResult = BasicSelectDropdownDemo.GetMultipleSelectedMessage();

Assert.AreEqual(expectedResult, actualResult);

But I get the result: "First selected option is : Texas"

Visually it seems that the selection is ok, all three States from the List  are selected, but practically it seems that only the last selection stays.

My "ClickFirstSelectedButton" methods looks like this:

public static void SelectMultiElements(string selectedState)
{
Common.MultiSelectByValue(selectStatesMultiSelectLocator, selectedState);
}

Futher, my "MultiSelectByValue" looks like this:

SelectElement selectElement = GetSelectElement(locator);
Actions actions = new Actions(Driver.GetDriver());
actions.KeyDown(Keys.Control);
selectElement.SelectByValue(value);
actions.Perform();

Maybe it is something wrong with my Actions code?

It may be a little confusing, as I have all my methods separated in other classes, but as I mentioned - visually it looks like I'm getting there, I'm getting the selection, but somehow only the last one stays in the end. I'm I missing something to "save" the previous selections? I guess that after actions.Perform(); the Driver "forgets" the selection and starts with each variable from scratch. But then again - on the screen I see the grey-out selections.


问:
Convert a .jpg image to rgb in micropython?
I am trying to create a program on the Raspberry Pi Pico W that downloads a jpg image and displays a very pixilated version of the image on an addressable led matrix. I have decided to attempt to use micro python as my coding language for this project since I have already completed a similar project in the full python language. Since I am downloading the images from an online source I am stuck using the '.jpg' format at a fixed size.

I have been running into some difficulties processing the image. To run on the addressable LEDs (Neopixel) I want to collect the rgb data from each individual pixel of the .jpg and add them to a list.

Working on python I know that the PIL/Pillow library is a great solution to this problem.

```<code>from PIL import Image
image = Image.open('256256.jpg',formats=None)
print(image)
from numpy import asarray
data = asarray(image)
</code>```

Unfortunately the RP2040 doesn't seem have enough storage space to handle the module.
I need to find a way to decode the image using the modules readily available to micro python.
I have attempted to reverse engineer the PIL open feature but haven't had any luck so far.

Thank you in advance!

Body:
I am trying to create a program on the Raspberry Pi Pico W that downloads a jpg image and displays a very pixilated version of the image on an addressable led matrix. I have decided to attempt to use micro python as my coding language for this project since I have already completed a similar project in the full python language. Since I am downloading the images from an online source I am stuck using the '.jpg' format at a fixed size.

I have been running into some difficulties processing the image. To run on the addressable LEDs (Neopixel) I want to collect the rgb data from each individual pixel of the .jpg and add them to a list.

Working on python I know that the PIL/Pillow library is a great solution to this problem.

from PIL import Image
image = Image.open('256256.jpg',formats=None)
print(image)
from numpy import asarray
data = asarray(image)

Unfortunately the RP2040 doesn't seem have enough storage space to handle the module.
I need to find a way to decode the image using the modules readily available to micro python.
I have attempted to reverse engineer the PIL open feature but haven't had any luck so far.

Thank you in advance!


问:
How Do I Mimic The Linking Of An "Example App" As A Bundle Loader of Match-O type "Bundle" to the Testing Target In Swift Package Manager
I am working on migrating a Carthage library into a Swift Package Manager library. In the current testing target, under build settings, we have an Example App linked as a Bundle Loader of Match-O type "Bundle" as shown below in the screenshot. How can I mimic the same behavior in Swift Package Manager? (I need this because the test cases are testing against the Example app.)

I have tried to add the "Example App" as a dependency under the .testDependency in the Package.swift file.


问:
Python how to create a thread and improve performance
I am new to python threading and still figuring out how to make one. I would like to know how to improve performance by threading.

My code is at the bottom.
I created 4 threads and each thread has a function drawing one specific shape. In addition to threads, I also added lock when the four function to actually draw a shape, then it worked properly. However, I can't make the code to draw shapes in a random order like some squares, then some circles, then some triangles and so on.

Thanks for your help in advance.

def draw_square(tur, x, y, side, color='black'):
    """Draw Square"""
    tur.move(x, y)
    tur.setheading(0)
    tur.color(color)
    for _ in range(4):
        tur.forward(side)
        tur.right(90)

def draw_circle(tur, x, y, radius, color='red'):
    """Draw Circle"""
    steps = 8
    circumference = 2 * math.pi * radius

    # Need to adjust starting position so that (x, y) is the center
    x1 = x - (circumference // steps) // 2
    y1 = y
    tur.move(x1, y1 + radius)

    tur.setheading(0)
    tur.color(color)
    for _ in range(steps):
        tur.forward(circumference / steps)
        tur.right(360 / steps)

def draw_rectangle(tur, x, y, width, height, color='blue'):
    """Draw a rectangle"""
    tur.move(x, y)
    tur.setheading(0)
    tur.color(color)
    tur.forward(width)
    tur.right(90)
    tur.forward(height)
    tur.right(90)
    tur.forward(width)
    tur.right(90)
    tur.forward(height)
    tur.right(90)

def draw_triangle(tur, x, y, side, color='green'):
    """Draw a triangle"""
    tur.move(x, y)
    tur.setheading(0)
    tur.color(color)
    for _ in range(4):
        tur.forward(side)
        tur.left(120)

def draw_coord_system(tur, x, y, size=300, color='black'):
    """Draw corrdinate lines"""
    tur.move(x, y)
    for i in range(4):
        tur.forward(size)
        tur.backward(size)
        tur.left(90)

lock = threading.Lock()

def draw_squares(tur):
    """Draw a group of squares"""
    for x in range(-300, 350, 200):
        for y in range(-300, 350, 200):
            lock.acquire()
            draw_square(tur, x - 50, y + 50, 100)
            lock.release()

def draw_circles(tur):
    """Draw a group of circles"""
    for x in range(-300, 350, 200):
        for y in range(-300, 350, 200):
            lock.acquire()
            draw_circle(tur, x, y-2, 50)
            lock.release()

def draw_triangles(tur):
    """Draw a group of triangles"""
    for x in range(-300, 350, 200):
        for y in range(-300, 350, 200):
            lock.acquire()
            draw_triangle(tur, x-30, y-30+10, 60)
            lock.release()

def draw_rectangles(tur):
    """Draw a group of Rectangles"""
    for x in range(-300, 350, 200):
        for y in range(-300, 350, 200):
            lock.acquire()
            draw_rectangle(tur, x-10, y+5, 20, 15)
            lock.release()

def run_no_threads(tur, log, main_turtle):
    """Draw different shapes without using threads"""

    # Draw Coords system
    tur.pensize(0.5)
    draw_coord_system(tur, 0, 0, size=375)
    tur.pensize(4)

    log.write('-' * 50)
    log.start_timer('Start Drawing No Threads')
    tur.move(0, 0)

    draw_squares(tur)
    draw_circles(tur)
    draw_triangles(tur)
    draw_rectangles(tur)

    log.step_timer('All drawing commands have been created')

    tur.move(0, 0)
    log.write(f'Number of Drawing Commands: {tur.get_command_count()}')

    # Play the drawing commands that were created
    tur.play_commands(main_turtle)
    log.stop_timer('Total drawing time')
    tur.clear()

def run_with_threads(tur, log, main_turtle):
    """Draw different shapes using threads"""

    # Draw Coors system
    tur.pensize(0.5)
    draw_coord_system(tur, 0, 0, size=375)
    tur.pensize(4)
    log.write('-' * 50)
    log.start_timer('Start Drawing With Threads')
    tur.move(0, 0)

    # Create a list of threads

    draws = [draw_squares, draw_circles, draw_triangles, draw_rectangles]
    threads = []
    for i in range(4):
        logging.info("Main    : create and start thread %d.", i)
        t = threading.Thread(target=draws[i], args=(tur, ))
        threads.append(t)

    for t in threads:
        t.start()

    for t in threads:
        t.join()

    log.step_timer('All drawing commands have been created')

    log.write(f'Number of Drawing Commands: {tur.get_command_count()}')

    # Play the drawing commands that were created
    tur.play_commands(main_turtle)
    log.stop_timer('Total drawing time')
    tur.clear()

def main():

    log = Log(show_terminal=True)

    # create a Screen Object
    screen = turtle.Screen()

    # Screen configuration
    screen.setup(800, 800)

    # Make turtle Object
    main_turtle = turtle.Turtle()
    main_turtle.speed(0)

    # Special CSE 251 Turtle Class
    turtle251 = CSE251Turtle()

    # Test 1 - Drawing with no threads
    run_no_threads(turtle251, log, main_turtle)

    main_turtle.clear()

    # Test 2 - Drawing with threads
    run_with_threads(turtle251, log, main_turtle)

    # Waiting for user to close window
    turtle.done()

if __name__ == "__main__":
    main()

```


问:
React Barcode Scanner returning wrong results
I am creating a web app that is able to scan barcodes to pull up inventory of an item.  I am using the QuaggaJS API to create this functionality.  The problem is every time I scan the same item a different result is returned.  I have tried fixing the lighting in my area so I don't think that is the issue.</p>
```<code>import { useNavigate } from "react-router-dom";
import Quagga from "quagga";

const BarcodeScanner = () => {
    const navigate = useNavigate()

  const startScanner = () => {
    Quagga.init(
      {
        inputStream: {
          name: "Live",
          type: "LiveStream",
          constraints: {
            facingMode: "environment",
          },
        locate: true,
        },
        decoder: {
          readers: ["ean_reader"], //4171287788700
        },
        debug: {
            drawBoundingBox: true,
            showFrequency: true,
            drawScanline: true,
            showPattern: true
        },

      },
      function (err) {
        if (err) {
          console.log(err);
          return;
        }
        console.log("Initialization finished. Ready to start");
        Quagga.start();
      }
    );

    Quagga.onDetected((data) => {
      console.log(data.codeResult.code);
      Quagga.stop();
      navigate('/home');
    });
  };

  const stopScanner = () => {
    Quagga.stop();
  };

  useEffect(() => {
    startScanner();
    return stopScanner;
  }, []);

  return <div id="interactive" className="viewport"></div>;
};

export default BarcodeScanner;
</code>```

Body:
I am creating a web app that is able to scan barcodes to pull up inventory of an item.  I am using the QuaggaJS API to create this functionality.  The problem is every time I scan the same item a different result is returned.  I have tried fixing the lighting in my area so I don't think that is the issue.

import { useNavigate } from "react-router-dom";
import Quagga from "quagga";

const BarcodeScanner = () => {
    const navigate = useNavigate()

  const startScanner = () => {
    Quagga.init(
      {
        inputStream: {
          name: "Live",
          type: "LiveStream",
          constraints: {
            facingMode: "environment",
          },
        locate: true,
        },
        decoder: {
          readers: ["ean_reader"], //4171287788700
        },
        debug: {
            drawBoundingBox: true,
            showFrequency: true,
            drawScanline: true,
            showPattern: true
        },

      },
      function (err) {
        if (err) {
          console.log(err);
          return;
        }
        console.log("Initialization finished. Ready to start");
        Quagga.start();
      }
    );

    Quagga.onDetected((data) => {
      console.log(data.codeResult.code);
      Quagga.stop();
      navigate('/home');
    });
  };

  const stopScanner = () => {
    Quagga.stop();
  };

  useEffect(() => {
    startScanner();
    return stopScanner;
  }, []);

  return

;
};

export default BarcodeScanner;


问:
Zooming in as Input in Dash-Plotly, Python
I am creating a Dash app with layout that requires zoomining in/out at some point. When it happens, I want some object to disappear (change CSS) in order to make the app "cleaner". If displaying 100 % changes to any other % value I need to use it as an input for the attached function. Is it possible by any chance? Thanks.</p>


问:
Which WordPress hook is used when a user role is updated to the same user role from the primary 'Users' screen?
I would like to run a function when a user or multiple users are updated in this specific scenario:

Admin user visits wp-admin/users.php

Admin selects user(s) using checkbox

Admin changes user role using 'Change role to...' dropdown and 'Change' button (note: the role will be the same)

I have experimented with the following hooks already:

user_profile_update_errors

update_user_metadata

add_user_role

set_user_role

These only seem to execute when pressing 'Update' from within an individual profile and not using a bulk method on the users.php screen?

Is there a hook that can be used that executes regardless even when the user role is updated to the same role it was previously?


问:
SQL Server DB event listener for java app
Does anyone know of a way to listen to SQL Server change events via Java?  I found this link for SQL server query notifications, but it only seems to apply to .NET, and I need to do this in Java: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/query-notifications-in-sql-server</p>


问:
Making “Reformat code” on request block - it has other layout I need
Laravel 9 app in PhpStorm 2021.1.4

When I make “Reformat code” on a block of code I got :

$totalVotesCount = Vote::getByName($filterName, true)
                       ->getByStatus($filterStatus)
                       ->getByIsQuiz($filterIsQuiz)
                       ->getByIsHomepage($filterIsHomepage)
                       ->with('voteCategory')
                       ->with('creator')
                       ->getByVoteCategoryId($filterVoteCategoryId)
                       ->count();
```
<p>But I need to have these lines formatted like this:</p>
<pre class="lang-php prettyprint-override"><code>$totalVotesCount = Vote::getByName($filterName, true)
    ->getByStatus($filterStatus)
    ->getByIsQuiz($filterIsQuiz)
    ->getByIsHomepage($filterIsHomepage)
    ->with('voteCategory')
    ->with('creator')
    ->getByVoteCategoryId($filterVoteCategoryId)
    ->count();
</code>```

Where can I configure these options?

Body:
Laravel 9 app in PhpStorm 2021.1.4

When I make “Reformat code” on a block of code I got :

$totalVotesCount = Vote::getByName($filterName, true)
                       ->getByStatus($filterStatus)
                       ->getByIsQuiz($filterIsQuiz)
                       ->getByIsHomepage($filterIsHomepage)
                       ->with('voteCategory')
                       ->with('creator')
                       ->getByVoteCategoryId($filterVoteCategoryId)
                       ->count();

But I need to have these lines formatted like this:

$totalVotesCount = Vote::getByName($filterName, true)
    ->getByStatus($filterStatus)
    ->getByIsQuiz($filterIsQuiz)
    ->getByIsHomepage($filterIsHomepage)
    ->with('voteCategory')
    ->with('creator')
    ->getByVoteCategoryId($filterVoteCategoryId)
    ->count();

Where can I configure these options?


问:
How to validate array item types with networknt/json-schema-validator?
its probably a very simple thing that Im missing, but my json-schema-validator (networknt/json-schema-validator) doesnt validate the type of my items inside an array.

This Java-snippet should yield errors:

```<code>var schema = "{\n" +
                    "  \"$schema\": \"http://json-schema.org/draft/2020-12/schema#\",\n" +
                    "  \"type\": \"array\",\n" +
                    "  \"items\": [\n" +
                    "    {\n" +
                    "      \"type\": \"integer\"\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}";

var input = "[true,false,{},\"foo\"]";

var factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
var jSchema = factory.getSchema(schema);
var errors = jSchema.validate(new ObjectMapper().readTree(input));
System.out.println("Errors: '"+errors.stream().map(ValidationMessage::getMessage).collect(joining(", ")) +"'");
</code>```

but 'errors is empty. Over on www.jsonschemavalidator.net this is invalid as expected.

What obvious am I overlooking here ?

Thanks!

Body:
its probably a very simple thing that Im missing, but my json-schema-validator (networknt/json-schema-validator) doesnt validate the type of my items inside an array.

This Java-snippet should yield errors:

var schema = "{\n" +
                    "  \"$schema\": \"http://json-schema.org/draft/2020-12/schema#\",\n" +
                    "  \"type\": \"array\",\n" +
                    "  \"items\": [\n" +
                    "    {\n" +
                    "      \"type\": \"integer\"\n" +
                    "    }\n" +
                    "  ]\n" +
                    "}";

var input = "[true,false,{},\"foo\"]";

var factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012);
var jSchema = factory.getSchema(schema);
var errors = jSchema.validate(new ObjectMapper().readTree(input));
System.out.println("Errors: '"+errors.stream().map(ValidationMessage::getMessage).collect(joining(", ")) +"'");

but 'errors is empty. Over on www.jsonschemavalidator.net this is invalid as expected.

What obvious am I overlooking here ?

Thanks!


问:
HTML5 Canvas sub-pixel position rendering issue
I'm trying to draw multiple rectangles positioned very densely in a straight line so they form a single shape like so:

```<code>const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");
const a = 87;
const l = 300;
const col = 'rgba(0,0,64)';
const q = 4; // density - change

ctx.moveTo(300, 100);
ctx.lineTo(
  300 + (Math.cos(degtorad(a)) * l),
  100 + (Math.sin(degtorad(a)) * l)
);
ctx.strokeStyle = col;
ctx.lineWidth = 3;
ctx.stroke();

stack(l, a, col);

function stack(length, angle, color) {
  ctx.fillStyle = color;
  for (let i = 1; i < length * q; i++) {
    let x = 100 + (Math.cos(degtorad(angle)) * i / q);
    let y = 100 + (Math.sin(degtorad(angle)) * i / q);
    console.log(`x:${x}, y:${y}`);
    ctx.beginPath();
    ctx.rect(x, y, 150, 100);
    ctx.fill();
  }
}

function degtorad(angle) {
  return angle * (Math.PI / 180.0);
}
</code>```

https://jsfiddle.net/fallenartist/qeo7a1gx/

However, I don't like the jagged edge at all! It looks like there are issues with canvas rendering at sub-pixel coordinates. Notice how rendering of edges of absolutely positioned rectangles differ from a straight line:

Can anyone explain why is this? And how it can be improved?

Body:
I'm trying to draw multiple rectangles positioned very densely in a straight line so they form a single shape like so:

const canvas = document.getElementById("c");
const ctx = canvas.getContext("2d");
const a = 87;
const l = 300;
const col = 'rgba(0,0,64)';
const q = 4; // density - change

ctx.moveTo(300, 100);
ctx.lineTo(
  300 + (Math.cos(degtorad(a)) * l),
  100 + (Math.sin(degtorad(a)) * l)
);
ctx.strokeStyle = col;
ctx.lineWidth = 3;
ctx.stroke();

stack(l, a, col);

function stack(length, angle, color) {
  ctx.fillStyle = color;
  for (let i = 1; i < length * q; i++) {
    let x = 100 + (Math.cos(degtorad(angle)) * i / q);
    let y = 100 + (Math.sin(degtorad(angle)) * i / q);
    console.log(`x:${x}, y:${y}`);
    ctx.beginPath();
    ctx.rect(x, y, 150, 100);
    ctx.fill();
  }
}

function degtorad(angle) {
  return angle * (Math.PI / 180.0);
}

https://jsfiddle.net/fallenartist/qeo7a1gx/

However, I don't like the jagged edge at all! It looks like there are issues with canvas rendering at sub-pixel coordinates. Notice how rendering of edges of absolutely positioned rectangles differ from a straight line:

Can anyone explain why is this? And how it can be improved?


问:
How to avoid google to detect laptop unique id
i purchased a laptop from someone who has terminated play console account by google and as i listen that once google terminate account then if you use that device whic was attached that account may be cause of re terminate if any one create a new account using that device.can anyone help me out in this regard. sorry for bad english i am not good in english

i am thinking i should reinstall the window and format the ssd before creating new window but i think unique id will not change ??


问:
Smart banner for safari doesn't show my app information on iOS, how to make it work?
I'm using the following meta tag to show a smart banner on the iOS safari browser to open and install the app, copied from apple guide to smartbanners:

```<code><meta name="apple-itunes-app" content="app-id=6444793650">
</code>```

this works for every app, except ours!
the app id is:6444793650

I guess since the app is fresh, apple's lazy crawlers couldn't find time to crawl it!

Body:
I'm using the following meta tag to show a smart banner on the iOS safari browser to open and install the app, copied from apple guide to smartbanners:

<meta name="apple-itunes-app" content="app-id=6444793650">

this works for every app, except ours!
the app id is:6444793650

I guess since the app is fresh, apple's lazy crawlers couldn't find time to crawl it!


问:
scrape hundreds of amazon affiliate links via ASIN using python
I am working on a django project.
At the moment i have a postgres database where all my products including their ASIN are stored.

In the next step i need the affiliate link for each product.

I thought about two options. What do you think is the better one and why?

1.) Using the AWS Product Advertising API (already have it) and generating each affiliate link seperately

2.) If i understood it correctly, there is a way to link my website to aws in such a way, that everytime someone comes from my website, my partnerlink will be added automatically


问:
How ot overwrite same files names after changing the files sizes?
In a new class i added two methods : ChangeSize and ResizeImage

```<code>using ImageMagick;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Weather
{
    public class RadarPixels
    {
        public RadarPixels(string[] imagesToChangeSize,Bitmap image1, Bitmap image2)
        {
            ChangeSize(imagesToChangeSize);
            ReadSetPixels(image1, image2);
        }
        private void ReadSetPixels(Bitmap image1, Bitmap image2)
        {
            int tolerance = 64;
            for (int x = 0; x < image1.Width; x++)
            {
                for (int y = 0; y < image1.Height; y++)
                {
                    Color pixelColor = image1.GetPixel(x, y);
                    // just average R, G, and B values to get gray. Then invert by 255.
                    int invertedGrayValue = 255 - (int)((pixelColor.R + pixelColor.G + pixelColor.B) / 3);
                    if (invertedGrayValue > tolerance) { invertedGrayValue = 255; }
                    // this keeps the original pixel color but sets the alpha value
                    image1.SetPixel(x, y, Color.FromArgb(invertedGrayValue, pixelColor));
                }
            }
            // composite image1 on top of image2
            using (Graphics g = Graphics.FromImage(image2))
            {
                g.CompositingMode = CompositingMode.SourceOver;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImage(image1, new Point(0, 0));
            }

            image2.Save(@"d:\mynewbmp.bmp");
            image1.Dispose();
            image2.Dispose();
        }

        private void ChangeSize(string[] images)
        {
            for(int i = 0; i < images.Length; i++)
            {
                Bitmap bmpResized = ResizeImage(Image.FromFile(images[i]), 512, 512);
                bmpResized.Save(images[i]);
                bmpResized.Dispose();
            }
        }

        public static Bitmap ResizeImage(Image image, int width, int height)
        {
            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

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

This is the saving line in the ChangeSize method : i want to keep the same folder and files names and overwrite the existing files with the new sized files.

```<code>bmpResized.Save(images[i]);
</code>```

before that i used to save it like this : and this is was working fine :

```<code>bmpResized.Save(@"d:\sized\" + Path.GetFileName(images[i]));
</code>```

but when i try to overwrite the files i'm getting exception error on the line :

```<code>bmpResized.Save(images[i]);

System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'

System.Runtime.InteropServices.ExternalException
  HResult=0x80004005
  Message=A generic error occurred in GDI+.
  Source=System.Drawing
  StackTrace:
   at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
   at System.Drawing.Image.Save(String filename, ImageFormat format)
   at System.Drawing.Image.Save(String filename)
   at Weather.RadarPixels.ChangeSize(String[] images) in D:\Csharp Projects\Weather\RadarPixels.cs:line 56
   at Weather.RadarPixels..ctor(String[] imagesToChangeSize, Bitmap image1, Bitmap image2) in D:\Csharp Projects\Weather\RadarPixels.cs:line 20
   at Weather.Form1..ctor() in D:\Csharp Projects\Weather\Form1.cs:line 113
   at Weather.Program.Main() in D:\Csharp Projects\Weather\Program.cs:line 19
</code>```

the files in the array images :

this is how i'm using it in form1 :

```<code>RadarPixels rp = new RadarPixels(radarImages,
                new Bitmap(Image.FromFile(@"D:\123.png")),
                new Bitmap(Image.FromFile(@"D:\2.jpg")));
</code>```

Maybe the problem is because i'm displaying the images in pictureBox before changing the sizes ? maybe because the images are in use ?

Body:
In a new class i added two methods : ChangeSize and ResizeImage

using ImageMagick;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Weather
{
    public class RadarPixels
    {
        public RadarPixels(string[] imagesToChangeSize,Bitmap image1, Bitmap image2)
        {
            ChangeSize(imagesToChangeSize);
            ReadSetPixels(image1, image2);
        }
        private void ReadSetPixels(Bitmap image1, Bitmap image2)
        {
            int tolerance = 64;
            for (int x = 0; x < image1.Width; x++)
            {
                for (int y = 0; y < image1.Height; y++)
                {
                    Color pixelColor = image1.GetPixel(x, y);
                    // just average R, G, and B values to get gray. Then invert by 255.
                    int invertedGrayValue = 255 - (int)((pixelColor.R + pixelColor.G + pixelColor.B) / 3);
                    if (invertedGrayValue > tolerance) { invertedGrayValue = 255; }
                    // this keeps the original pixel color but sets the alpha value
                    image1.SetPixel(x, y, Color.FromArgb(invertedGrayValue, pixelColor));
                }
            }
            // composite image1 on top of image2
            using (Graphics g = Graphics.FromImage(image2))
            {
                g.CompositingMode = CompositingMode.SourceOver;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.DrawImage(image1, new Point(0, 0));
            }

            image2.Save(@"d:\mynewbmp.bmp");
            image1.Dispose();
            image2.Dispose();
        }

        private void ChangeSize(string[] images)
        {
            for(int i = 0; i < images.Length; i++)
            {
                Bitmap bmpResized = ResizeImage(Image.FromFile(images[i]), 512, 512);
                bmpResized.Save(images[i]);
                bmpResized.Dispose();
            }
        }

        public static Bitmap ResizeImage(Image image, int width, int height)
        {
            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            return destImage;
        }
    }
}

This is the saving line in the ChangeSize method : i want to keep the same folder and files names and overwrite the existing files with the new sized files.

bmpResized.Save(images[i]);

before that i used to save it like this : and this is was working fine :

bmpResized.Save(@"d:\sized\" + Path.GetFileName(images[i]));

but when i try to overwrite the files i'm getting exception error on the line :

bmpResized.Save(images[i]);

System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'

System.Runtime.InteropServices.ExternalException
  HResult=0x80004005
  Message=A generic error occurred in GDI+.
  Source=System.Drawing
  StackTrace:
   at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
   at System.Drawing.Image.Save(String filename, ImageFormat format)
   at System.Drawing.Image.Save(String filename)
   at Weather.RadarPixels.ChangeSize(String[] images) in D:\Csharp Projects\Weather\RadarPixels.cs:line 56
   at Weather.RadarPixels..ctor(String[] imagesToChangeSize, Bitmap image1, Bitmap image2) in D:\Csharp Projects\Weather\RadarPixels.cs:line 20
   at Weather.Form1..ctor() in D:\Csharp Projects\Weather\Form1.cs:line 113
   at Weather.Program.Main() in D:\Csharp Projects\Weather\Program.cs:line 19

the files in the array images :

this is how i'm using it in form1 :

RadarPixels rp = new RadarPixels(radarImages,
                new Bitmap(Image.FromFile(@"D:\123.png")),
                new Bitmap(Image.FromFile(@"D:\2.jpg")));

Maybe the problem is because i'm displaying the images in pictureBox before changing the sizes ? maybe because the images are in use ?