问:
creating a dataframe using lists
I am trying to create a dataframe that looks like this excel sheet but I can't figure out how to do so. Here is the code I am attempting to use

```<code>import pandas as pd
ls_super = ['Supernatant',total_volume_super_ml, Total_activity_super, total_protein_super_mg, specific_activity_sup, 100, 1]
df3 = pd.DataFrame(ls_super, columns =['Sample','Total Volume','Total activity','Total protein','Specific Activity','percent yield,','purification'
])
</code>```

Here is the error message: ValueError                                Traceback (most recent call last)
/tmp/ipykernel_125580/4224246098.py in
20
21 # list of strings
---> 22 df3 = pd.DataFrame(ls_super, columns =['Sample','Total Volume','Total activity','Total protein','Specific Activity','percent yield,','purification'
23 ])
24

~/.local/lib/python3.8/site-packages/pandas/core/frame.py in init(self, data, index, columns, dtype, copy)
709                     )
710                 else:
--> 711                     mgr = ndarray_to_mgr(
712                         data,
713                         index,

~/.local/lib/python3.8/site-packages/pandas/core/internals/construction.py in ndarray_to_mgr(values, index, columns, dtype, copy, typ)
322     )
323
--> 324     _check_values_indices_shape_match(values, index, columns)
325
326     if typ == "array":

~/.local/lib/python3.8/site-packages/pandas/core/internals/construction.py in _check_values_indices_shape_match(values, index, columns)
391         passed = values.shape
392         implied = (len(index), len(columns))
--> 393         raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
394
395

ValueError: Shape of passed values is (7, 1), indices imply (7, 7)

答:
```<code>import pandas as pd

first_row_list = [
    "Supernatant",
    total_volume_super_ml,
    Total_activity_super,
    total_protein_super_mg,
    specific_activity_sup,
    100,
    1
]

columns = [
    "Sample",
    "Total Volume",
    "Total Activity",
    "Total protein",
    "Specific Activity",
    "percent yield",
    "purification"
]

d = dict(zip(columns, [[f] for f in first_row_list]))
df = pd.DataFrame(d)
</code>```

or

```<code>d = {'Sample': ["Supernatant"],
      'Total Volume': [total_volume_super_ml],
      'Total Acitivity': [Total_activity_super],
      'Total protein': [total_protein_super_mg],
      'Specific Activity': [specific_activity_sup],
      'percent yield': [100],
      'purification': [1]}

df = pd.DataFrame(d)
</code>```

Title: creating a dataframe using lists

Body:
I am trying to create a dataframe that looks like this excel sheet but I can't figure out how to do so. Here is the code I am attempting to use

import pandas as pd
ls_super = ['Supernatant',total_volume_super_ml, Total_activity_super, total_protein_super_mg, specific_activity_sup, 100, 1]
df3 = pd.DataFrame(ls_super, columns =['Sample','Total Volume','Total activity','Total protein','Specific Activity','percent yield,','purification'
])

Here is the error message: ValueError                                Traceback (most recent call last)
/tmp/ipykernel_125580/4224246098.py in
20
21 # list of strings
---> 22 df3 = pd.DataFrame(ls_super, columns =['Sample','Total Volume','Total activity','Total protein','Specific Activity','percent yield,','purification'
23 ])
24

~/.local/lib/python3.8/site-packages/pandas/core/frame.py in init(self, data, index, columns, dtype, copy)
709                     )
710                 else:
--> 711                     mgr = ndarray_to_mgr(
712                         data,
713                         index,

~/.local/lib/python3.8/site-packages/pandas/core/internals/construction.py in ndarray_to_mgr(values, index, columns, dtype, copy, typ)
322     )
323
--> 324     _check_values_indices_shape_match(values, index, columns)
325
326     if typ == "array":

~/.local/lib/python3.8/site-packages/pandas/core/internals/construction.py in _check_values_indices_shape_match(values, index, columns)
391         passed = values.shape
392         implied = (len(index), len(columns))
--> 393         raise ValueError(f"Shape of passed values is {passed}, indices imply {implied}")
394
395

ValueError: Shape of passed values is (7, 1), indices imply (7, 7)

Body:
import pandas as pd

first_row_list = [
    "Supernatant",
    total_volume_super_ml,
    Total_activity_super,
    total_protein_super_mg,
    specific_activity_sup,
    100,
    1
]

columns = [
    "Sample",
    "Total Volume",
    "Total Activity",
    "Total protein",
    "Specific Activity",
    "percent yield",
    "purification"
]

d = dict(zip(columns, [[f] for f in first_row_list]))
df = pd.DataFrame(d)

or

d = {'Sample': ["Supernatant"],
      'Total Volume': [total_volume_super_ml],
      'Total Acitivity': [Total_activity_super],
      'Total protein': [total_protein_super_mg],
      'Specific Activity': [specific_activity_sup],
      'percent yield': [100],
      'purification': [1]}

df = pd.DataFrame(d)


来源: stackexchange

问:
C++ loop until keystroke
If I want to loop until a keystroke there is a quite nice Windows solution:

```<code>while(!kbhit()){
    //...
}
</code>```

But this is neither an ISO-Function nor works on other Operating Systems except MS Win. I found other cross-plattform solutions but they are quite confusing and bloated - isn't there another easy way to manage this?

答:
You can use the next version of kbhit() for *nix OSes:</p>

```<code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: C++ loop until keystroke

Body:
If I want to loop until a keystroke there is a quite nice Windows solution:

while(!kbhit()){
    //...
}

But this is neither an ISO-Function nor works on other Operating Systems except MS Win. I found other cross-plattform solutions but they are quite confusing and bloated - isn't there another easy way to manage this?

Body:
You can use the next version of kbhit() for *nix OSes:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}


问:
Apply onClick functions based on conditions within components React
I have a component which renders a bunch of components called ActionItem

```<code>            <ActionItem title={'Client Assigned'} icon={<MdOutlineAssignmentTurnedIn />} />
            <ActionItem title={'Inital Client Follow Up'} icon={<BsFillPersonCheckFill />} />
            <ActionItem title={'Validated Need'} icon={<BiDonateHeart />} />

            <ActionItem title={'Initiated Discovery'} icon={<RiCompassDiscoverLine />} />
            <ActionItem title={'Service In Progress'} icon={<GiProgression />} />
            <ActionItem title={'Fulfilled The Need'} icon={<ImCheckmark />} />
</code>```

Inside of my ActionItem I have a function: handleToggle() which fires  onClick and pretty much adds or removes an "active" class. I want this function available to every component EXCEPT the one with the title of 'Client Assigned'

ActionItem component:

```<code>  const [toggleItem, setToggleItem] = useState(false)
  const [date, setDate] = useState('')

  const handleToggle = () => {

    setToggleItem(!toggleItem)
    setDate(new Date())
    if (date !== '') {
      setDate('')
    }

  }

  useEffect(() => {
    title === 'Client Assigned' ? handleToggle() : null
  }, [])

  return (
    <React.Fragment>
      <div className={toggleItem ? 'ReportsModal' : 'ReportsModal not-active'}>
        <span
          style={title === 'Fulfilled The Need' ? (
            { borderColor: 'green', backgroundColor: 'green', color: '#fff' }
          ) : null}
          className={'hover'}
          onClick={title === 'Client Assigned' ? handleToggle : null}>
          {icon}
        </span>
        <div>
          <h3>{title}</h3>
          <p>{date !== '' ? moment(date).format('D MMM YYYY') : date}</p>
          {toggleItem ? (
            <h5 onClick={handleInitComment} className='hover'><AiOutlinePlusCircle style={iconStyles} /> Add Comment</h5>
          ) : null}

        </div>
      </div>
</code>```

the conditional I am trying to use is currently not working. Any advice?

答:
You can create an array of banned/prohibited titles and use an AND operator in the onClick prop. For example:</p>
```<code>function Component({ title, handleToggle }) {
  const bannedTitles = ["Client Assigned"];

  useEffect(() => {
    title === "Client Assigned" ? handleToggle() : null;
  }, []);

  return (
    <>
      <div
        onClick={() => !bannedTitles.includes(title) && handleToggleItem()}
      />
    </>
  );
}

export default Component;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a component which renders a bunch of components called ActionItem

            <ActionItem title={'Client Assigned'} icon={<MdOutlineAssignmentTurnedIn />} />
            <ActionItem title={'Inital Client Follow Up'} icon={<BsFillPersonCheckFill />} />
            <ActionItem title={'Validated Need'} icon={<BiDonateHeart />} />

            <ActionItem title={'Initiated Discovery'} icon={<RiCompassDiscoverLine />} />
            <ActionItem title={'Service In Progress'} icon={<GiProgression />} />
            <ActionItem title={'Fulfilled The Need'} icon={<ImCheckmark />} />

Inside of my ActionItem I have a function: handleToggle() which fires  onClick and pretty much adds or removes an "active" class. I want this function available to every component EXCEPT the one with the title of 'Client Assigned'

ActionItem component:

  const [toggleItem, setToggleItem] = useState(false)
  const [date, setDate] = useState('')

  const handleToggle = () => {

    setToggleItem(!toggleItem)
    setDate(new Date())
    if (date !== '') {
      setDate('')
    }

  }

  useEffect(() => {
    title === 'Client Assigned' ? handleToggle() : null
  }, [])

  return (
    <React.Fragment>

          {icon}

{title}

{date !== '' ? moment(date).format('D MMM YYYY') : date}

          {toggleItem ? (

<AiOutlinePlusCircle style={iconStyles} /> Add Comment

          ) : null}

the conditional I am trying to use is currently not working. Any advice?

Body:
You can create an array of banned/prohibited titles and use an AND operator in the onClick prop. For example:

function Component({ title, handleToggle }) {
  const bannedTitles = ["Client Assigned"];

  useEffect(() => {
    title === "Client Assigned" ? handleToggle() : null;
  }, []);

  return (
    <>
      <div
        onClick={() => !bannedTitles.includes(title) && handleToggleItem()}
      />
    </>
  );
}

export default Component;


问:
Independent reactions are interacting in a Shiny App
I'm using the sliderInput function with the animate argument to perform an automatic calculation in my shinyApp. However, using animate is affecting other reactions in my app. I would like to stop this side effect that is occurring in other reactivities.

For example, I have a dropdownMenu inside an if else structure. But, because of the animate argument, I can't click the option in the top right corner when I start the animation. It is disappearing with each calculation that the animate is doing. See:

I tried use isolate() in pred_1() but it stop the valueBox and the conditional structure (if else structure).

I'd like to just make animate not affect other reactivity in the app.

My app:

```<code>library(shiny)
library(shinydashboard)

header <- dashboardHeader(

  title = "Dashboard",
  titleWidth = 300,

  dropdownMenuOutput(
    outputId = "drop1"
  )

)

sidebar <- dashboardSidebar(

  width = 300

)

body <- dashboardBody(

  sliderInput(
    inputId = "one",
    label = "Registro 1",
    value = 1,
    animate = animationOptions(
      interval = 500, loop = TRUE
    ),
    min = 1,
    max = 10,
    step = 1,
    ticks = TRUE
  ),

  sliderInput(
    inputId = "two",
    label = "Registro 2",
    value = 1,
    animate = animationOptions(
      interval = 500, loop = TRUE
    ),
    min = 1,
    max = 10,
    step = 1,
    ticks = TRUE
  ),

  sliderInput(
    inputId = "three",
    label = "Sum 3",
    value = 1,
    animate = animationOptions(
      interval = 500, loop = TRUE
    ),
    min = 1,
    max = 10,
    step = 1,
    ticks = TRUE
  ),

  valueBoxOutput(
    outputId = "box1"
  )

)

ui <- dashboardPage(

  header = header,
  sidebar = sidebar,
  body = body

)

server <- function(session, input, output) {

  fx <- function(x, y) {

    x + y

  }

  fy <- function(x) {

    x

  }

  reac_0 <- reactive({

    tibble::tibble(
      one = input$one,
      two = input$two,
      three = input$three
    )

  })

  chuveiro <- reactive({

    temp <- reac_0()
    fx(
      x = temp$one,
      y = temp$two
    )

  })

  luz <- reactive({

    temp <- reac_0()
    fy(
      x = temp$three
    )

  })

  fdrop <- function(x) {

    if (x <= 5) {

      dropdownMenu(
        type = "notifications",
        badgeStatus = NULL,
        headerText = "Not 1",
        notificationItem(
          text = HTML(
            "<text style='color:#020202;'>Without.</text>"
          ),
          status = "danger",
          icon = icon("times"),
          href = NULL
        )
      )

    } else (
      dropdownMenu(
        type = "notifications",
        badgeStatus = "danger",
        headerText = "Not 2",
        notificationItem(
          text = HTML(
            "<a style='color:#020202;'
          href='https://www.instagram.com' target='_blank' title='A'>
          With</a>"
          ),
          status = "success",
          icon = icon("tags")
        )
      )
    )
  }

  output$drop1 <- renderMenu({

    expr = fdrop(x = luz())

  })

  output$box1 <- renderValueBox({

    expr = valueBox(
      value = chuveiro(),
      subtitle = "Sum"
    )

  })

}

shinyApp(ui, server)
</code>```

So how can I make one reactivity effect another in a shinyApp?

I would like to click normally on the dropdownMenu notification with the sliderInput working with animate.

I tried isolating each argument of sliderInput, but not work.

答:
The reac0() reactive is triggered whenever an input changes. Then it triggers every reactive that includes it, even if the value used in that reactive has not changed.

Your code :

```<code>reac_0 <- reactive({
  tibble::tibble(
    one = input$one,
    two = input$two,
    three = input$three
  )
})

luz <- reactive({
  temp <- reac_0()
  fy(
    x = temp$three
  )
})
</code>```

triggers luz() whenever one, two or three changes.

An alternative would be to use input$three directly:

```<code>luz <- reactive({
  fy(
    x = input$three
  )
})
</code>```

This way, the change or animation of slider one and two won't trigger luz() which won't trigger the menu rendering.

Of course, since the value of slider three is used to render the menu, any update of its value has to trigger the menu rendering.

Body:
I'm using the sliderInput function with the animate argument to perform an automatic calculation in my shinyApp. However, using animate is affecting other reactions in my app. I would like to stop this side effect that is occurring in other reactivities.

For example, I have a dropdownMenu inside an if else structure. But, because of the animate argument, I can't click the option in the top right corner when I start the animation. It is disappearing with each calculation that the animate is doing. See:

I tried use isolate() in pred_1() but it stop the valueBox and the conditional structure (if else structure).

I'd like to just make animate not affect other reactivity in the app.

My app:

library(shiny)
library(shinydashboard)

header <- dashboardHeader(

  title = "Dashboard",
  titleWidth = 300,

  dropdownMenuOutput(
    outputId = "drop1"
  )

)

sidebar <- dashboardSidebar(

  width = 300

)

body <- dashboardBody(

  sliderInput(
    inputId = "one",
    label = "Registro 1",
    value = 1,
    animate = animationOptions(
      interval = 500, loop = TRUE
    ),
    min = 1,
    max = 10,
    step = 1,
    ticks = TRUE
  ),

  sliderInput(
    inputId = "two",
    label = "Registro 2",
    value = 1,
    animate = animationOptions(
      interval = 500, loop = TRUE
    ),
    min = 1,
    max = 10,
    step = 1,
    ticks = TRUE
  ),

  sliderInput(
    inputId = "three",
    label = "Sum 3",
    value = 1,
    animate = animationOptions(
      interval = 500, loop = TRUE
    ),
    min = 1,
    max = 10,
    step = 1,
    ticks = TRUE
  ),

  valueBoxOutput(
    outputId = "box1"
  )

)

ui <- dashboardPage(

  header = header,
  sidebar = sidebar,
  body = body

)

server <- function(session, input, output) {

  fx <- function(x, y) {

    x + y

  }

  fy <- function(x) {

    x

  }

  reac_0 <- reactive({

    tibble::tibble(
      one = input$one,
      two = input$two,
      three = input$three
    )

  })

  chuveiro <- reactive({

    temp <- reac_0()
    fx(
      x = temp$one,
      y = temp$two
    )

  })

  luz <- reactive({

    temp <- reac_0()
    fy(
      x = temp$three
    )

  })

  fdrop <- function(x) {

    if (x <= 5) {

      dropdownMenu(
        type = "notifications",
        badgeStatus = NULL,
        headerText = "Not 1",
        notificationItem(
          text = HTML(
            "<text style='color:#020202;'>Without.</text>"
          ),
          status = "danger",
          icon = icon("times"),
          href = NULL
        )
      )

    } else (
      dropdownMenu(
        type = "notifications",
        badgeStatus = "danger",
        headerText = "Not 2",
        notificationItem(
          text = HTML(
            "
          With"
          ),
          status = "success",
          icon = icon("tags")
        )
      )
    )
  }

  output$drop1 <- renderMenu({

    expr = fdrop(x = luz())

  })

  output$box1 <- renderValueBox({

    expr = valueBox(
      value = chuveiro(),
      subtitle = "Sum"
    )

  })

}

shinyApp(ui, server)

So how can I make one reactivity effect another in a shinyApp?

I would like to click normally on the dropdownMenu notification with the sliderInput working with animate.

I tried isolating each argument of sliderInput, but not work.

Body:
The reac0() reactive is triggered whenever an input changes. Then it triggers every reactive that includes it, even if the value used in that reactive has not changed.

Your code :

reac_0 <- reactive({
  tibble::tibble(
    one = input$one,
    two = input$two,
    three = input$three
  )
})

luz <- reactive({
  temp <- reac_0()
  fy(
    x = temp$three
  )
})

triggers luz() whenever one, two or three changes.

An alternative would be to use input$three directly:

luz <- reactive({
  fy(
    x = input$three
  )
})

This way, the change or animation of slider one and two won't trigger luz() which won't trigger the menu rendering.

Of course, since the value of slider three is used to render the menu, any update of its value has to trigger the menu rendering.


问:
Is there a way to rebuild a Laravel site if I have all the files locally?
I got tasked with fixing a site that I have no access to the host. I have the entire site directory, and the site is built on Laravel framework. Can someone give me directions or point me to a guide on taking this site directory and setting it up locally either in WAMP or Docker and getting the database set back up so that I can work on fixing the issues to the site and re-uploading it to a new host?</p>

答:
Install laragon, then create an empty folder in the C:/laragon/www folder and move your files there.

Using heidi sql in laragon, create a database for the project.

Run your migrations.

Start laragon and all should go well.


问:
The bundle's Info.plist does not contain a CFBundleVersion key or its value is not a string
Xcode is build the project and when build is success, I get this message "The bundle's Info.plist does not contain a CFBundleVersion key or its value is not a string". What is that mean. There is my info.plist:</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key></key>
    <string></string>
    <key>Additional_Version_String</key>
    <string>Updated on build</string>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
    <key>CFBundleIcons</key>
    <dict/>
    <key>CFBundleIcons~ipad</key>
    <dict/>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>Commit_Short_Hash</key>
    <string>Updated on build</string>
    <key>ITSAppUsesNonExemptEncryption</key>
    <false/>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSContactsUsageDescription</key>
    <string>Vialer needs access to your contacts to make calling to your contacts possible</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>Vialer needs access to your microphone to make calling possible</string>
    <key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
        <string>fetch</string>
        <string>remote-notification</string>
        <string>voip</string>
    </array>
    <key>UIMainStoryboardFile</key>
    <string>MainStoryboard</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIRequiresPersistentWiFi</key>
    <true/>
    <key>UIStatusBarStyle</key>
    <string>UIStatusBarStyleBlackTranslucent</string>
    <key>UIStatusBarTintParameters</key>
    <dict>
        <key>UINavigationBar</key>
        <dict>
            <key>Style</key>
            <string>UIBarStyleDefault</string>
            <key>Translucent</key>
            <true/>
        </dict>
    </dict>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <true/>
</dict>
</plist>
</code>```

答: I just edit my project's ".plist" file and added a CFBundleShortVersionString entry with some value.

Body:
Xcode is build the project and when build is success, I get this message "The bundle's Info.plist does not contain a CFBundleVersion key or its value is not a string". What is that mean. There is my info.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key></key>
    <string></string>
    <key>Additional_Version_String</key>
    <string>Updated on build</string>
    <key>CFBundleDevelopmentRegion</key>
    <string>en</string>
    <key>CFBundleDisplayName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundleExecutable</key>
    <string>${EXECUTABLE_NAME}</string>
    <key>CFBundleIcons</key>
    <dict/>
    <key>CFBundleIcons~ipad</key>
    <dict/>
    <key>CFBundleIdentifier</key>
    <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>${PRODUCT_NAME}</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleShortVersionString</key>
    <string>1.0</string>
    <key>CFBundleVersion</key>
    <string>1</string>
    <key>Commit_Short_Hash</key>
    <string>Updated on build</string>
    <key>ITSAppUsesNonExemptEncryption</key>
    <false/>
    <key>LSRequiresIPhoneOS</key>
    <true/>
    <key>NSContactsUsageDescription</key>
    <string>Vialer needs access to your contacts to make calling to your contacts possible</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>Vialer needs access to your microphone to make calling possible</string>
    <key>UIBackgroundModes</key>
    <array>
        <string>audio</string>
        <string>fetch</string>
        <string>remote-notification</string>
        <string>voip</string>
    </array>
    <key>UIMainStoryboardFile</key>
    <string>MainStoryboard</string>
    <key>UIRequiredDeviceCapabilities</key>
    <array>
        <string>armv7</string>
    </array>
    <key>UIRequiresPersistentWiFi</key>
    <true/>
    <key>UIStatusBarStyle</key>
    <string>UIStatusBarStyleBlackTranslucent</string>
    <key>UIStatusBarTintParameters</key>
    <dict>
        <key>UINavigationBar</key>
        <dict>
            <key>Style</key>
            <string>UIBarStyleDefault</string>
            <key>Translucent</key>
            <true/>
        </dict>
    </dict>
    <key>UISupportedInterfaceOrientations</key>
    <array>
        <string>UIInterfaceOrientationPortrait</string>
    </array>
    <key>UIViewControllerBasedStatusBarAppearance</key>
    <true/>
</dict>
</plist>


问:
Theory of storing a number and text in same SQL field
I have a three tables

Results:
TestID
TestCode
Value

Tests:
TestID
TestType
SysCodeID

SystemCodes
SysCodeID
ParentSysCodeID
Description

The question I have is for when the user is entering data into the results table.

The formatting code when the row gets the focus changes the value field to a dropdown combobox if the testCode is of type SystemList.  The drop down has a list of all the system codes that have a parentsyscodeID of the test.SysCodeID.  When the user chooses a value in the list it translates into a number which goes into the value field.

The datatype of the Results.Value field is integer.  I made it an integer instead of a string because when reporting it is easier to do calculations and sorting if it is a number.  There are issues if you are putting integer/decimal value into a string field.  As well, when the system was being designed they only wanted numbers in there.

The users now want to put strings into the value field as well as numbers/values from a list and I'm wondering what the best way of doing that would be.

Would it be bad practice to convert the field over to a string and then store both strings and integers in the same field?  There are different issues related to this one but i'm not sure if any are a really big deal.

Should I add another column into the table of string datatype and  if the test is a string type then put the data the user enters into the different field.

Another option would be to create a 1-1 relationship to another table and if the user types in a string into the value field it adds it into the new table with a key of a number.

Anyone have any interesting ideas?

答: I think the easiest way to do it would be to convert Results.Value to a "string" (char, varchar, whatever). Yes, this ruins the ability to do numeric sorting (and you won't be able to do a cast or convert on the column any longer since text will be intermingled with integer values), but I think any other method would be too complex to maintain properly. (For example, in the 1-1 case you mentioned, is that integer value the actual value or a foreign key to the string table? Now we need another column to determine that.)</p>

OwnerDisplayName: Jaydel Gluckie

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Michael Todd


答:
Problem: the DataFrame() constructor insists on interpreting the one-dimensional python list ls_super as 1 column and 7 rows ("Shape of passed values is (7, 1)"), as opposed to 1 row with 7 columns (which would have shape=(1, 7)).

Solution: add a second set of brackets ([]) around your definition of the ls_super list. In other words, make ls_super a two-dimensional list. The DataFrame constructor then sees a single value in the first dimension, and seven values in the second dimension, producing the desired shape of (1, 7).

```<code>ls_super = [['Supernatant',1, 2, 3, 4, 100, 1]]

df3 = pd.DataFrame(ls_super,
                   columns=['Sample', 'Total Volume', 'Total activity', 'Total protein', 'Specific Activity', 'percent yield', 'purification'])
</code>```

Title: creating a dataframe using lists

Body:
Problem: the DataFrame() constructor insists on interpreting the one-dimensional python list ls_super as 1 column and 7 rows ("Shape of passed values is (7, 1)"), as opposed to 1 row with 7 columns (which would have shape=(1, 7)).

Solution: add a second set of brackets ([]) around your definition of the ls_super list. In other words, make ls_super a two-dimensional list. The DataFrame constructor then sees a single value in the first dimension, and seven values in the second dimension, producing the desired shape of (1, 7).

ls_super = [['Supernatant',1, 2, 3, 4, 100, 1]]

df3 = pd.DataFrame(ls_super,
                   columns=['Sample', 'Total Volume', 'Total activity', 'Total protein', 'Specific Activity', 'percent yield', 'purification'])


答:
In pandas dataframe your input could be an a list of list.</p>
```<code>import pandas as pd
from random import uniform

total_volume_super_ml = uniform(0,1)
Total_activity_super = uniform(0,1)
total_protein_super_mg = uniform(0,1)
specific_activity_sup = uniform(0,1)

ls_super = ['Supernatant',total_volume_super_ml, Total_activity_super, total_protein_super_mg, specific_activity_sup, 100, 1]
df3 = pd.DataFrame([ls_super], columns =['Sample','Total Volume','Total activity','Total protein','Specific Activity','percent yield','purification'])
df3
</code>```

Title: creating a dataframe using lists

Body:
In pandas dataframe your input could be an a list of list.

import pandas as pd
from random import uniform

total_volume_super_ml = uniform(0,1)
Total_activity_super = uniform(0,1)
total_protein_super_mg = uniform(0,1)
specific_activity_sup = uniform(0,1)

ls_super = ['Supernatant',total_volume_super_ml, Total_activity_super, total_protein_super_mg, specific_activity_sup, 100, 1]
df3 = pd.DataFrame([ls_super], columns =['Sample','Total Volume','Total activity','Total protein','Specific Activity','percent yield','purification'])
df3


问:
R with dplyr rename, avoid error if column doesn't exist AND create new column with NAs
We are looking to rename columns in a dataframe in R, however the columns may be missing and this throws an error:

```<code>my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))
my_df %>% dplyr::rename(aa = a, bb = b, cc = c)

Error: Can't rename columns that don't exist.
x Column `c` doesn't exist.
</code>```

our desired output is this, which creates a new column with NA values if the original column does not exist:

```<code>> my_df
  aa bb  c
1  1  4 NA
2  2  5 NA
3  3  6 NA
</code>```

答:
You can use a named vector with any_of() to rename that won't error on missing variables.  I'm uncertain of a dplyr way to then create the missing vars but it's easy enough in base R.

```<code>library(dplyr)

cols <- c(aa = "a", bb = "b", cc = "c")

my_df %>%
  rename(any_of(cols)) %>%
  `[<-`(., , setdiff(names(cols), names(.)), NA)

  aa bb cc
1  1  4 NA
2  2  5 NA
3  3  6 NA
</code>```

Body:
We are looking to rename columns in a dataframe in R, however the columns may be missing and this throws an error:

my_df <- data.frame(a = c(1,2,3), b = c(4,5,6))
my_df %>% dplyr::rename(aa = a, bb = b, cc = c)

Error: Can't rename columns that don't exist.
x Column `c` doesn't exist.

our desired output is this, which creates a new column with NA values if the original column does not exist:

> my_df
  aa bb  c
1  1  4 NA
2  2  5 NA
3  3  6 NA

Body:
You can use a named vector with any_of() to rename that won't error on missing variables.  I'm uncertain of a dplyr way to then create the missing vars but it's easy enough in base R.

library(dplyr)

cols <- c(aa = "a", bb = "b", cc = "c")

my_df %>%
  rename(any_of(cols)) %>%
  `[<-`(., , setdiff(names(cols), names(.)), NA)

  aa bb cc
1  1  4 NA
2  2  5 NA
3  3  6 NA


问:
Domain Host cant connect to the server filezilla
can I use Filezilla to upload files to my free WordPress domain website or should the domain be not-free to do this also does the free domain from WordPress comes with a password to type in the password field in Filezilla?

also, I don't know what to type in the password field in Filezilla I don't know which password does it mean?

sorry :frowning: I'm a beginner in this field and I don't know much

答:
Welcome, so to upload via FTP/SFTP you will need to set up credentials with your host ie. goDaddy.

Once you have them set up you will have something that looks like this:

Host:
Username:
Password:
Port:

Put these into FileZilla which will point you to the webspace of your contract.


问:
Why NaN/NA is NaN?
```<code>R> 1/NA
[1] NA
R> NaN/NA
[1] NaN
</code>```

A number divided by NA is NA. NaN is not even a number. So it is more reasonable to define NaN divided by NA as NA.

I don't understand the logic of defining it as NaN. Is it a careful design choice of R? Or it is just a haphazard choice that was stuck at the birth of R or S.

I don't need any guessed answer to this question. I need an authoritative answer from the original designers of R that carefully thought about this case.

答:
You could just consult the documentation, written by R's maintainers. From ?NaN:

Computations involving NaN will return NaN or perhaps NA: which of those two is not guaranteed and may depend on the R platform (since compilers may re-order computations).

On my machine, the following return NA_real_, not NaN:

NaN / NA
NA / NaN

NaN / NA_integer_
NA_integer_ / NaN

NaN / NA_real_
NA_real_ / NaN
```
<h3>Internals, performance, etc.</h3>
<p>At C level, <code>NaN</code> and <code>NA_real_</code> are two types of IEEE 754 <code>NaN</code>s, distinguished only by the bits in the significand field of the <code>double</code>. Meanwhile, <code>NA</code> and <code>NA_integer_</code> are both <code>INT_MIN</code>.</p>
<p>To ensure that arithmetic involving <code>NaN</code> produces consistent results across platforms, R would need to do the following for <em>every</em> operation <code>z = a <op> b</code>:</p>
<ul>
<li>Check whether <code>z</code> is <code>NaN</code>.
<ul>
<li>If it is, check whether <code>z</code> is an <code>NaN</code> of the desired type.
<ul>
<li>If it isn't, set <code>z</code> equal to an <code>NaN</code> of the desired type.</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>These checks would incur an unacceptable performance cost.</p>
<p>Ultimately, the current behaviour is a compromise, favouring speed over consistency. It is left to users and package developers to decide whether consistency is important enough to justify doing something like:</p>
<pre class="lang-r prettyprint-override"><code>z <- a + b
z[is.nan(z)] <- NA
</code>```

Considering that most users rarely encounter NaN and that most packages don't attempt to distinguish it from NA_real_, I would say that this design makes a lot of sense.

References

FWIW, here are four related threads:

NA_real_ <op> NaN -> NA or NaN, should we care?, R-devel, Apr 2009 [1] [2]

Question re: NA, NaNs in R, R-devel, Feb 2014 [3]

1954 from NA, R-devel, May 2021 [4]

Difference between NA_real_ and NaN, Stack Overflow, Dec 2021 [5]

The first three received several comments from members of the R Core Team. R-devel is a better forum for these kinds of questions, in general...

Title: Why NaN/NA is NaN?

Body:
R> 1/NA
[1] NA
R> NaN/NA
[1] NaN

A number divided by NA is NA. NaN is not even a number. So it is more reasonable to define NaN divided by NA as NA.

I don't understand the logic of defining it as NaN. Is it a careful design choice of R? Or it is just a haphazard choice that was stuck at the birth of R or S.

I don't need any guessed answer to this question. I need an authoritative answer from the original designers of R that carefully thought about this case.

Body:
You could just consult the documentation, written by R's maintainers. From ?NaN:

Computations involving NaN will return NaN or perhaps NA: which of those two is not guaranteed and may depend on the R platform (since compilers may re-order computations).

On my machine, the following return NA_real_, not NaN:

NaN / NA
NA / NaN

NaN / NA_integer_
NA_integer_ / NaN

NaN / NA_real_
NA_real_ / NaN

Internals, performance, etc.

At C level, NaN and NA_real_ are two types of IEEE 754 NaNs, distinguished only by the bits in the significand field of the double. Meanwhile, NA and NA_integer_ are both INT_MIN.

To ensure that arithmetic involving NaN produces consistent results across platforms, R would need to do the following for every operation z = a <op> b:

Check whether z is NaN.

If it is, check whether z is an NaN of the desired type.

If it isn't, set z equal to an NaN of the desired type.

These checks would incur an unacceptable performance cost.

Ultimately, the current behaviour is a compromise, favouring speed over consistency. It is left to users and package developers to decide whether consistency is important enough to justify doing something like:

z <- a + b
z[is.nan(z)] <- NA

Considering that most users rarely encounter NaN and that most packages don't attempt to distinguish it from NA_real_, I would say that this design makes a lot of sense.

References

FWIW, here are four related threads:

NA_real_ <op> NaN -> NA or NaN, should we care?, R-devel, Apr 2009 [1] [2]

Question re: NA, NaNs in R, R-devel, Feb 2014 [3]

1954 from NA, R-devel, May 2021 [4]

Difference between NA_real_ and NaN, Stack Overflow, Dec 2021 [5]

The first three received several comments from members of the R Core Team. R-devel is a better forum for these kinds of questions, in general...


问:
Mac OS X Lion, scrollbars, and website usability
I have a number of overflowed divs that I use to display a lot of content in small space (like long lists, etc). Giving the divs the CSS rule of overflow: auto; always worked like a charm, giving the user scroll bars to indicate more content was available.

This is kinda thrown out the window with Mac OS X Lion, which (as a default) hides the scroll bars unless you're actively scrolling. I like it when dealing with an application on my computer, because I think there are very strong visual clues that you can scroll to see more content. On webpage elements, it's a lot less clear, and I'm worried that my users won't know there's more content available (case in point: StackOverflow's "Questions with similar titles" when entering in a new question is a good example of this).

Is this a legitimate concern, or will Lion users know that if something appears to be cut off, it indicates that scrolling might be available? Are there any workarounds to, say, force browsers running on Lion to render scroll bars if it's an element on the page (and not the page itself)??

答:
Lion does take care of this itself by flashing the scrollbars on any scrollable element for an instant when it comes into view, giving the user an initial hint that there's more to scroll to. Of course, the user may or may not notice this. If the user is used to the Lion way of doing things, your website won't be the only place this happens and the user probably knows how to deal with it. If your boxen look "unscrollable" without scrollbars, you might want to give a stronger indication that they are scrollable, e.g. by having a clear border around the box with some cut-off content inside. This may be something you will want to do regardless of Lion.

If you can improve your UI to make scrollability more obvious, do it either way. Otherwise, if your content is presented in a way that suggests there's more, I wouldn't worry about missing scrollbars on a system were the user should be used to it.

You may want to take this to https://ux.stackexchange.com/ for some real expert opinions.


问:
How to click all arrow buttons within a dynamic table on website?
On this website (https://www.tradingview.com/symbols/NASDAQ-TSLA/financials-income-statement/), there is a table with clickable arrows on some of the rows. I've been trying to use Python Selenium and 'driver.find_elements_by_xpath' to find the arrows (within the table only) and continue clicking on the arrows until all of the rows within table have been fully expanded before scraping, but have been struggling.

The xpath to some of these arrows shown below, but there are some hidden arrows, which will only become visible to click once the first arrow is clicked

```<code>//span[@class='arrow-jKD0Exn-']//*[name()='svg']
</code>```

答:
The arrows has class name jKD0Exn use that element to click then search for the next one

Example for CSS Selector

```<code>div.container-jKD0Exn-:nth-child(2) > div:nth-child(2) > span:nth-child(2)
</code>```

Body:
On this website (https://www.tradingview.com/symbols/NASDAQ-TSLA/financials-income-statement/), there is a table with clickable arrows on some of the rows. I've been trying to use Python Selenium and 'driver.find_elements_by_xpath' to find the arrows (within the table only) and continue clicking on the arrows until all of the rows within table have been fully expanded before scraping, but have been struggling.

The xpath to some of these arrows shown below, but there are some hidden arrows, which will only become visible to click once the first arrow is clicked

//span[@class='arrow-jKD0Exn-']//*[name()='svg']

Body:
The arrows has class name jKD0Exn use that element to click then search for the next one

Example for CSS Selector

div.container-jKD0Exn-:nth-child(2) > div:nth-child(2) > span:nth-child(2)


问:
Why use nested blocks?
I just came across this piece of code in base64 crate:

```<code> buffer.resize(decoded_len_estimate, 0);

let bytes_written;
{
    let buffer_slice = &mut buffer.as_mut_slice()[starting_output_len..];
    bytes_written = decode_helper(input_bytes, num_chunks, config, buffer_slice)?;
}

buffer.truncate(starting_output_len + bytes_written);
</code>```

See https://github.com/marshallpierce/rust-base64/blob/b63975f0a3d2e724c611bf6cd7213ae6bcb065a3/src/decode.rs#L165-L169

What is the reason for using this style of declaring the variable bytes_written and then use this nested block. What problem does this solve? Why not just use this code:

```<code> buffer.resize(decoded_len_estimate, 0);

let buffer_slice = &mut buffer.as_mut_slice()[starting_output_len..];
let bytes_written = decode_helper(input_bytes, num_chunks, config, buffer_slice)?
buffer.truncate(starting_output_len + bytes_written);
</code>```

Can someone help me with that?

答: This code was written 4 years ago (5 Dec 2017), before NLL (Non-Lexical Lifetimes) arrived (6 Dec 2018). With NLL, the borrow checker consider a reference "alive" until its last use and no more. But without it, a reference is considered alive until the end of the scope (its drop). Since buffer_slice borrows buffer mutably, and the last line does that too, the borrow checker pre-NLL would err - and that's probably why they introduced the block, to create a new scope for buffer_slice so it will be dropped before the next borrow of buffer.

Title: Why use nested blocks?

Body:
I just came across this piece of code in base64 crate:

 buffer.resize(decoded_len_estimate, 0);

let bytes_written;
{
    let buffer_slice = &mut buffer.as_mut_slice()[starting_output_len..];
    bytes_written = decode_helper(input_bytes, num_chunks, config, buffer_slice)?;
}

buffer.truncate(starting_output_len + bytes_written);

See https://github.com/marshallpierce/rust-base64/blob/b63975f0a3d2e724c611bf6cd7213ae6bcb065a3/src/decode.rs#L165-L169

What is the reason for using this style of declaring the variable bytes_written and then use this nested block. What problem does this solve? Why not just use this code:

 buffer.resize(decoded_len_estimate, 0);

let buffer_slice = &mut buffer.as_mut_slice()[starting_output_len..];
let bytes_written = decode_helper(input_bytes, num_chunks, config, buffer_slice)?
buffer.truncate(starting_output_len + bytes_written);

Can someone help me with that?


问:
How to collect a list of random numbers in ranges?
I have a list of numbers not in order 8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205, and it is a very important to me to make this list of numbers in ranges, like this :  8-10,25,47-55,102,107,111,201-205,
I'm familiar with shell scripting, but i couldn't find any solution.

答:
As only shell and bash are tagged, here's a bash solution based on Parameter Expansion:

This iterates over the list of numbers, and with each new number adjusts the final part of the target string accordingly.

list=
for n in 8 9 10 25 47 48 49 50 51 52 53 54 55 102 107 111 201 202 203 204 205; do
  a=${list##*,} b=${a#*-} c=${a%-*} list=${list%$a}
  if ((n > b+1)); then list+=$a,$n
  elif ((n > c)); then list+=$c-$n
  else list+=$n; fi
done
echo ${list:1}
```
```8-10,25,47-55,102,107,111,201-205
```

If your numbers are stored in an array, loop over that instead, as in for n in ${arrayvar[@]}; do.

If your input is a string of comma-separated numbers (similar to the output), either turn it into an array using arrayvar=(${strvar//,/ }), or iterate directly on the conversion for n in ${strvar//,/ }; do.

If you want to pipe in a file with each number on its own line, change the for loop into while read -r n; do.

If you need to sort the file's contents first, sort -n is the easiest way.

If you wish to sort it while being an array, either use mapfile -t arrayvar < <(printf '%s\n' "${arrayvar[@]}" | sort -n), or follow the solution from here: IFS=$'\n' arrayvar=($(sort -n <<< "${arrayvar[*]}")); unset IFS.

Body:
As only shell and bash are tagged, here's a bash solution based on Parameter Expansion:

This iterates over the list of numbers, and with each new number adjusts the final part of the target string accordingly.

list=
for n in 8 9 10 25 47 48 49 50 51 52 53 54 55 102 107 111 201 202 203 204 205; do
  a=${list##*,} b=${a#*-} c=${a%-*} list=${list%$a}
  if ((n > b+1)); then list+=$a,$n
  elif ((n > c)); then list+=$c-$n
  else list+=$n; fi
done
echo ${list:1}

8-10,25,47-55,102,107,111,201-205

If your numbers are stored in an array, loop over that instead, as in for n in ${arrayvar[@]}; do.

If your input is a string of comma-separated numbers (similar to the output), either turn it into an array using arrayvar=(${strvar//,/ }), or iterate directly on the conversion for n in ${strvar//,/ }; do.

If you want to pipe in a file with each number on its own line, change the for loop into while read -r n; do.

If you need to sort the file's contents first, sort -n is the easiest way.

If you wish to sort it while being an array, either use mapfile -t arrayvar < <(printf '%s\n' "${arrayvar[@]}" | sort -n), or follow the solution from here: IFS=$'\n' arrayvar=($(sort -n <<< "${arrayvar[*]}")); unset IFS.


问:
How to send an email when item is added to Cosmos DB with Azure Functions
I want to have a Cosmos DB trigger which gives me the added document, which I can use to send an email via Sendgrid.

Now I've already added the Cosmos DB trigger, and also the Sendgrid output, but I don't really know how to get the added document from the Cosmos DB.

Can anyone help?

```<code>// function.json
{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "restaurant",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "connection-string",
      "databaseName": "database-name",
      "collectionName": "collection-name",
      "createLeaseCollectionIfNotExists": true
    },
    {
      "type": "sendGrid",
      "name": "message",
      "direction": "out",
      "apiKey": "SENDGRID_API_KEY",
      "from": "from",
      "to": "{customerEmail}",
      "subject": "",
      "text": ""
    }
  ]
}
</code>```

答: The easiest way to do this is with Logic Apps. The new Logic Apps Standard has new connectors for Cosmos DB. There you could use the Cosmos DB Trigger to listen for new items and then add SendGrid to send the email.</p>

Body:
I want to have a Cosmos DB trigger which gives me the added document, which I can use to send an email via Sendgrid.

Now I've already added the Cosmos DB trigger, and also the Sendgrid output, but I don't really know how to get the added document from the Cosmos DB.

Can anyone help?

// function.json
{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "restaurant",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "connection-string",
      "databaseName": "database-name",
      "collectionName": "collection-name",
      "createLeaseCollectionIfNotExists": true
    },
    {
      "type": "sendGrid",
      "name": "message",
      "direction": "out",
      "apiKey": "SENDGRID_API_KEY",
      "from": "from",
      "to": "{customerEmail}",
      "subject": "",
      "text": ""
    }
  ]
}


问:
React SetState within a async function
I'm trying to learn React making a weather application and I have got stacked using the async/await function. Here is the trouble I'm facing..

I have a function which does a axios call to an api and then I'm trying to set some state variables. The think is that it seems the application is running the setState methods before the promise is resolved.

Here is the method that makes the axios call.

```<code>const fetchWeeklyWeather = async () => {

    try {
        let response = await axios.get(url);

        console.log('%cFetch Weekly Weather Response:', 'color: #bada55', response);

        setCurrentWeather(response.data.current);
        setWeeklyWeather(response.data.daily);
        setWeatherAlerts(response.data.alerts);
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }
}
</code>```

And I call that method on the componentDidMount like so:

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

    console.log("Current Weather", currentWeather);
    console.log("Weekly Weather", weeklyWeather);
    console.log("Weather alerts", weatherAlerts);

    formatData(weeklyWeather);
}, []);
</code>```

It is weird because sometimes it works but most of the time it does not. I guess I'm not doing the right think with the async/await. Can anyone give me a hand?

Thank you so much!

答:
Lots of discussion here React setState not Updating Immediately

But basically, setState is async/ a request to update state in the next render. Therefor, the updates to state are not immediately available/observable

Title: React SetState within a async function

Body:
I'm trying to learn React making a weather application and I have got stacked using the async/await function. Here is the trouble I'm facing..

I have a function which does a axios call to an api and then I'm trying to set some state variables. The think is that it seems the application is running the setState methods before the promise is resolved.

Here is the method that makes the axios call.

const fetchWeeklyWeather = async () => {

    try {
        let response = await axios.get(url);

        console.log('%cFetch Weekly Weather Response:', 'color: #bada55', response);

        setCurrentWeather(response.data.current);
        setWeeklyWeather(response.data.daily);
        setWeatherAlerts(response.data.alerts);
    } catch (err) {
        // Handle Error Here
        console.error(err);
    }
}

And I call that method on the componentDidMount like so:

useEffect(() => {
    fetchWeeklyWeather();

    console.log("Current Weather", currentWeather);
    console.log("Weekly Weather", weeklyWeather);
    console.log("Weather alerts", weatherAlerts);

    formatData(weeklyWeather);
}, []);

It is weird because sometimes it works but most of the time it does not. I guess I'm not doing the right think with the async/await. Can anyone give me a hand?

Thank you so much!


问:
dealing with missing values with the R filter() function
I'd like to handle missing values using the filter() function in R.

In fact, I wish to compute X_t = 1/(2*T+1) * sum(X_i, i = (t-T)...(t+T)) where (X_t) is a classical time series containing missing values. filter() computes sums over the time intervals [(t-T);(t+T)] but it does not give the mean of the values excluding the NAs.

Does anyone have any idea how about dealing with that?

答:
If you want a simple moving average over 2k+1 points, you can do this:

```<code>x <- c(rep(1,5), NA, rep(1,5))
k <- 1  ## Moving average over three points.
smooth <- sapply(1:length(x), mean(x[(i-k):(i+k)], na.rm=TRUE))
</code>```

which results in a vector of all ones in this case.

Body:
If you want a simple moving average over 2k+1 points, you can do this:

x <- c(rep(1,5), NA, rep(1,5))
k <- 1  ## Moving average over three points.
smooth <- sapply(1:length(x), mean(x[(i-k):(i+k)], na.rm=TRUE))

which results in a vector of all ones in this case.


问:
How set up multiple servers on the same node.js program that communicate with socket.io?
I'm trying to simulate on one machine multiple servers that communicate with socket.io in a node.js program. There is going to be one coordinator server, and many client servers. I'm doing this with the future goal of having a "web service program" for which I increase it's processing capability by adding more servers.

here is a simplification of the coordinator server part of the code;

```<code>const httpM= require('http');
const socketIo = require('socket.io');
const express = require('express');
const app = express();

var http = httpM.Server(app);
 io = socketIo(http);
 io.on('connection', function(socket) {
             console.log("successful connection");
             socket.on("test",function(msg){
                 console.log(msg);
             })
        });
const PORT = process.env.PORT || (5000);
http.listen(PORT, () => console.log(`coordinator server: started on ${PORT}`));
</code>```

here is the client server part.

```<code>const clientIo = require("socket.io/client-dist/socket.io");
var interServerSocket;
setInterval(function() {
      if(interServerSocket==null||interServerSocket==undefined)
      {
        interServerSocket= clientIo.connect("http://localhost:5000");
        console.log("-should have connected the interserver socket");
      }
      interServerSocket.emit("test","hello coordinator here to serve");
      console.log("-should have emit");
    },5000);

</code>```

But my code doesn't work. I never get "successful connection" logged in the console nor any of the messages I emit logged. Nothing is logged from the coordinator server part.
I don't see what I could be doing wrong. I was thinking it could be something to do with the fact that the code is all in the same node program in the same machine. Maybe I'm writing the url wrong. I appreciate all help.

I found this question that helped me:
Is it possible to set up a socket.io client running (server-side) on a node.js server?
I think it's outdated though, require("socket.io-client"); needs to be changed with require("socket.io/client-dist/socket.io");. In any case for my case for some reason it's not working.

答:
answer in short download socket.io-client with the command npm i socket.io-client
then use require("socket.io-client"); intead of require("socket.io/client-dist/socket.io");

The answer was in this thread after all:
Is it possible to set up a socket.io client running (server-side) on a node.js server?
I was wrong socket.io-client is actually another npm module that one can download separate from socket.io: https://www.npmjs.com/package/socket.io-client
using: require("socket.io/client-dist/socket.io"); unexpectedly gave me no compilation errors but it seems it wasn't the right way to do this the socket.io/client-dist/socket.io module is maybe only for the browser or something.

Body:
I'm trying to simulate on one machine multiple servers that communicate with socket.io in a node.js program. There is going to be one coordinator server, and many client servers. I'm doing this with the future goal of having a "web service program" for which I increase it's processing capability by adding more servers.

here is a simplification of the coordinator server part of the code;

const httpM= require('http');
const socketIo = require('socket.io');
const express = require('express');
const app = express();

var http = httpM.Server(app);
 io = socketIo(http);
 io.on('connection', function(socket) {
             console.log("successful connection");
             socket.on("test",function(msg){
                 console.log(msg);
             })
        });
const PORT = process.env.PORT || (5000);
http.listen(PORT, () => console.log(`coordinator server: started on ${PORT}`));

here is the client server part.

const clientIo = require("socket.io/client-dist/socket.io");
var interServerSocket;
setInterval(function() {
      if(interServerSocket==null||interServerSocket==undefined)
      {
        interServerSocket= clientIo.connect("http://localhost:5000");
        console.log("-should have connected the interserver socket");
      }
      interServerSocket.emit("test","hello coordinator here to serve");
      console.log("-should have emit");
    },5000);

But my code doesn't work. I never get "successful connection" logged in the console nor any of the messages I emit logged. Nothing is logged from the coordinator server part.
I don't see what I could be doing wrong. I was thinking it could be something to do with the fact that the code is all in the same node program in the same machine. Maybe I'm writing the url wrong. I appreciate all help.

I found this question that helped me:
Is it possible to set up a socket.io client running (server-side) on a node.js server?
I think it's outdated though, require("socket.io-client"); needs to be changed with require("socket.io/client-dist/socket.io");. In any case for my case for some reason it's not working.


问:
How do I deliver OpenAL32.dll with my application without requiring OpenAL installation on the client machine?
I have a 32-bit C++ Windows application using the OpenAL library. I am using the official OpenAL setup to install the required DLL file, but when I publish my application, I would like to find a way to deliver it without requiring the user to install OpenAL seperately like I did.

With other DLL files, I simply add them to my project, but with OpenAL I seemed to get issues. Is this possible? And if so, how?

答:
Apparently, I mixed up the System32 and SysWow64 folders in Windows.

It should be the other way around!

System32 on 64-bit Windows contains 64-bit .dll files

SysWow64 on 64-bit Windows contains 32-bit .dll files

For reference:
https://www.howtogeek.com/326509/whats-the-difference-between-the-system32-and-syswow64-folders-in-windows/

What I did:

So I installed OpenAL from the official installation source. This installer copies the OpenAL32.dll files into the System32 and SysWow64 folders.

As my application is 32-bit I needed to copy OpenAL32.dll from SysWow64 folder into my executable directory. Once I uninstalled OpenAL (which removed these .dll files from my Windows System32 and SysWow64 folders, it worked with the .dll file accompanied with my executable file.


问:
Create a column in power Bi Based upon selection
Recently I came up with this problem:
I have a table with two different codes: COD1 and COD2. I want to create in power bi bar charts and tables with this information but I want to be able to change whether if I want to see them with COD1 or COD2. I have a slicer that gives you the option of which code you want the info be displayed. I've done this before with numeric data types because you can do this with a measure, however I don't know how to make it work with non-numeric columns.

COD1
COD2
Sales

AA
A10
5

AB
B45
10

CD
D44
20

答:
I'm not exactly sure what you're trying to achieve but if I understand you correctly, you can change columns on a bar chart by making two bar charts. One will have COD1 as an axis with Sales, and the other will have COD2 as an axis with the same sales metric.

You could then use buttons and the bookmark functionality of Power BI to seamlessly "switch" the axis. See an example below:


问:
How would I add URL subsections/subpages?
How would I add things like this:

/page/sub-section

ex: https://url.com/account/notifications

答:
In terms of a static site, each slash represents a single directory on your web server.

```<code>/page/sub-section
</code>```

Would mean you have the

/ the root directory

/page a folder called page

/sub-section another folder called sub-section

In the last folder, you would then have your index file, which will be loaded once visiting the URL. For example index.html.

In terms of web development this is named routing and all the big web frameworks come with own modules for routing. Here you don't have to create directories as described above, instead these frameworks will handle the request and route it internally to find the right content and display it for that route.

Body:
In terms of a static site, each slash represents a single directory on your web server.

/page/sub-section

Would mean you have the

/ the root directory

/page a folder called page

/sub-section another folder called sub-section

In the last folder, you would then have your index file, which will be loaded once visiting the URL. For example index.html.

In terms of web development this is named routing and all the big web frameworks come with own modules for routing. Here you don't have to create directories as described above, instead these frameworks will handle the request and route it internally to find the right content and display it for that route.


问:
How to add european countries borders to a Raster in R?
I have this raster file:

fdiff_north:

```<code>class      : RasterLayer
dimensions : 5500, 12000, 6.6e+07  (nrow, ncol, ncell)
resolution : 100, 100  (x, y)
extent     : 4e+06, 5200000, 2250000, 2800000  (xmin, xmax, ymin, ymax)
crs        : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs
source     : memory
names      : layer
values     : -1, 1  (min, max)
</code>```

to get a plot:

```<code>cl <- colorRampPalette(c("red","white","blue"))(100)
plot(fdiff_north, col=cl)
</code>```

I need boundaries to make the plot more usable.

I also tried to change the crs of my raster:

rfdiff_north:

```<code>class      : RasterLayer
dimensions : 12571, 6151, 77324221  (nrow, ncol, ncell)
resolution : 9e-04, 0.00128  (x, y)
extent     : 42.7836, 48.3195, 5.672145, 21.76303  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs
source     : r_tmp_2022-02-07_151752_9872_54603.grd
names      : layer
values     : -1.466443, 1.366832  (min, max)
</code>```

I want to add european countries boundaries to my raster, but I can't get it. I've tried with many different functions but I achieved no results. Can you help me to do that ?

答:
The boundaries of European countries you can get from spMaps or any other source (OpenStreetMap data for example)

# devtools::install_github("rte-antares-rpackage/spMaps", ref = "master")
library(spMaps)
eu <- getEuropeCountries(mergeCountry = FALSE)
```
<p>Trying to create similar (in size and CRS) raster:</p>
<pre class="lang-r prettyprint-override"><code>library(terra)
#> terra 1.5.17
x <- rast(nrows=5500, ncols = 12000, nlyrs = 1,
     xmin = 4e+06, xmax = 5200000, ymin = 2250000, ymax = 2800000,
     crs = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
     resolution = 100)
x <- setValues(x,runif(ncell(x)))
x
#> class       : SpatRaster
#> dimensions  : 5500, 12000, 1  (nrow, ncol, nlyr)
#> resolution  : 100, 100  (x, y)
#> extent      : 4e+06, 5200000, 2250000, 2800000  (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs
#> source      : memory
#> name        :        lyr.1
#> min value   : 4.889444e-09
#> max value   :            1
</code>```

Now it's time to convert SpatialPolygons to SimpleFeature and transform the coordinates to yours CRS:

library(sf)
eu <- st_as_sf(eu)

plot(x)
plot(st_transform(eu$geometry,
    crs = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs"),
    add = TRUE)
```

Created on 2022-02-09 by the reprex package (v2.0.1)

You can crop boundaries to your raster bbox with st_crop()

Regards,
Grzegorz

Body:
I have this raster file:

fdiff_north:

class      : RasterLayer
dimensions : 5500, 12000, 6.6e+07  (nrow, ncol, ncell)
resolution : 100, 100  (x, y)
extent     : 4e+06, 5200000, 2250000, 2800000  (xmin, xmax, ymin, ymax)
crs        : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs
source     : memory
names      : layer
values     : -1, 1  (min, max)

to get a plot:

cl <- colorRampPalette(c("red","white","blue"))(100)
plot(fdiff_north, col=cl)

I need boundaries to make the plot more usable.

I also tried to change the crs of my raster:

rfdiff_north:

class      : RasterLayer
dimensions : 12571, 6151, 77324221  (nrow, ncol, ncell)
resolution : 9e-04, 0.00128  (x, y)
extent     : 42.7836, 48.3195, 5.672145, 21.76303  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +no_defs
source     : r_tmp_2022-02-07_151752_9872_54603.grd
names      : layer
values     : -1.466443, 1.366832  (min, max)

I want to add european countries boundaries to my raster, but I can't get it. I've tried with many different functions but I achieved no results. Can you help me to do that ?

Body:
The boundaries of European countries you can get from spMaps or any other source (OpenStreetMap data for example)

# devtools::install_github("rte-antares-rpackage/spMaps", ref = "master")
library(spMaps)
eu <- getEuropeCountries(mergeCountry = FALSE)

Trying to create similar (in size and CRS) raster:

library(terra)
#> terra 1.5.17
x <- rast(nrows=5500, ncols = 12000, nlyrs = 1,
     xmin = 4e+06, xmax = 5200000, ymin = 2250000, ymax = 2800000,
     crs = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
     resolution = 100)
x <- setValues(x,runif(ncell(x)))
x
#> class       : SpatRaster
#> dimensions  : 5500, 12000, 1  (nrow, ncol, nlyr)
#> resolution  : 100, 100  (x, y)
#> extent      : 4e+06, 5200000, 2250000, 2800000  (xmin, xmax, ymin, ymax)
#> coord. ref. : +proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs
#> source      : memory
#> name        :        lyr.1
#> min value   : 4.889444e-09
#> max value   :            1

Now it's time to convert SpatialPolygons to SimpleFeature and transform the coordinates to yours CRS:

library(sf)
eu <- st_as_sf(eu)

plot(x)
plot(st_transform(eu$geometry,
    crs = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs"),
    add = TRUE)

Created on 2022-02-09 by the reprex package (v2.0.1)

You can crop boundaries to your raster bbox with st_crop()

Regards,
Grzegorz


问:
postgres select non existing field as empty string
This might be a stupid question. Imaging following table in Postgres:

```<code>create table scientist (id integer, firstname varchar(100), lastname varchar(100));
insert into scientist (id, firstname, lastname) values (1, 'albert', 'einstein');
</code>```

A simple select of all fields:

```<code>select  id, firstname, lastname   scientist;
</code>```

results in:

is
firstname
lastname

1
albert
einstein

Is there some way to add a kind of non-existing empty virtual field f.e. age?
Pseudo Code:

```<code> select
    id,
    firstname,
    lastname,
    age as '' -- my non existing field that should show up in the results
    from
    scientist;
</code>```

that the result looks like?

is
firstname
lastname
age

1
albert
einstein

答:
It's the other way round: as defines a column alias, so

```<code>'' as age
</code>```

will work.

However, I'd be quite surprised about a column named age in a result that is a character value, not an integer. If you want a typed value, you can also use null::int as age

Body:
This might be a stupid question. Imaging following table in Postgres:

create table scientist (id integer, firstname varchar(100), lastname varchar(100));
insert into scientist (id, firstname, lastname) values (1, 'albert', 'einstein');

A simple select of all fields:

select  id, firstname, lastname   scientist;

results in:

is
firstname
lastname

1
albert
einstein

Is there some way to add a kind of non-existing empty virtual field f.e. age?
Pseudo Code:

 select
    id,
    firstname,
    lastname,
    age as '' -- my non existing field that should show up in the results
    from
    scientist;

that the result looks like?

is
firstname
lastname
age

1
albert
einstein

Body:
It's the other way round: as defines a column alias, so

'' as age

will work.

However, I'd be quite surprised about a column named age in a result that is a character value, not an integer. If you want a typed value, you can also use null::int as age


问:
Do ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION require a prominent disclosure message?
I see that the ACCESS_BACKGROUND_LOCATION permission (which according to Google needs to be requested individually) requires a prominent disclosure (which according to Google needs to be also shown individually).

I also see that ACCESS_BACKGROUND_LOCATION permission requires prior ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION permissions (which according to Google these need to be requested together).

My question is, would I also need to show a prominent disclosure message for these permissions?

Directions are a bit fuzzy.

答: Yes. Those are categorised as "dangerous permissions". You need to ask the user at runtime for those permissions with a system UI dialog.</p>


问:
Differences between Tab, TabContext, Tablist, TabPanel, in React material-ui
I'm having a hard time deciding when to use TabPanel, Tabs, TabList, and TabContext when working with material-ui.

Is there a high-level overview of when to use each? It looks like all can... well make tabs.

答:
I haven't found much documentation, it seems that you can either use

```<code><TabContext>
    <TabList>
        <Tab> </Tab>
        <Tab> </Tab>
        <Tab> </Tab>
    </TabList>
</TabContext>
</code>```

OR

```<code><Tabs>
    <Tab> </Tab>
    <Tab> </Tab>
    <Tab> </Tab>
</Tabs>
</code>```

The former seems more customizable and perhaps less standard because it's in the @mui/lab library. The latter automatically wraps your Tabs in a TabList container, but you lose access to this container in-code, including the ability to add custom styles to it.

By the way @Patrick, I remember you from a Chainlink Hackathon a few years ago!

Body:
I haven't found much documentation, it seems that you can either use

<TabContext>
    <TabList>
        <Tab> </Tab>
        <Tab> </Tab>
        <Tab> </Tab>
    </TabList>
</TabContext>

OR

<Tabs>
    <Tab> </Tab>
    <Tab> </Tab>
    <Tab> </Tab>
</Tabs>

The former seems more customizable and perhaps less standard because it's in the @mui/lab library. The latter automatically wraps your Tabs in a TabList container, but you lose access to this container in-code, including the ability to add custom styles to it.

By the way @Patrick, I remember you from a Chainlink Hackathon a few years ago!


问:
AttributeError: 'str' object has no attribute 'isascii'
My code:

```<code>def check_string(text):

    valid = bool(text and (not text.isascii() or any(t.isalnum() for t in text)))

    return text if valid else ""
</code>```

While I process some text, I got the following error:

```<code>File "/data/text_normalizer.py", line 176, in check_string
    valid = bool(text and (not text.isascii() or any(t.isalnum() for t in text)))
AttributeError: 'str' object has no attribute 'isascii'
</code>```

isascii() is indeed a function of a str object, so why does it report this error?

答: isascii requires Python 3.7 or later.

Body:
My code:

def check_string(text):

    valid = bool(text and (not text.isascii() or any(t.isalnum() for t in text)))

    return text if valid else ""

While I process some text, I got the following error:

File "/data/text_normalizer.py", line 176, in check_string
    valid = bool(text and (not text.isascii() or any(t.isalnum() for t in text)))
AttributeError: 'str' object has no attribute 'isascii'

isascii() is indeed a function of a str object, so why does it report this error?

Body: isascii requires Python 3.7 or later.


问:
Finding Minimum For every group in ArrayList in Java
I have a class as below.

```<code>public class Employee{
int EmployeeDepartmentId;
int EmplyoyeeId;
int Salary;
}
</code>```

I an creating an ArrayList as Below.

```<code>ArrayList<Employee> arrEmployee = new ArrayList<Employee>;
</code>```

Now, I want to find out List of employees from every department with minimum salary.

How can this be achieved. I tried using Collections.Min(), but that will give me the minimum salary from whole list. I want it to be grouped by department.

Any suggestions?

答:
every logic is in Comparator they will be grouped by department and sorted by salary:    </p>

```<code>public class Employee {
Integer EmployeeDepartmentId;
Integer EmplyoyeeId;
Integer Salary;

public Employee(Integer employeeDepartmentId, Integer emplyoyeeId, Integer salary)  {
    EmployeeDepartmentId = employeeDepartmentId;
    EmplyoyeeId = emplyoyeeId;
    Salary = salary;
}

public Integer getEmployeeDepartmentId() {
    return EmployeeDepartmentId;
}

public void setEmployeeDepartmentId(Integer employeeDepartmentId) {
    EmployeeDepartmentId = employeeDepartmentId;
}

public Integer getEmplyoyeeId() {
    return EmplyoyeeId;
}

public void setEmplyoyeeId(Integer emplyoyeeId) {
    EmplyoyeeId = emplyoyeeId;
}

public Integer getSalary() {
    return Salary;
}

public void setSalary(Integer salary) {
    Salary = salary;
}

public static void main(String[] args) {
    List<Employee> employees=new ArrayList<Employee>();
    employees.add(new Employee(3, 3, 50));
    employees.add(new Employee(2, 4, 2500));
    employees.add(new Employee(1, 1, 100));
    employees.add(new Employee(2, 5, 1100));
    employees.add(new Employee(1, 2, 20));
    for(Employee e:employees)
        System.out.println(e.getEmployeeDepartmentId()+" "+e.getEmplyoyeeId()+" "+e.getSalary());
    Collections.sort(employees,new Comparator<Employee>() {
        @Override
        public int compare(Employee e, Employee e1) {
            if(e.getEmployeeDepartmentId()==e1.getEmployeeDepartmentId()){
                return e.getSalary().compareTo(e1.getSalary());
            }else
                return e.getEmployeeDepartmentId().compareTo(e1.getEmployeeDepartmentId());
        }
    });
    for(Employee e:employees)
        System.out.println(e.getEmployeeDepartmentId()+" "+e.getEmplyoyeeId()+" "+e.getSalary());
}
</code>```

<p>}</p>

Body:
I have a class as below.

public class Employee{
int EmployeeDepartmentId;
int EmplyoyeeId;
int Salary;
}

I an creating an ArrayList as Below.

ArrayList<Employee> arrEmployee = new ArrayList<Employee>;

Now, I want to find out List of employees from every department with minimum salary.

How can this be achieved. I tried using Collections.Min(), but that will give me the minimum salary from whole list. I want it to be grouped by department.

Any suggestions?

Body:
every logic is in Comparator they will be grouped by department and sorted by salary:

public class Employee {
Integer EmployeeDepartmentId;
Integer EmplyoyeeId;
Integer Salary;

public Employee(Integer employeeDepartmentId, Integer emplyoyeeId, Integer salary)  {
    EmployeeDepartmentId = employeeDepartmentId;
    EmplyoyeeId = emplyoyeeId;
    Salary = salary;
}

public Integer getEmployeeDepartmentId() {
    return EmployeeDepartmentId;
}

public void setEmployeeDepartmentId(Integer employeeDepartmentId) {
    EmployeeDepartmentId = employeeDepartmentId;
}

public Integer getEmplyoyeeId() {
    return EmplyoyeeId;
}

public void setEmplyoyeeId(Integer emplyoyeeId) {
    EmplyoyeeId = emplyoyeeId;
}

public Integer getSalary() {
    return Salary;
}

public void setSalary(Integer salary) {
    Salary = salary;
}

public static void main(String[] args) {
    List<Employee> employees=new ArrayList<Employee>();
    employees.add(new Employee(3, 3, 50));
    employees.add(new Employee(2, 4, 2500));
    employees.add(new Employee(1, 1, 100));
    employees.add(new Employee(2, 5, 1100));
    employees.add(new Employee(1, 2, 20));
    for(Employee e:employees)
        System.out.println(e.getEmployeeDepartmentId()+" "+e.getEmplyoyeeId()+" "+e.getSalary());
    Collections.sort(employees,new Comparator<Employee>() {
        @Override
        public int compare(Employee e, Employee e1) {
            if(e.getEmployeeDepartmentId()==e1.getEmployeeDepartmentId()){
                return e.getSalary().compareTo(e1.getSalary());
            }else
                return e.getEmployeeDepartmentId().compareTo(e1.getEmployeeDepartmentId());
        }
    });
    for(Employee e:employees)
        System.out.println(e.getEmployeeDepartmentId()+" "+e.getEmplyoyeeId()+" "+e.getSalary());
}

}


问:
How does SSR go with PWA
How can one do SSR (Server side rendering) with PWA (Progressive web app)?

From what I understand,

SSR

The SSR runtime will load the page and run the necessary scripts to load the data on to the page. Then returns the rendered html. This is important for web crawlers which will not run javascript and browsers with no-script. At least the first impression will be usable.

PWA

Among others, PWA requires having a shell, which will be cached and the data will come after it. This means, even if the user is offline, the shell will be loaded.

?

So, if we're pre rendering the data, how can one cache the shell separate from the data?

答:
You should use workbox library by google - look at these docs on how to cache routes by using the workbox-routing module.

Here are also some common recipes or approaches to handle caching in any type of a web app.

Title: How does SSR go with PWA


问:
Google Sheets, Web scrape Best Buy Price
im trying to figure out how to web scrape the price of a product into google sheets.
Before i would use =importrange(A1,B1)

And have A1 = https://www.bestbuy.com/site/asus-17-3-chromebook-intel-celeron-n4500-4gb-memory-32gb-emmc-transparent-silver/6471189.p?skuId=6471189

And have B1 = /html/body/div[3]/main/div[2]/div/div[1]/div[3]/div[2]/div/div[1]/div[1]/div/div/div/div/div/div[2]/div[1]/div[1]/div/span[1]

This was done by coping the full Xpath.
So far this has been working but unfortunately it seems like that is no longer a way to do it.

Im trying to do this for both Best Buy and Walmart

if i could have an example for these two links that would be awesome! Thank you in advanced!

Link 1: https://www.bestbuy.com/site/asus-17-3-chromebook-intel-celeron-n4500-4gb-memory-32gb-emmc-transparent-silver/6471189.p?skuId=6471189

Link 2:https://www.walmart.com/ip/Samsung-Chromebook-4-11-6-Intel-Celeron-N4020-4GB-RAM-32GB-SSD-Chrome-OS-Platinum-Titan-XE310XBA/153097702?athbdg=L1300

答:
Functions in Google Sheets like IMPORTHTML, IMPORTXML, IMPORTDATA and IMPORTFEED may not retrieve data from a website if the content is added dynamically(using JavaScript). I will reference this answer:

If the content is added dynamically (by using Javascript), it can't be imported by using Google Sheets built-in functions. Also if the website webmaster have taken certain measures, this functions will not able to import the data.


问:
ITMS-90338: Non-public API usage - The app references non-public selectors in [App]
I am building a Xamarin.Forms app that is building properly and deploying to the Apple App Store but keeps getting rejected for the following reasons:

ITMS-90338: Non-public API usage - The app references non-public
selectors in [App].Mobile.iOS: accessibilityBrailleMapRenderRegion,
accessibilityBrailleMapRenderer, accessibilityColumnRange,
accessibilityRowRange, activePlayer, beginAuthorizationWithRequest:,
cancelAuthorizationWithRequest:, errorForCHIPErrorCode:,
errorToCHIPErrorCode:, playerId, serviceExtensionWillTerminate,
session:didReceiveData:fromPlayer:,
session:didReceiveMessage:withData:fromPlayer:,
session:player:didChangeConnectionState:, session:player:didSaveData:,
setAccessibilityBrailleMapRenderRegion:,
setAccessibilityBrailleMapRenderer:. If method names in your source
code match the private Apple APIs listed above, altering your method
names will help prevent this app from being flagged in future
submissions. In addition, note that one or more of the above APIs may
be located in a static library that was included with your app.

I coded the app on a PC in Visual Studio Community 2019 v16.9.1. And built and deployed the app via Appcenter.ms.

Packages that I am using are:

Microsoft.AppCenter.Analytics v4.5.0

Microsoft.AppCenter.Crashes v4.5.0

Xamarin.Essentials v1.7.1

Xamarin.Forms v5.0.0.2337

Target Framework: .NET Standard 2.0

Information that I have confirmed from other sources:

Build Configuration: Release

Linker Behavior: Link Framework SDKs Only

Additional mtouch arguments: --linkskip=[selectors]

Additional mtouch arguments: --linkplatform

I have found all of the non-public selectors in xamarin/xamarin-macios and xamarin/apple-api-docs but I have not been able to find out how to fix the errors.

Thanks

Edit: I was not able to fix the issue. Instead, I got a Mac VM and was able to publish the code that way.

答: i had the same problem and i fix it by selecting (release | iphone) in the build options before archiving for publishing</p>


问:
Need help changing jquery to javascript for an on change function
I am trying to change some jQuery code to plain JS for an on call function. I keep getting the following error - Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object'.

Old

```<code>$(document).on('change', '.js-variant-radio', onVariantRadioChange);

</code>```

New

```<code>document.querySelector('.js-variant-radio').addEventListener("change", onVariantRadioChange);
</code>```

Complete code block here

```<code>(function(){
  //START QUANTITY INPUT VALIDATION FUNCTION
  let
    onVariantRadioChange = function(event) {
      let
        $radio = document.querySelector(this),
        $form = $radio.closest('form'),
        max = $radio.attr('data-inventory-quantity'),
        $quantity = $form.querySelector('.js-quantity-field'),
        $addToCartButton = $form.querySelector('.add-to-cart-button');

      if($addToCartButton.prop('disabled') === true) {
        $addToCartButton.prop('disabled', false);
      }

      $quantity.attr('max', max);

      if (parseInt($quantity.value) > max) {
        $quantity.val(max).change();
      }
    };

    //END QUANTITY INPUT VALIDATION FUNCTION
})();
</code>```

答:
You're still adding the event listener with jQuery. Try changing it to:

const jsVariantRadio = document.getElementsByClassName('.js-variant-radio')[0];

jsVariantRadio.addEventListener('change', onVariantRadioChange);
```

Body:
I am trying to change some jQuery code to plain JS for an on call function. I keep getting the following error - Failed to execute 'addEventListener' on 'EventTarget': parameter 2 is not of type 'Object'.

Old

$(document).on('change', '.js-variant-radio', onVariantRadioChange);

New

document.querySelector('.js-variant-radio').addEventListener("change", onVariantRadioChange);

Complete code block here

(function(){
  //START QUANTITY INPUT VALIDATION FUNCTION
  let
    onVariantRadioChange = function(event) {
      let
        $radio = document.querySelector(this),
        $form = $radio.closest('form'),
        max = $radio.attr('data-inventory-quantity'),
        $quantity = $form.querySelector('.js-quantity-field'),
        $addToCartButton = $form.querySelector('.add-to-cart-button');

      if($addToCartButton.prop('disabled') === true) {
        $addToCartButton.prop('disabled', false);
      }

      $quantity.attr('max', max);

      if (parseInt($quantity.value) > max) {
        $quantity.val(max).change();
      }
    };

    //END QUANTITY INPUT VALIDATION FUNCTION
})();


问:
Example keycloak spring-boot app fails to find bean KeycloakSpringBootConfigResolver
I'm trying to run example app from:

https://github.com/keycloak/keycloak-quickstarts/tree/latest/app-springboot

I'm getting error:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of method setKeycloakSpringBootProperties in org.keycloak.adapters.springboot.KeycloakBaseSpringBootConfiguration required a bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' that could not be found.

Action:

Consider defining a bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' in your configuration.

Process finished with exit code 1
</code>```

答:
I could solve this problem by adding some annotations in the KeycloakConfig class declaration:</p>
```<code>@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class,
               excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX,
               pattern = "org.keycloak.adapters.springsecurity.management.HttpSessionManager"))
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter
{
}
</code>```

Body:
I'm trying to run example app from:

https://github.com/keycloak/keycloak-quickstarts/tree/latest/app-springboot

I'm getting error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 1 of method setKeycloakSpringBootProperties in org.keycloak.adapters.springboot.KeycloakBaseSpringBootConfiguration required a bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' that could not be found.

Action:

Consider defining a bean of type 'org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver' in your configuration.

Process finished with exit code 1

Body:
I could solve this problem by adding some annotations in the KeycloakConfig class declaration:

@EnableWebSecurity
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class,
               excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX,
               pattern = "org.keycloak.adapters.springsecurity.management.HttpSessionManager"))
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter
{
}


问:
Invalid Hook Call error when running Next app from PM2
We have an install of Node.js running on a Windows Server 2012R2 web server.  A developer created an application for us using Next/React/Node (I'm not a web developer so I'm unsure of the specifics of the various development tools used).  This app works fine when manually started on the command line like this:

C:\NodeApps\pacifield>"C:\PROGRAM FILES\NODEJS\NODE.EXE" C:\NodeApps\pacifield\node_modules\next\dist\bin\next start

However this requires someone to manually login and restart the app whenever the server is rebooted or the app stops for whatever reason.  I am trying to setup PM2 to run the app.  I have it up and running fine until you browse to the app - at which point you get the following error:

```<code>next-server.ts:306 Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (c:\NodeApps\pacifield\node_modules\react\cjs\react.development.js:1476:13)
    at useContext (c:\NodeApps\pacifield\node_modules\react\cjs\react.development.js:1484:20)
    at useSession (c:\NodeApps\pacifield\node_modules\next-auth\dist\client\index.js:75:39)
    at Provider (c:\NodeApps\pacifield\node_modules\next-auth\dist\client\index.js:588:12)
    at processChild (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:3353:14)
    at resolve (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:3270:5)
    at ReactDOMServerRenderer.render (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:3753:22)
    at ReactDOMServerRenderer.read (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:3690:29)
    at Object.renderToString (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:4298:27)
    at Object.renderPage (C:\NodeApps\pacifield\node_modules\next\dist\server\render.js:596:45)
</code>```

I have checked and there is only the one installation of React in C:\NodeApps\pacifield\node_modules\react and the other suggestions don't seem to make sense when it runs fine outside of PM2.  I have checked with ProcessExplorer that all the environment variables are the same (except for the additional ones PM2 adds) when the app is run from the command line vs. PM2.

Anyone have any suggestions?

答:
Hooks can only be call inside of functional component or inside another hook.

take note: Invalid Hook Call Warning

Notify your frontend developer it.

Body:
We have an install of Node.js running on a Windows Server 2012R2 web server.  A developer created an application for us using Next/React/Node (I'm not a web developer so I'm unsure of the specifics of the various development tools used).  This app works fine when manually started on the command line like this:

C:\NodeApps\pacifield>"C:\PROGRAM FILES\NODEJS\NODE.EXE" C:\NodeApps\pacifield\node_modules\next\dist\bin\next start

However this requires someone to manually login and restart the app whenever the server is rebooted or the app stops for whatever reason.  I am trying to setup PM2 to run the app.  I have it up and running fine until you browse to the app - at which point you get the following error:

next-server.ts:306 Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
    at resolveDispatcher (c:\NodeApps\pacifield\node_modules\react\cjs\react.development.js:1476:13)
    at useContext (c:\NodeApps\pacifield\node_modules\react\cjs\react.development.js:1484:20)
    at useSession (c:\NodeApps\pacifield\node_modules\next-auth\dist\client\index.js:75:39)
    at Provider (c:\NodeApps\pacifield\node_modules\next-auth\dist\client\index.js:588:12)
    at processChild (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:3353:14)
    at resolve (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:3270:5)
    at ReactDOMServerRenderer.render (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:3753:22)
    at ReactDOMServerRenderer.read (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:3690:29)
    at Object.renderToString (C:\NodeApps\pacifield\node_modules\react-dom\cjs\react-dom-server.node.development.js:4298:27)
    at Object.renderPage (C:\NodeApps\pacifield\node_modules\next\dist\server\render.js:596:45)

I have checked and there is only the one installation of React in C:\NodeApps\pacifield\node_modules\react and the other suggestions don't seem to make sense when it runs fine outside of PM2.  I have checked with ProcessExplorer that all the environment variables are the same (except for the additional ones PM2 adds) when the app is run from the command line vs. PM2.

Anyone have any suggestions?