问:
How to start WebRTC call with AWS Kinesis as Master
I'm trying to start a WebRTC call with AWS Kinesis, but the demo on The AWS Kinesis Javascript docs only shows how to join the call as a VIEWER not the MASTER.

I can't find a clear example anywhere online, and I've spent hours on it with my teammate.

I can see and hear myself, so I know I'm getting the hardware working correctly, but we can't see or hear each other. I know it's going to be something simple, but I just can't figure out where I'm going wrong with the connection.

```<code>const startKinesisCall = async () => {
     const coachingSession = new AWS.KinesisVideo({
          region,
          accessKeyId,
          secretAccessKey,
          correctClockSkew: true
        });

    // Get Signaling Channel Endpoints
    // Each signaling channel is assigned an HTTPS and WSS endpoint to connect to for
    // data-plane operations. These can be discovered using the GetSignalingChannelEndpoint API.
    const getSignalingChannelEndpointResponse = await coachingSession.getSignalingChannelEndpoint({
      ChannelARN: channelARN,
      SingleMasterChannelEndpointConfiguration: {
        Protocols: ['WSS', 'HTTPS'],
        Role: Role.VIEWER
      }
    }).promise();

    const endpointsByProtocol = getSignalingChannelEndpointResponse?.ResourceEndpointList?.reduce((endpoints, endpoint) => {
      endpoints[endpoint.Protocol] = endpoint?.ResourceEndpoint;
      return endpoints;
    }, {});

    // Create KVS Signaling Client
    // The HTTPS endpoint from the GetSignalingChannelEndpoint response is used with this client.
    // This client is just used for getting ICE servers, not for actual signaling.
    const kinesisVideoSignalingChannelsClient = new AWS.KinesisVideoSignalingChannels({
      region,
      accessKeyId,
      secretAccessKey,
      endpoint: endpointsByProtocol.HTTPS,
      correctClockSkew: true,
    });

    // Get ICE server configuration
    // For best performance, we collect STUN and TURN ICE server configurations.
    // The KVS STUN endpoint is always stun:stun.kinesisvideo.${region}.amazonaws.com:443.
    // To get TURN servers, the GetIceServerConfig API is used.
    const getIceServerConfigResponse = await kinesisVideoSignalingChannelsClient
      .getIceServerConfig({
        ChannelARN: channelARN,
      }).promise();
    const iceServers = [{ urls: `stun:stun.kinesisvideo.${region}.amazonaws.com:443` }];
    getIceServerConfigResponse.IceServerList.forEach(iceServer =>
      iceServers.push({
        urls: iceServer.Uris,
        username: iceServer.Username,
        credential: iceServer.Password,
      }),
    );

    console.log('ICE SERVERS: ', iceServers);

    // Create RTCPeerConnection
    // The RTCPeerConnection is the primary interface for WebRTC communications in the Web.
    const peerConnection = new RTCPeerConnection({ iceServers });

    // Create WebRTC Signaling Client
    // This is the actual client that is used to send messages over the signaling channel.
    const signalingClient = new SignalingClient({
      channelARN,
      channelEndpoint: endpointsByProtocol.WSS,
      role: Role.MASTER,
      region,
      clientId,
      credentials: {
        accessKeyId,
        secretAccessKey,
      },
      systemClockOffset: coachingSession.config.systemClockOffset
    });

    // GET THE USER MEDIA DEVICES
    const localStream = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    }).catch(e => {
      console.log("COULD NOT FIND WEBCAM");
      setShowErrorStartingVideoModal(true);
    });

    // *** AUDIO & VIDEO DEVICE COLLECTION ***
    let audioInputDevices: MediaDeviceInfo[];
    let audioOutputDevices: MediaDeviceInfo[];
    let videoInputDevices: MediaDeviceInfo[];
    try {
      const mediaDevices = await navigator.mediaDevices.enumerateDevices();
      audioInputDevices = mediaDevices.filter(device => device.kind === 'audioinput');
      audioOutputDevices = mediaDevices.filter(device => device.kind === 'audiooutput');
      videoInputDevices = mediaDevices.filter(device => device.kind === 'videoinput');
      setMicrophoneList(audioInputDevices);
      setSpeakerList(audioOutputDevices);
      setCameraList(videoInputDevices);
    } catch (e) {
      console.log(e);
      console.log("ERROR COLLECTING MEDIA DEVICE INFORMATION: MAKE SURE PERMISSIONS ARE ALLOWED AND TRY AGAIN");
    };

    // GRAB THE LOCAL PROVIDER AND PATIENT VIDEO TILES
    const providerVideoTile: HTMLVideoElement = document.getElementById('provider-video-element') as HTMLVideoElement;
    const patientVideoElement = document.getElementById('patient-video-element') as HTMLVideoElement;
    // let dataChannel: RTCDataChannel
    // Add Signaling Client Event Listeners
    signalingClient.on('open', async () => {
      if (!localStream || !peerConnection) return;

      // Get a stream from the webcam, add it to the peer connection, and display it in the local view
      try {
        localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));
        providerVideoTile.srcObject = localStream;
      } catch (e) {
        // Could not find webcam
        console.log(e);
        return;
      };

      // Create an SDP offer and send it to the master
      const offer = await peerConnection.createOffer({
        offerToReceiveAudio: true,
        offerToReceiveVideo: true
      });

      console.log('CREATED OFFER: ', offer);

      await peerConnection.setLocalDescription(offer);

      if (peerConnection.localDescription) signalingClient.sendSdpOffer(peerConnection.localDescription, patient.patientID);
    });

    // When the SDP answer is received back from the master, add it to the peer connection.
    signalingClient.on('sdpAnswer', async answer => {
      console.log('RECEIVED ANSWER: ', answer);
      if (!peerConnection) return;
      await peerConnection.setRemoteDescription(answer).catch(e => console.log(e));
    });

    signalingClient.on('sdpOffer', async (offer, senderClientID) => {
      console.log({ offer });
      if (!peerConnection) return;

      await peerConnection.setRemoteDescription(offer).catch(e => console.log(e));
      console.log('REMOTE DESCRIPTION SET: ', peerConnection);
      const answer = await peerConnection.createAnswer().catch(e => console.log(e));

      console.log({ answer });
      if (answer) signalingClient.sendSdpAnswer(answer, senderClientID);

      // dataChannel = peerConnection.createDataChannel(`data-channel-of-${senderClientID}`);
      // dataChannel.addEventListener("open", (event) => {
      //   console.log(event);
      //   dataChannel.send('******HI ALEC*******');
      // });
    });

    // When an ICE candidate is received from the master, add it to the peer connection.
    signalingClient.on('iceCandidate', async (candidate, senderClientID) => {
      if (!peerConnection) return;
      console.log('new iceCandidate received:', candidate);

      await peerConnection.addIceCandidate(candidate).catch(e => console.log(e));
      console.log("ICE CANDIDATE ADDED: ", candidate);
    });

    signalingClient.on('close', async () => {
      if (!localStream) return;
      // Handle client closures
      console.log("ENDING THE CALL");
      localStream.getTracks().forEach(track => track.stop());
      peerConnection.close();
      if ('srcObject' in providerVideoTile) providerVideoTile.srcObject = null;
    });

    signalingClient.on('error', error => {
      // Handle client errors
      console.log(error);
    });

    signalingClient.on('chat', (dataMessage: any) => {
      const decodedMessage = UTF8Decoder.decode(new Uint8Array(dataMessage.data));
      console.log("GOT TEST MESSAGE:", decodedMessage);
    });

    signalingClient.on('SeriesData', (dataMessage: any) => {
      const seriesFromMobile = JSON.parse(UTF8Decoder.decode(new Uint8Array(dataMessage.data)));
      console.log("SERIES FROM MOBILE:", seriesFromMobile);
      kickOffSeriesCreation(seriesFromMobile);
    });

    signalingClient.on('EffortMarker', (dataMessage: any) => {
      const effortMarker = UTF8Decoder.decode(new Uint8Array(dataMessage.data));
      console.log("EFFORT MARKER:", effortMarker);
      setEffortMarker(effortMarker);
    });

    signalingClient.on('CoachingMessage', async (dataMessage: any) => {
      const coachingMessage = UTF8Decoder.decode(new Uint8Array(dataMessage.data));
      console.log("COACHING MESSAGE FROM MOBILE:", coachingMessage);
      if (coachingMessage === 'EndSeries') {
        await handleForceEndEffort(signalingClient);
        await handleEndSeries(signalingClient);
      };
    });

    // Add Peer Connection Event Listeners
    // Send any ICE candidates generated by the peer connection to the other peer
    peerConnection.addEventListener('icecandidate', ({ candidate }) => {
      if (candidate) {
        console.log(candidate);
        signalingClient.sendIceCandidate(candidate, patient.patientID);
      } else {
        // No more ICE candidates will be generated
        console.log('NO MORE ICE CANDIDATES WILL BE GENERATED');
      }
    });

    // As remote tracks are received, add them to the remote view
    peerConnection.addEventListener('track', event => {
      // if (patientVideoElement.srcObject) return;
      setNoPatientConnected(false);
      console.log({ event });
      try {
        peerConnection.addTrack(event.track, event.streams[0]);
        if (event.track.kind === 'video') patientVideoElement.srcObject = event.streams[0];
      } catch (e) {
        console.log(e);
      }
    });

    // Open Signaling Connection
    signalingClient.open();
  };
</code>```

答: For anyone else with the same issue, I managed to find the master example on this github repo and was able to get it working</p>

Body:
I'm trying to start a WebRTC call with AWS Kinesis, but the demo on The AWS Kinesis Javascript docs only shows how to join the call as a VIEWER not the MASTER.

I can't find a clear example anywhere online, and I've spent hours on it with my teammate.

I can see and hear myself, so I know I'm getting the hardware working correctly, but we can't see or hear each other. I know it's going to be something simple, but I just can't figure out where I'm going wrong with the connection.

const startKinesisCall = async () => {
     const coachingSession = new AWS.KinesisVideo({
          region,
          accessKeyId,
          secretAccessKey,
          correctClockSkew: true
        });

    // Get Signaling Channel Endpoints
    // Each signaling channel is assigned an HTTPS and WSS endpoint to connect to for
    // data-plane operations. These can be discovered using the GetSignalingChannelEndpoint API.
    const getSignalingChannelEndpointResponse = await coachingSession.getSignalingChannelEndpoint({
      ChannelARN: channelARN,
      SingleMasterChannelEndpointConfiguration: {
        Protocols: ['WSS', 'HTTPS'],
        Role: Role.VIEWER
      }
    }).promise();

    const endpointsByProtocol = getSignalingChannelEndpointResponse?.ResourceEndpointList?.reduce((endpoints, endpoint) => {
      endpoints[endpoint.Protocol] = endpoint?.ResourceEndpoint;
      return endpoints;
    }, {});

    // Create KVS Signaling Client
    // The HTTPS endpoint from the GetSignalingChannelEndpoint response is used with this client.
    // This client is just used for getting ICE servers, not for actual signaling.
    const kinesisVideoSignalingChannelsClient = new AWS.KinesisVideoSignalingChannels({
      region,
      accessKeyId,
      secretAccessKey,
      endpoint: endpointsByProtocol.HTTPS,
      correctClockSkew: true,
    });

    // Get ICE server configuration
    // For best performance, we collect STUN and TURN ICE server configurations.
    // The KVS STUN endpoint is always stun:stun.kinesisvideo.${region}.amazonaws.com:443.
    // To get TURN servers, the GetIceServerConfig API is used.
    const getIceServerConfigResponse = await kinesisVideoSignalingChannelsClient
      .getIceServerConfig({
        ChannelARN: channelARN,
      }).promise();
    const iceServers = [{ urls: `stun:stun.kinesisvideo.${region}.amazonaws.com:443` }];
    getIceServerConfigResponse.IceServerList.forEach(iceServer =>
      iceServers.push({
        urls: iceServer.Uris,
        username: iceServer.Username,
        credential: iceServer.Password,
      }),
    );

    console.log('ICE SERVERS: ', iceServers);

    // Create RTCPeerConnection
    // The RTCPeerConnection is the primary interface for WebRTC communications in the Web.
    const peerConnection = new RTCPeerConnection({ iceServers });

    // Create WebRTC Signaling Client
    // This is the actual client that is used to send messages over the signaling channel.
    const signalingClient = new SignalingClient({
      channelARN,
      channelEndpoint: endpointsByProtocol.WSS,
      role: Role.MASTER,
      region,
      clientId,
      credentials: {
        accessKeyId,
        secretAccessKey,
      },
      systemClockOffset: coachingSession.config.systemClockOffset
    });

    // GET THE USER MEDIA DEVICES
    const localStream = await navigator.mediaDevices.getUserMedia({
      video: true,
      audio: true
    }).catch(e => {
      console.log("COULD NOT FIND WEBCAM");
      setShowErrorStartingVideoModal(true);
    });

    // *** AUDIO & VIDEO DEVICE COLLECTION ***
    let audioInputDevices: MediaDeviceInfo[];
    let audioOutputDevices: MediaDeviceInfo[];
    let videoInputDevices: MediaDeviceInfo[];
    try {
      const mediaDevices = await navigator.mediaDevices.enumerateDevices();
      audioInputDevices = mediaDevices.filter(device => device.kind === 'audioinput');
      audioOutputDevices = mediaDevices.filter(device => device.kind === 'audiooutput');
      videoInputDevices = mediaDevices.filter(device => device.kind === 'videoinput');
      setMicrophoneList(audioInputDevices);
      setSpeakerList(audioOutputDevices);
      setCameraList(videoInputDevices);
    } catch (e) {
      console.log(e);
      console.log("ERROR COLLECTING MEDIA DEVICE INFORMATION: MAKE SURE PERMISSIONS ARE ALLOWED AND TRY AGAIN");
    };

    // GRAB THE LOCAL PROVIDER AND PATIENT VIDEO TILES
    const providerVideoTile: HTMLVideoElement = document.getElementById('provider-video-element') as HTMLVideoElement;
    const patientVideoElement = document.getElementById('patient-video-element') as HTMLVideoElement;
    // let dataChannel: RTCDataChannel
    // Add Signaling Client Event Listeners
    signalingClient.on('open', async () => {
      if (!localStream || !peerConnection) return;

      // Get a stream from the webcam, add it to the peer connection, and display it in the local view
      try {
        localStream.getTracks().forEach(track => peerConnection.addTrack(track, localStream));
        providerVideoTile.srcObject = localStream;
      } catch (e) {
        // Could not find webcam
        console.log(e);
        return;
      };

      // Create an SDP offer and send it to the master
      const offer = await peerConnection.createOffer({
        offerToReceiveAudio: true,
        offerToReceiveVideo: true
      });

      console.log('CREATED OFFER: ', offer);

      await peerConnection.setLocalDescription(offer);

      if (peerConnection.localDescription) signalingClient.sendSdpOffer(peerConnection.localDescription, patient.patientID);
    });

    // When the SDP answer is received back from the master, add it to the peer connection.
    signalingClient.on('sdpAnswer', async answer => {
      console.log('RECEIVED ANSWER: ', answer);
      if (!peerConnection) return;
      await peerConnection.setRemoteDescription(answer).catch(e => console.log(e));
    });

    signalingClient.on('sdpOffer', async (offer, senderClientID) => {
      console.log({ offer });
      if (!peerConnection) return;

      await peerConnection.setRemoteDescription(offer).catch(e => console.log(e));
      console.log('REMOTE DESCRIPTION SET: ', peerConnection);
      const answer = await peerConnection.createAnswer().catch(e => console.log(e));

      console.log({ answer });
      if (answer) signalingClient.sendSdpAnswer(answer, senderClientID);

      // dataChannel = peerConnection.createDataChannel(`data-channel-of-${senderClientID}`);
      // dataChannel.addEventListener("open", (event) => {
      //   console.log(event);
      //   dataChannel.send('******HI ALEC*******');
      // });
    });

    // When an ICE candidate is received from the master, add it to the peer connection.
    signalingClient.on('iceCandidate', async (candidate, senderClientID) => {
      if (!peerConnection) return;
      console.log('new iceCandidate received:', candidate);

      await peerConnection.addIceCandidate(candidate).catch(e => console.log(e));
      console.log("ICE CANDIDATE ADDED: ", candidate);
    });

    signalingClient.on('close', async () => {
      if (!localStream) return;
      // Handle client closures
      console.log("ENDING THE CALL");
      localStream.getTracks().forEach(track => track.stop());
      peerConnection.close();
      if ('srcObject' in providerVideoTile) providerVideoTile.srcObject = null;
    });

    signalingClient.on('error', error => {
      // Handle client errors
      console.log(error);
    });

    signalingClient.on('chat', (dataMessage: any) => {
      const decodedMessage = UTF8Decoder.decode(new Uint8Array(dataMessage.data));
      console.log("GOT TEST MESSAGE:", decodedMessage);
    });

    signalingClient.on('SeriesData', (dataMessage: any) => {
      const seriesFromMobile = JSON.parse(UTF8Decoder.decode(new Uint8Array(dataMessage.data)));
      console.log("SERIES FROM MOBILE:", seriesFromMobile);
      kickOffSeriesCreation(seriesFromMobile);
    });

    signalingClient.on('EffortMarker', (dataMessage: any) => {
      const effortMarker = UTF8Decoder.decode(new Uint8Array(dataMessage.data));
      console.log("EFFORT MARKER:", effortMarker);
      setEffortMarker(effortMarker);
    });

    signalingClient.on('CoachingMessage', async (dataMessage: any) => {
      const coachingMessage = UTF8Decoder.decode(new Uint8Array(dataMessage.data));
      console.log("COACHING MESSAGE FROM MOBILE:", coachingMessage);
      if (coachingMessage === 'EndSeries') {
        await handleForceEndEffort(signalingClient);
        await handleEndSeries(signalingClient);
      };
    });

    // Add Peer Connection Event Listeners
    // Send any ICE candidates generated by the peer connection to the other peer
    peerConnection.addEventListener('icecandidate', ({ candidate }) => {
      if (candidate) {
        console.log(candidate);
        signalingClient.sendIceCandidate(candidate, patient.patientID);
      } else {
        // No more ICE candidates will be generated
        console.log('NO MORE ICE CANDIDATES WILL BE GENERATED');
      }
    });

    // As remote tracks are received, add them to the remote view
    peerConnection.addEventListener('track', event => {
      // if (patientVideoElement.srcObject) return;
      setNoPatientConnected(false);
      console.log({ event });
      try {
        peerConnection.addTrack(event.track, event.streams[0]);
        if (event.track.kind === 'video') patientVideoElement.srcObject = event.streams[0];
      } catch (e) {
        console.log(e);
      }
    });

    // Open Signaling Connection
    signalingClient.open();
  };


来源: stackexchange

问:
How to set state using useState and do something else as well in onChange in React?
I have a component which includes another component (from headlessui/react) defined as follows:

```<code>export default function MyComponent(props) {
  const [selectedState, setState] = useState('');
  return (
    <div>
      <RadioGroup value={selectedState} onChange={setState}>
      ...
      </RadioGroup>
    </div>
  )
}
</code>```

In the onChange I would like to first call a function which does something and then calls setState. However, nomatter what I try, I can't get this to work.

I've tried:

```<code>onChange={() => {
  doSomethingFirst();
  return setState;
}

onChange={() => {
  doSomethingFirst();
  // This requires an argument and I'm not sure what the argument should be
  setState();
}

// Even this fails
onChange={() => setState;}
</code>```

What do I do to get this working?

答:
When you pass onChange directly to RadioGroup it will invoke your setState with any arguments the RadioGroup supplies. Because setState only takes one argument that's thereby equal to doing onChange={arg => setState(arg)} which already shows how to accomplish what you're trying to do. Just emulate this exact behaviour and add in your function call:

```<code>onChange={arg => {
  doSomethingHere()
  return setState(arg)
}}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a component which includes another component (from headlessui/react) defined as follows:

export default function MyComponent(props) {
  const [selectedState, setState] = useState('');
  return (

      <RadioGroup value={selectedState} onChange={setState}>
      ...
      </RadioGroup>

  )
}

In the onChange I would like to first call a function which does something and then calls setState. However, nomatter what I try, I can't get this to work.

I've tried:

onChange={() => {
  doSomethingFirst();
  return setState;
}

onChange={() => {
  doSomethingFirst();
  // This requires an argument and I'm not sure what the argument should be
  setState();
}

// Even this fails
onChange={() => setState;}

What do I do to get this working?

Body:
When you pass onChange directly to RadioGroup it will invoke your setState with any arguments the RadioGroup supplies. Because setState only takes one argument that's thereby equal to doing onChange={arg => setState(arg)} which already shows how to accomplish what you're trying to do. Just emulate this exact behaviour and add in your function call:

onChange={arg => {
  doSomethingHere()
  return setState(arg)
}}


问:
Design tips for a program to be run in 25 years
If creating an application (that does mostly data processing) that needs to be run now and maybe (maybe not) 10 or 25 years later, what design tips are out there for such applications?

The general rules apply: rely on open source software and proven platforms and failsafe data formats.

The language must be a high-level language for readability reasons (maybe the only option will be re-writing the application in 15 years by someone who has little knowledge of the original code).

I'd go for UNIX(Linux)+Python+YAML/JSON(/CSV/plaintext), any tips for this selection or an alternative toolset? Scheme/lisp has been around for ages and is really hard to screw up the language basics as well, given that everything would be self-contained.

EDIT: please don't forget tips about actual design and code, like 2038 year issue!

答:
It would be interesting to know the half-life of a deployed application. My guess is that 10 years is not at all unusual, and the core applications of an enterprise may well be more than 25 years old - there's a heck of a lot of Mainframe/CICS apps out there.

Hence, I'd claim that any serious development has to anticipate that the application will be used for at least 10 years. Large Enterpises may well have a policy of "Evergreening" - that is migrating their applications to later versions of Operating Systems, Databases etc.

It's effectively impossible to second-guess the longevity of any platform, so just select something that's pretty widely adopted and which is in some sense (De facto or formally) a standard.

Your suggested stack is reasonable, Java and Spring or Java EE would be good too.

I would pay attention to the modularity and "openness" of the application. When I say that many apps are more than 10 years old that doesn't mean they fossilised in that time. The apps change both internally and integrate with more and more systems. Those CICS apps now produce data being viewed on mobile devices that were unheard of 20 years ago.

So look at interfaces into your application, choose a layered and modular architecture that allows the internals to evolve and accommodates new integrations.

ContentLicense: CC BY-SA 3.0


问:
Get the full path of file name which is numbers only `highest number` , on main Folder or Subfolders?
I am using database software and export excel files from it and save on my desktop with name like ********.xls

***** means numbers only , for example   08134471.xls

23222578.xls

Those numbers on file name are random on count and length.

The path is constant D:\Users\Waleed\Desktop\    but, file name will change each time incrementally to higher number.

So, I need to open the workbook with highest number on the cited path.

In advance , gratefully for your help.

```<code>Sub Open_Numeric_File()

    Workbooks.Open "D:\Users\Waleed\Desktop\08134471.xls"

End Sub
</code>```

答:
Something for you to consider:

```<code>Sub OpenAndCalc()

Dim myDir As String, fn As String, high As String, highVal As Long

    myDir = "D:\Users\Waleed\Desktop\"
    fn = Dir(myDir & "*.xls")

    Do While fn <> "" And Not fn Like "*[!0-9]*.xls"
        If Val(fn) > highVal Then highVal = Val(fn): high = fn
        fn = Dir()
    Loop

    Workbooks.Open myDir & high

End Sub
</code>```

This should:

Loop through all '.xls' files in your static directory;

Test if anything before '.xls' is numeric through Like();

Test the numeric substring, using Val(), against previous (or empty) value;

Append the static directory with the highest value and open this workbook.

Body:
I am using database software and export excel files from it and save on my desktop with name like ********.xls

***** means numbers only , for example   08134471.xls

23222578.xls

Those numbers on file name are random on count and length.

The path is constant D:\Users\Waleed\Desktop\    but, file name will change each time incrementally to higher number.

So, I need to open the workbook with highest number on the cited path.

In advance , gratefully for your help.

Sub Open_Numeric_File()

    Workbooks.Open "D:\Users\Waleed\Desktop\08134471.xls"

End Sub

Body:
Something for you to consider:

Sub OpenAndCalc()

Dim myDir As String, fn As String, high As String, highVal As Long

    myDir = "D:\Users\Waleed\Desktop\"
    fn = Dir(myDir & "*.xls")

    Do While fn <> "" And Not fn Like "*[!0-9]*.xls"
        If Val(fn) > highVal Then highVal = Val(fn): high = fn
        fn = Dir()
    Loop

    Workbooks.Open myDir & high

End Sub

This should:

Loop through all '.xls' files in your static directory;

Test if anything before '.xls' is numeric through Like();

Test the numeric substring, using Val(), against previous (or empty) value;

Append the static directory with the highest value and open this workbook.


问:
Dynamicly call a variable from enum values
In my flutter app, I organize my strings with LocalizationsDelegate to manage locale language.

So to call a string, I write :

```<code>Languages.of(context).NAME_VARIABLE;
</code>```

I have never seen what I'm trying to do and I'm not sure how to word it, so I'm gonna try to show what I want to achieve.

Let's say I have an enum class like this :

```<code>enum Numbers {
 one,
 two,
 three,
}
</code>```

I would like to dynamicly call strings (which I would have already added to my Languages files), something in this spirit :

```<code>  List<String> numbersStr = <String>[];
  for (String number in Numbers.values) {
  numbersStr.add(Languages.of(context).number);
}
</code>```

Is there any way to do something like that, or do I have to manually link each value to its string?

答:
I haven't used it with translations but maybe its worth a try.
https://pub.dev/packages/enhanced_enum</p>

Body:
In my flutter app, I organize my strings with LocalizationsDelegate to manage locale language.

So to call a string, I write :

Languages.of(context).NAME_VARIABLE;

I have never seen what I'm trying to do and I'm not sure how to word it, so I'm gonna try to show what I want to achieve.

Let's say I have an enum class like this :

enum Numbers {
 one,
 two,
 three,
}

I would like to dynamicly call strings (which I would have already added to my Languages files), something in this spirit :

  List<String> numbersStr = <String>[];
  for (String number in Numbers.values) {
  numbersStr.add(Languages.of(context).number);
}

Is there any way to do something like that, or do I have to manually link each value to its string?


问:
overlayfs inside docker container
Is it possible to mount an overlay fs inside a (privileged) docker container? At least my intuitive approach, which works fine outside of a container, fails:

```<code>> mkdir /tmp/{up,low,work,merged}
> mount -t overlay overlay -o lowerdir=/tmp/low/,upperdir=/tmp/up/,workdir=/tmp/work/ /tmp/merged/
mount: /tmp/merged: wrong fs type, bad option, bad superblock on overlay, missing codepage or helper program, or other error.
</code>```

Additional information:

Docker version 18.09.1, build 4c52b90

Kernel 4.19.0-8-amd64

Debian 10 (host and docker-image)

答:
This is a bit of a guess but I suspect it is because docker is already using overlayfs and overlayfs is refusing to use upperdir as another overlayfs.

I suspect this may be due to whiteout files:

In order to support rm and rmdir without changing the lower
filesystem, an overlay filesystem needs to record in the upper
filesystem that files have been removed.  This is done using whiteouts
and opaque directories (non-directories are always opaque).

A whiteout is created as a character device with 0/0 device number.
When a whiteout is found in the upper level of a merged directory, any
matching name in the lower level is ignored, and the whiteout itself
is also hidden.

To delete a file that exists in a lowerdir, overlayfs will create a whiteout file and hides all whiteout files (device number 0,0).  This logically means that you cannot create a character device file with number 0,0 inside an overlayfs because that must be hidden by overlayfs itself.

If you were allowed to use an overlayfs as an upperdir it wouldn't be able to create blackout files and therefore wouldn't be able to rm or rmdir any files from the lower layers. Because it can't create a character device file with number 0,0 on another overlayfs.

Title: overlayfs inside docker container

Body:
Is it possible to mount an overlay fs inside a (privileged) docker container? At least my intuitive approach, which works fine outside of a container, fails:

> mkdir /tmp/{up,low,work,merged}
> mount -t overlay overlay -o lowerdir=/tmp/low/,upperdir=/tmp/up/,workdir=/tmp/work/ /tmp/merged/
mount: /tmp/merged: wrong fs type, bad option, bad superblock on overlay, missing codepage or helper program, or other error.

Additional information:

Docker version 18.09.1, build 4c52b90

Kernel 4.19.0-8-amd64

Debian 10 (host and docker-image)


问:
Sum formula monthly columns
im trying to sum up a group of monthly figures into my summary page from other tabs, without using SUM formula, as the other tabs column shifts and moves everytime its copied over.

im trying to find a formula that captures the total of the year, even though the columns move.

below is the tab1

trying to get the summary like the below 2

答: You can find the column number of your total with match formula.  Then get the sum with vlookup like this:

Title: Sum formula monthly columns


问:
R Avoid rowwise() and looking for faster alternative
I want to merge two vectors into one dataset and integrate it with the function mutate as 5 new columns into the already existing dataset.
Here is my example code:

```<code>vector1<-list(c("Reply","Reshare","Like","Share","Search"),c("Reply","Reshare","Like","Share","Search"),c("Reply","Reshare","Like","Share","Search"))
vector2<-list(c(1,2,6,3,4),c(3,7,9,2,4),c(5,2,8,4,0))

tibble(vector1=vector1,
       vector2=vector2)%>%
  rowwise()%>%
  mutate(vector2|> set_names(vector1)|> as.list()|> data.frame())

# A tibble: 3 x 7
# Rowwise:
  vector1   vector2   Reply Reshare  Like Share Search
  <list>    <list>    <dbl>   <dbl> <dbl> <dbl>  <dbl>
1 <chr [5]> <dbl [5]>     1       2     6     3      4
2 <chr [5]> <dbl [5]>     3       7     9     2      4
3 <chr [5]> <dbl [5]>     5       2     8     4      0
</code>```

This works quite well so far. However, I have a very large dataset and the rowwise() solution is very time consuming.
If I omit the rowwise() function I get an error message.

I think the error is due to the fact that I transform the vectors as a list (as.list()). The mutate function for the data set does not seem to be able to handle this.

The rowwise() function should be omitted and only the code in the mutate function should be changed.

Can anyone help me and provide a faster solution?

答:
If vector1 has the same values (and in the same order) always like in the example we can do this in base R in a more simpler way.

```<code>do.call(rbind, vector2) |>
  as.data.frame() |>
  setNames(vector1[[1]])

#  Reply Reshare Like Share Search
#1     1       2    6     3      4
#2     3       7    9     2      4
#3     5       2    8     4      0
</code>```

Body:
I want to merge two vectors into one dataset and integrate it with the function mutate as 5 new columns into the already existing dataset.
Here is my example code:

vector1<-list(c("Reply","Reshare","Like","Share","Search"),c("Reply","Reshare","Like","Share","Search"),c("Reply","Reshare","Like","Share","Search"))
vector2<-list(c(1,2,6,3,4),c(3,7,9,2,4),c(5,2,8,4,0))

tibble(vector1=vector1,
       vector2=vector2)%>%
  rowwise()%>%
  mutate(vector2|> set_names(vector1)|> as.list()|> data.frame())

# A tibble: 3 x 7
# Rowwise:
  vector1   vector2   Reply Reshare  Like Share Search
  <list>    <list>    <dbl>   <dbl> <dbl> <dbl>  <dbl>
1 <chr [5]> <dbl [5]>     1       2     6     3      4
2 <chr [5]> <dbl [5]>     3       7     9     2      4
3 <chr [5]> <dbl [5]>     5       2     8     4      0

This works quite well so far. However, I have a very large dataset and the rowwise() solution is very time consuming.
If I omit the rowwise() function I get an error message.

I think the error is due to the fact that I transform the vectors as a list (as.list()). The mutate function for the data set does not seem to be able to handle this.

The rowwise() function should be omitted and only the code in the mutate function should be changed.

Can anyone help me and provide a faster solution?

Body:
If vector1 has the same values (and in the same order) always like in the example we can do this in base R in a more simpler way.

do.call(rbind, vector2) |>
  as.data.frame() |>
  setNames(vector1[[1]])

#  Reply Reshare Like Share Search
#1     1       2    6     3      4
#2     3       7    9     2      4
#3     5       2    8     4      0


问:
I have a hard time understanding the purpose of a "backing property"
I am learning Kotlin right now. For context, I am a Java developer for +10 years.

I stumbled upon the concept of backing properties. As I understand it, the problem to be solved is this: I have a property in a class. I want this property to be mutable and visible only in the containing class, so I declare it as private var. The property should only be modified in the containing class, but it should be readable outside the class. So, the Kotlin docs propose something like this:

private var _word = "test"
val word: String
   get() = _word
```
<p>This works and fulfills the above requirements, but this looks a bit odd, for a Java developer. In Java, we only need 1 field (there is no such thing as a property in Java):</p>
```private String word = "test";

public String getWord() {
   return word;
}
```
<p>AFAIK, same result.</p>
<p>Today I learned that in Kotlin, I simply can make a setter private. So what about this Kotlin code:</p>
```var word = "test"
     private set
```

All requirements fulfilled, much more concise code.

Im I missing something? Why do I need a backing property?

答:
(This answer starts with some general info about Kotlin properties, as there seems to be general confusion about them.)

The main conceptual difference between Kotlin and Java is that in Java, the fundamental thing is the field, while in Kotlin the fundamental thing is the accessor method(s).

So in Java, you define a field. You can then define explicit getter and/or setter methods for it, if needed. The language doesn't have a concept of ‘property’, nor does it define any explicit connection between the accessors and the field; but there's a long-standing convention in the accessor method names (deriving originally from JavaBeans) that almost everyone follows.

This is clear, but long-winded. And because it's only a convention, the language doesn't force you to match fields with accessors: you can have accessors with different types, setters without getters and vice versa, or even accessors with no field. (Some of those things are desirable, but others are more likely to cause bugs and confusion!)

Kotlin, however, takes the view that the accessors are the important thing. (This is an example of the general principle that you should program to the interface, not caring about how it may be implemented.) In effect, a property is its accessor(s). As long as you have a getter method, then you can get the property's value; and as long as you have a setter method, then you can set it too.

Because getters and setters are usually trivial, Kotlin defines them implicitly unless you tell it otherwise. So when you write:

```<code>val myProperty = 1
</code>```

then Kotlin creates:

A private field called myProperty, with the type inferred as Int, and initialised to the value 1.

A getter method called getMyProperty(), with public scope (as that's the default), returning an Int.

That's just what you'd do in Java, only more concise.

What's different is that whenever you refer to the property, you're calling the accessor method, not accessing the field directly. (That's why it's called a backing field — its only purpose is for the accessor(s) to use.)

Of course, the effect is identical unless you override the accessor. For example:

```<code>val myProperty = 1
    get() {
        LOG.info("Getting value of myProperty = $field")
        return field
    }
</code>```

(field is a special keyword within getters and setters, referring to their backing field.)

As before, this generates a field and a getter method; but the getter method is specified in the code and not autogenerated.

(I haven't referred to mutable properties or setters, but the principle there is the same: if the property is a var, then you get an autogenerated or explicit setter method too. One Java possibility that Kotlin doesn't support is write-only properties, where some scope can see a setter but no getter. But those are rarely used; you can always use a normal method to set them, which is probably clearer.)

There's one more case to consider. In Java, a getter method can exist on its own, without a corresponding field. (It must then get its value from some other source — maybe by performing a calculation on other fields, or getting it from another object, or even using a hard-coded value.)

You can do the same in Kotlin, by overriding the getter (and setter, if mutable) and not referring to the field, e.g.:

```<code>val myProperty: Int
    get() = someOtherObject.someOtherProperty
</code>```

In this case, there would be no point in generating a field, because it would never be used! So Kotlin recognises this and generates only the accessor method(s).

It's still a property, because it still has accessor method(s), and the rest of the code can't see any difference. Whether it has a backing field or not is purely an implementation detail.

This question is asking about a ‘backing property’. The official docs use that term for a separate, private property which ‘shadows’ an existing one, as shown in this question. (Thanks to cactustictacs for the reference.)

There are specific situations where a backing property can be useful. For example, suppose you need to refer to a specific type within the class, but expose only a supertype publicly; the private property could be of the specific type, and then the public one could be of the supertype.

However, that's not needed simply to restrict the visibility of a setter method: as the question demonstrates, that can be done explicitly (e.g. by adding private set to the property definition).

(In my experience, backing properties are needed very rarely.)

Body:
I am learning Kotlin right now. For context, I am a Java developer for +10 years.

I stumbled upon the concept of backing properties. As I understand it, the problem to be solved is this: I have a property in a class. I want this property to be mutable and visible only in the containing class, so I declare it as private var. The property should only be modified in the containing class, but it should be readable outside the class. So, the Kotlin docs propose something like this:

private var _word = "test"
val word: String
   get() = _word

This works and fulfills the above requirements, but this looks a bit odd, for a Java developer. In Java, we only need 1 field (there is no such thing as a property in Java):

private String word = "test";

public String getWord() {
   return word;
}

AFAIK, same result.

Today I learned that in Kotlin, I simply can make a setter private. So what about this Kotlin code:

var word = "test"
     private set

All requirements fulfilled, much more concise code.

Im I missing something? Why do I need a backing property?

Body:
(This answer starts with some general info about Kotlin properties, as there seems to be general confusion about them.)

The main conceptual difference between Kotlin and Java is that in Java, the fundamental thing is the field, while in Kotlin the fundamental thing is the accessor method(s).

So in Java, you define a field. You can then define explicit getter and/or setter methods for it, if needed. The language doesn't have a concept of ‘property’, nor does it define any explicit connection between the accessors and the field; but there's a long-standing convention in the accessor method names (deriving originally from JavaBeans) that almost everyone follows.

This is clear, but long-winded. And because it's only a convention, the language doesn't force you to match fields with accessors: you can have accessors with different types, setters without getters and vice versa, or even accessors with no field. (Some of those things are desirable, but others are more likely to cause bugs and confusion!)

Kotlin, however, takes the view that the accessors are the important thing. (This is an example of the general principle that you should program to the interface, not caring about how it may be implemented.) In effect, a property is its accessor(s). As long as you have a getter method, then you can get the property's value; and as long as you have a setter method, then you can set it too.

Because getters and setters are usually trivial, Kotlin defines them implicitly unless you tell it otherwise. So when you write:

val myProperty = 1

then Kotlin creates:

A private field called myProperty, with the type inferred as Int, and initialised to the value 1.

A getter method called getMyProperty(), with public scope (as that's the default), returning an Int.

That's just what you'd do in Java, only more concise.

What's different is that whenever you refer to the property, you're calling the accessor method, not accessing the field directly. (That's why it's called a backing field — its only purpose is for the accessor(s) to use.)

Of course, the effect is identical unless you override the accessor. For example:

val myProperty = 1
    get() {
        LOG.info("Getting value of myProperty = $field")
        return field
    }

(field is a special keyword within getters and setters, referring to their backing field.)

As before, this generates a field and a getter method; but the getter method is specified in the code and not autogenerated.

(I haven't referred to mutable properties or setters, but the principle there is the same: if the property is a var, then you get an autogenerated or explicit setter method too. One Java possibility that Kotlin doesn't support is write-only properties, where some scope can see a setter but no getter. But those are rarely used; you can always use a normal method to set them, which is probably clearer.)

There's one more case to consider. In Java, a getter method can exist on its own, without a corresponding field. (It must then get its value from some other source — maybe by performing a calculation on other fields, or getting it from another object, or even using a hard-coded value.)

You can do the same in Kotlin, by overriding the getter (and setter, if mutable) and not referring to the field, e.g.:

val myProperty: Int
    get() = someOtherObject.someOtherProperty

In this case, there would be no point in generating a field, because it would never be used! So Kotlin recognises this and generates only the accessor method(s).

It's still a property, because it still has accessor method(s), and the rest of the code can't see any difference. Whether it has a backing field or not is purely an implementation detail.

This question is asking about a ‘backing property’. The official docs use that term for a separate, private property which ‘shadows’ an existing one, as shown in this question. (Thanks to cactustictacs for the reference.)

There are specific situations where a backing property can be useful. For example, suppose you need to refer to a specific type within the class, but expose only a supertype publicly; the private property could be of the specific type, and then the public one could be of the supertype.

However, that's not needed simply to restrict the visibility of a setter method: as the question demonstrates, that can be done explicitly (e.g. by adding private set to the property definition).

(In my experience, backing properties are needed very rarely.)


问:
multiple condition at select-object expression powershell
I am getting IP and Name data from infoblox API like below

As you can see there are certain entries which are blank or having like "gateway"/"reserved s"

I need to eliminate such entries and write rest of the data in csv. currently I am writing all of the data using below code

```<code>    $url = "https://example.net/wapi/v2.10.5/ipv4address?network=$subnet&status=USED&_return_as_object=1"

    $lapw = Get-Content "E:\EncryptedPassword\pw.txt" | ConvertTo-SecureString -Key (Get-Content E:\EncryptedPassword\aes.key)
    $creds = New-Object System.Management.Automation.PsCredential("USER",$lapw)
    $Result_IPAddress = Invoke-RestMethod -Uri $url -Method Get -Credential $creds -Headers $headers -ContentType 'application/json'

$Result_IPAddress.Result |
Select-Object @{Name='IPAddress';Expression='IP_Address'},
              @{Name='IPName';Expression={$_.names -join ' ;'}}  | Export-Csv -Path "E:\Used_IP_Details.csv" -NoTypeInformation -Append -Force

</code>```

Please let me know how can I filter the data. as of now I got only these 3 types which I have to ignore writing but later there might be more such keywords which I have to ignore and filter out the data.

I tried giving like this

```<code>@{Name='IPName';Expression={$_.names -join ' ;'} -and {$_.names -match 'reserved s'} -or {$_.names -match 'gateway'}}
</code>```

but problem is I am not getting how to give condition for Blank and there are certain entries which starts with "reserved" but have followed hostname in it so I have to keep them. So have to have strict matching.

With respect to @MathiasR.Jessen answer, tried below

```<code>$addressesAndNames = $Result_IPAddress.Result |
Select-Object @{Name='IPAddress';Expression='IP_Address'},
              @{Name='IPName';Expression={$_.names -join ' ;'}}

$addressesAndNames | Where-Object $_.IPName -notlike 'reserved *' | Where-Object $_.IPName -notlike 'gateway' | Where-Object $_.IPName -ne '' | Export-Csv -Path "E:\ComparisonFiles\InfoBlox_Used_IP_Details.csv" -NoTypeInformation -Append -Force
</code>```

but getting error like

```<code>Where-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
At E:\InfoBlox_CMDB_Comparison_Report.ps1:101 char:35
+ $addressesAndNames | Where-Object $_.IPName -notlike 'reserved *' | W ...
+                                   ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Where-Object], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WhereObjectCommand
</code>```

答:
Select-Object is not for filtering. For that, you'll want to use Where-Object:

```<code>$addressesAndNames = $Result_IPAddress.Result | Select-Object @{Name='IPAddress';Expression='IP_Address'},@{Name='IPName';Expression={$_.names -join ' ;'}}

# use `Where-Object` to filter the output from `Select-Object`
$addressesAndNames |Where-Object IPName -notlike 'reserved *' |Export-Csv ...
</code>```

You can chain as many excluding Where-Object commands as you like:

```<code>$addressesAndNames |Where-Object IPName -notlike 'reserved *' |Where-Object IPName -notlike '*gateway*' |Export-Csv ...
</code>```

Body:
I am getting IP and Name data from infoblox API like below

As you can see there are certain entries which are blank or having like "gateway"/"reserved s"

I need to eliminate such entries and write rest of the data in csv. currently I am writing all of the data using below code

    $url = "https://example.net/wapi/v2.10.5/ipv4address?network=$subnet&status=USED&_return_as_object=1"

    $lapw = Get-Content "E:\EncryptedPassword\pw.txt" | ConvertTo-SecureString -Key (Get-Content E:\EncryptedPassword\aes.key)
    $creds = New-Object System.Management.Automation.PsCredential("USER",$lapw)
    $Result_IPAddress = Invoke-RestMethod -Uri $url -Method Get -Credential $creds -Headers $headers -ContentType 'application/json'

$Result_IPAddress.Result |
Select-Object @{Name='IPAddress';Expression='IP_Address'},
              @{Name='IPName';Expression={$_.names -join ' ;'}}  | Export-Csv -Path "E:\Used_IP_Details.csv" -NoTypeInformation -Append -Force

Please let me know how can I filter the data. as of now I got only these 3 types which I have to ignore writing but later there might be more such keywords which I have to ignore and filter out the data.

I tried giving like this

@{Name='IPName';Expression={$_.names -join ' ;'} -and {$_.names -match 'reserved s'} -or {$_.names -match 'gateway'}}

but problem is I am not getting how to give condition for Blank and there are certain entries which starts with "reserved" but have followed hostname in it so I have to keep them. So have to have strict matching.

With respect to @MathiasR.Jessen answer, tried below

$addressesAndNames = $Result_IPAddress.Result |
Select-Object @{Name='IPAddress';Expression='IP_Address'},
              @{Name='IPName';Expression={$_.names -join ' ;'}}

$addressesAndNames | Where-Object $_.IPName -notlike 'reserved *' | Where-Object $_.IPName -notlike 'gateway' | Where-Object $_.IPName -ne '' | Export-Csv -Path "E:\ComparisonFiles\InfoBlox_Used_IP_Details.csv" -NoTypeInformation -Append -Force

but getting error like

Where-Object : Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
At E:\InfoBlox_CMDB_Comparison_Report.ps1:101 char:35
+ $addressesAndNames | Where-Object $_.IPName -notlike 'reserved *' | W ...
+                                   ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Where-Object], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.WhereObjectCommand

Body:
Select-Object is not for filtering. For that, you'll want to use Where-Object:

$addressesAndNames = $Result_IPAddress.Result | Select-Object @{Name='IPAddress';Expression='IP_Address'},@{Name='IPName';Expression={$_.names -join ' ;'}}

# use `Where-Object` to filter the output from `Select-Object`
$addressesAndNames |Where-Object IPName -notlike 'reserved *' |Export-Csv ...

You can chain as many excluding Where-Object commands as you like:

$addressesAndNames |Where-Object IPName -notlike 'reserved *' |Where-Object IPName -notlike '*gateway*' |Export-Csv ...


问:
filter object array with other object array - React Typescript
I'm getting data from the server and saving it in 2 different states so one will show all the data received and the other one will show it as pagination.

The array type is:

```<code>type ArrayType = {
  name:string;
  id:number;
  link:string;
}
</code>```

Now the first array has over 200 objects inside of it, while the second array has only 15 objects inside of it.

I'm trying to loop and filter it but it returns the lasts objects + the same last Objects:

interface ComponentState {
  total?: ArrayType[];
  few?: ArrayType[];
}

const Component = () => {
  const isMounted = useRef(true);
  const [state, setState] = useState<ComponentState>({});

  useEffect(() => {
    const updateState = async () => {
      const res = await fetch(FetchUrl);
      const data = await res.json();
      setState((prevState) => ({
        ...prevState,
        total: data,
        few: data.slice(0, 10),
      }));
    };

    if (isMounted.current) updateState();

    return () => {
      isMounted.current = false;
    };
  }, []);
};```
</div>
</div>
</p>
<p>Now When I want to update The state.few I'm trying to do:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>const onButtonClick = () => {
    setState((prevState) => ({
      ...prevState,
      few: [
        ...state.few!,
        ...state.total!.filter((item) =>
          state.few!.filter((prevItem) => prevItem !== item)
        ).slice(0,10),
      ],
    }));
  };

  console.log(state.few);

  return <button onClick={onButtonClick}></button>;</code>```

And I keep getting the first 10 items of state.total instead of the next 10 items in the list

答:
In React you should not store variables that can be calculated from the state in another state.

So what's the information you need to implement a 'load more' button?

all the list elements

the index up to which you want to render

These are your state variables. Which items to render can be calculated from those.

So I would implement your component as follows:

```<code>const Component = ()=> {
  const [items, setItems] = useState([]);
  const [showN, setShowN] = useState(10);

  // calculate elements to render from state
  const toRender = items.slice(0, showN);

  useEffect(()=>{
    // your isMounted ref does not work. You need to check if the component is mounted before setting the state, not before firing the async function
    let stillMounted = true;
    const updateState = async () => {
      const res = await fetch(FetchUrl);
      const data = await res.json();
      // check if still mounted
      if(!stillMounted) return;
      setItems(data);
      };
    updateState();
    // on unmount, this function will be called, preventing a state update on an unmounted component
    return ()=>stillMounted = false;
  }, []);

  // just update the showN state when the button is clicked
  const onButtonClick = ()=>{
    setShowN(before=>before + 10);
  }
  // return something
}
</code>```

Body:
I'm getting data from the server and saving it in 2 different states so one will show all the data received and the other one will show it as pagination.

The array type is:

type ArrayType = {
  name:string;
  id:number;
  link:string;
}

Now the first array has over 200 objects inside of it, while the second array has only 15 objects inside of it.

I'm trying to loop and filter it but it returns the lasts objects + the same last Objects:

interface ComponentState {
  total?: ArrayType[];
  few?: ArrayType[];
}

const Component = () => {
  const isMounted = useRef(true);
  const [state, setState] = useState<ComponentState>({});

  useEffect(() => {
    const updateState = async () => {
      const res = await fetch(FetchUrl);
      const data = await res.json();
      setState((prevState) => ({
        ...prevState,
        total: data,
        few: data.slice(0, 10),
      }));
    };

    if (isMounted.current) updateState();

    return () => {
      isMounted.current = false;
    };
  }, []);
};

Now When I want to update The state.few I'm trying to do:

const onButtonClick = () => {
    setState((prevState) => ({
      ...prevState,
      few: [
        ...state.few!,
        ...state.total!.filter((item) =>
          state.few!.filter((prevItem) => prevItem !== item)
        ).slice(0,10),
      ],
    }));
  };

  console.log(state.few);

  return <button onClick={onButtonClick}></button>;

And I keep getting the first 10 items of state.total instead of the next 10 items in the list

Body:
In React you should not store variables that can be calculated from the state in another state.

So what's the information you need to implement a 'load more' button?

all the list elements

the index up to which you want to render

These are your state variables. Which items to render can be calculated from those.

So I would implement your component as follows:

const Component = ()=> {
  const [items, setItems] = useState([]);
  const [showN, setShowN] = useState(10);

  // calculate elements to render from state
  const toRender = items.slice(0, showN);

  useEffect(()=>{
    // your isMounted ref does not work. You need to check if the component is mounted before setting the state, not before firing the async function
    let stillMounted = true;
    const updateState = async () => {
      const res = await fetch(FetchUrl);
      const data = await res.json();
      // check if still mounted
      if(!stillMounted) return;
      setItems(data);
      };
    updateState();
    // on unmount, this function will be called, preventing a state update on an unmounted component
    return ()=>stillMounted = false;
  }, []);

  // just update the showN state when the button is clicked
  const onButtonClick = ()=>{
    setShowN(before=>before + 10);
  }
  // return something
}


问:
Adding custom log locations to the OS X console application
After searching online, the best solution I've found so far is to just make a symbolic link in either "/Library/logs/" or "~/Library/logs/" to get it to show up in the Console application.

I'm wondering if it would be possible to add a new directory or log file to the "root" level directly under the "LOG FILES" section in the console.

Here's a quick screenshot:

答: You can just open any text file with console.app and it will add and keep it. Folder's though, no luck on that yet.</p>

OwnerDisplayName: Wilco


问:
How to add space in data/String using python?
I have some data in my database. It looks like 84819010 and I wanted to make it like 8481 90 10
I use the following code and get the following error:

```<code>information_table = data.cur.execute("""
                    SELECT p.gs_com_code, p.gs_code FROM product p
                    INNER JOIN (
                    SELECT pp.p_gs_com_code From product_purchase pp
                    ) t ON t.p_gs_com_code = p.gs_com_code
                         """,).fetchall()

for info in information_table:
    t = info[1]
    sep = "{}{}{}{} {}{} {}{}"
    gs_code = sep.format(*t)
    print(gs_code)

</code>```

Error:

```<code>    gs_code = sep.format(*t)
IndexError: Replacement index 7 out of range for positional args tuple
</code>```

My information looks like 84819010 and I wanted to make it like 8481 90 10

答:
Use f-strings:

```<code>for info in information_table:
    gs_code = f"{info[:4]} {info[4:6]} {info[6:]}"
    print(gs_code)

# Output
6804 22 00
7018 10 00
8712 00 00
6804 22 00
</code>```

Body:
I have some data in my database. It looks like 84819010 and I wanted to make it like 8481 90 10
I use the following code and get the following error:

information_table = data.cur.execute("""
                    SELECT p.gs_com_code, p.gs_code FROM product p
                    INNER JOIN (
                    SELECT pp.p_gs_com_code From product_purchase pp
                    ) t ON t.p_gs_com_code = p.gs_com_code
                         """,).fetchall()

for info in information_table:
    t = info[1]
    sep = "{}{}{}{} {}{} {}{}"
    gs_code = sep.format(*t)
    print(gs_code)

Error:

    gs_code = sep.format(*t)
IndexError: Replacement index 7 out of range for positional args tuple

My information looks like 84819010 and I wanted to make it like 8481 90 10

Body:
Use f-strings:

for info in information_table:
    gs_code = f"{info[:4]} {info[4:6]} {info[6:]}"
    print(gs_code)

# Output
6804 22 00
7018 10 00
8712 00 00
6804 22 00


答:
I would suggest a standard join, followed by a grouped filter to the closest instance of each timestamp:

```<code>library(tidyverse)
library(lubridate)

match_timest <- event_timest %>%
  inner_join(lv_timest, by = "Date") %>%
  mutate(diff = abs(as.numeric(Date_time.x - Date_time.y, unit = "hours"))) %>%
  group_by(Date_time.y) %>%
  filter(diff <= 1 & diff == min(diff)) %>%
  ungroup() %>%
  select(!diff)
</code>```

Note:

this will still match multiple rows if there’s more than one that are the exact same shortest difference from the index timestamp.

this won’t match timestamps from different dates — eg, 23:59:59 on 1/1/22 won’t be matched with 00:00:00 on 1/2/22. If you’d like to do that, you can use a full Cartesian join (full_join(lv_timest, by = character())) rather than the inner_join() above.

Title: Match two tables based on a time difference criterium

Body:
I have a data table (lv_timest) with time stamps every 3 hours for each date:

# A tibble: 6 × 5
     LV0_mean LV1_mean  LV2_mean Date_time           Date
     <dbl>    <dbl>     <dbl>    <S3:POSIXct>        <date>
1    0.778    -4.12     0.736    2016-12-28 00:00:00 2016-12-28
2    0.376    -0.234    0.388    2016-12-28 03:00:00 2016-12-28
3    0.409    1.46      0.241    2016-12-28 06:00:00 2016-12-28
4    0.760    2.07      0.460    2016-12-28 09:00:00 2016-12-28
5    0.759    2.91      0.735    2016-12-28 12:00:00 2016-12-28
6    0.857    3.00      0.803    2016-12-28 15:00:00 2016-12-28

from which I would like to extract the time stamps that match as closely as possible those of another table (event_timest):

# A tibble: 6 × 4
   Event_number Date_time           Date       Date_time_new
   <int>        <S3: POSIXct>       <date>     <S3: POSIXct>
1  75           2016-12-28 08:00:00 2016-12-28 2016-12-28 08:00:00
2  123          2016-12-30 14:02:00 2016-12-30 2016-12-30 14:00:00
3  264          2017-01-07 06:12:00 2017-01-07 2017-01-07 06:00:00
4  317          2017-01-09 10:59:00 2017-01-09 2017-01-09 11:00:00
5  318          2017-01-09 13:31:00 2017-01-09 2017-01-09 14:00:00
6  369          2017-01-11 07:24:00 2017-01-11 2017-01-11 07:00:00

For example, for row 1 in table event_timest, I would extract row 4 from table lv_timest:

Event_number Date_time.x          Date.x      Date_time_new      LV0_mean LV1_mean   LV2_mean Date_time.y          Date.y
<int>        <S3: POSIXct>        <date>      <S3: POSIXct>      <dbl>    <dbl>      <dbl>    <S3: POSIXct>        <date>
75           2016-12-28 08:00:00  2016-12-28 2016-12-28 08:00:00 0.760    2.07       0.460    2016-12-28 09:00:00  2016-12-28

In fact, the time difference should not be over one hour. I thought of using the fuzzyjoin package for this, and writing a function that computes the time difference between timestamps of the two table, as hours. However, fuzzy_inner_join replicates rows in the second table and takes several timestamps in the first table to match it.

require(lubridate)
require(fuzzyjoin)

diff_timest <- function(x, y){abs(x%--%y %/% hours(1)) <= 1} # time interval as hours ≤ 1 hour

match_timest <- fuzzy_inner_join(event_timest, lv_timest,
                                 by = c("Date" = "Date",
                                        "Date_time_new" = "Date_time"),
                                 match_fun = list(`==`, diff_timest))
head(match_timest)

# A tibble: 6 × 9
  Event_number Date_time.x         Date.x     Date_time_new       LV0_mean LV1_mean LV2_mean Date_time.y         Date.y
         <int> <dttm>              <date>     <dttm>                 <dbl>    <dbl>    <dbl> <dttm>              <date>
1           75 2016-12-28 08:00:00 2016-12-28 2016-12-28 08:00:00   0.760     2.07     0.460 2016-12-28 09:00:00 2016-12-28
2          123 2016-12-30 14:02:00 2016-12-30 2016-12-30 14:00:00   1.24      1.83     2.05  2016-12-30 15:00:00 2016-12-30
3          264 2017-01-07 06:12:00 2017-01-07 2017-01-07 06:00:00  -0.128    -5.43     2.72  2017-01-07 06:00:00 2017-01-07
4          317 2017-01-09 10:59:00 2017-01-09 2017-01-09 11:00:00  -0.0751    0.171    2.56  2017-01-09 09:00:00 2017-01-09
5          317 2017-01-09 10:59:00 2017-01-09 2017-01-09 11:00:00  -0.204    -0.797    2.28  2017-01-09 12:00:00 2017-01-09
6          318 2017-01-09 13:31:00 2017-01-09 2017-01-09 14:00:00  -0.204    -0.797    2.28  2017-01-09 12:00:00 2017-01-09

Would there be another way to do this?

Body:
I would suggest a standard join, followed by a grouped filter to the closest instance of each timestamp:

library(tidyverse)
library(lubridate)

match_timest <- event_timest %>%
  inner_join(lv_timest, by = "Date") %>%
  mutate(diff = abs(as.numeric(Date_time.x - Date_time.y, unit = "hours"))) %>%
  group_by(Date_time.y) %>%
  filter(diff <= 1 & diff == min(diff)) %>%
  ungroup() %>%
  select(!diff)

Note:

this will still match multiple rows if there’s more than one that are the exact same shortest difference from the index timestamp.

this won’t match timestamps from different dates — eg, 23:59:59 on 1/1/22 won’t be matched with 00:00:00 on 1/2/22. If you’d like to do that, you can use a full Cartesian join (full_join(lv_timest, by = character())) rather than the inner_join() above.


问:
Update timestamps every 30 seconds using setInterval()
I have a list of posts like so:

```<code><ul>
    <li>
       <p class="post" id="432">This is a post</p>
       <p class="timestamp">5 minutes ago</p>
    </li>
    <li>
       <p class="post" id="589">This is another post on the site</p>
       <p class="timestamp">1 hour ago</p>
    </li>
</ul>
</code>```

I want to update the timestamp every 30 seconds (much like facebook timestamps) using setInterval().

```<code>function update_timestamps(){

    $('.timestamp').ajax({
        type    : 'POST',
        url     : '/ajax/refresh_timestamp',
        data    : { 'post_id' : $(this).closest('li').find('p.post').attr('id') },
        success : function(data){
            $(this).html(data);
        }
    });

}

setInterval(update_timestamps(), 30000);
</code>```

Obviously something is wrong with my .ajax() function, or maybe I shouldn't use ajax() at all?

答:
From the fine manual:

context

  This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

So your this in the success callback is, essentially, just the AJAX options. So either specify the right context option to get the this you're expecting or use an explicit selector:

```<code>success : function(data){
    $('.timestamp').html(data);
    setTimeout(update_timestamps, 30000);
}
</code>```

You probably want to add an error callback to restart your timer if there was an error. Or use the complete callback for that:

```<code>success: function(data) {
    $('.timestamp').html(data);
},
complete: function() {
    setTimeout(update_timestamps, 30000);
}
</code>```

Even with all that you still have a problem with .timestamp matching multiple things in your callbacks so you'll need to adjust your whole approach (i.e. id attributes on the .timestamp elements and an id-to-timestamp mapping in the returned data). Or just ditch the AJAX and listen to naveen.

Body:
I have a list of posts like so:

This is a post

5 minutes ago

This is another post on the site

1 hour ago

I want to update the timestamp every 30 seconds (much like facebook timestamps) using setInterval().

function update_timestamps(){

    $('.timestamp').ajax({
        type    : 'POST',
        url     : '/ajax/refresh_timestamp',
        data    : { 'post_id' : $(this).closest('li').find('p.post').attr('id') },
        success : function(data){
            $(this).html(data);
        }
    });

}

setInterval(update_timestamps(), 30000);

Obviously something is wrong with my .ajax() function, or maybe I shouldn't use ajax() at all?

Body:
From the fine manual:

context

  This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).

So your this in the success callback is, essentially, just the AJAX options. So either specify the right context option to get the this you're expecting or use an explicit selector:

success : function(data){
    $('.timestamp').html(data);
    setTimeout(update_timestamps, 30000);
}

You probably want to add an error callback to restart your timer if there was an error. Or use the complete callback for that:

success: function(data) {
    $('.timestamp').html(data);
},
complete: function() {
    setTimeout(update_timestamps, 30000);
}

Even with all that you still have a problem with .timestamp matching multiple things in your callbacks so you'll need to adjust your whole approach (i.e. id attributes on the .timestamp elements and an id-to-timestamp mapping in the returned data). Or just ditch the AJAX and listen to naveen.


问:
Excel formula where certain combinations of cells would return a value
I'm creating a stakeholder map and I have two columns with two possible entries for each

```<code>Power | Interest | Strategy
</code>```

Power and Interest can be either High or Low

So I am trying to get a strategy to return a value based on whether Power or Interest is one of those two combinations as an example:

```<code>Power = High, Interest = High, Strategy = Manage Closely
Power = Low, Interest = High, Strategy = Keep Informed
Power = Low, Interest = Low, Strategy = Monitor
Power = High, Interest = Low, Strategy = Meet Their Needs
</code>```

Can someone help me with this formula?

答:
Make a new column where you concatenate Power and interest.

```<code>  A     B           C            D
1 Power Interest    Concat       Result
2 High  Low         HighLow
3 High  High        HighHigh
</code>```

Then somewhere down in the excel (or in another tab) make a relationship between inputs and outputs

```<code>     A      B           C           D
1000 Power  Interest    Concat      Result
1001 High   High        HighHigh    Manage Closely
1002 High   Low         HighLow     Kep Informed
1003 Low    High        LowHigh     Monitor
1004 Low    Low         LowLow      Meet Their Needs
</code>```

finally use the following formula in the cell D2 and slide it down to all your rows

```<code>=VLOOKUP(C2,$C$1001:$D$1004,2)
</code>```

Where C is the concatenated column, C1001:D1004 is the relationship table location.

You can then hide the column C if you wish.

Body:
I'm creating a stakeholder map and I have two columns with two possible entries for each

Power | Interest | Strategy

Power and Interest can be either High or Low

So I am trying to get a strategy to return a value based on whether Power or Interest is one of those two combinations as an example:

Power = High, Interest = High, Strategy = Manage Closely
Power = Low, Interest = High, Strategy = Keep Informed
Power = Low, Interest = Low, Strategy = Monitor
Power = High, Interest = Low, Strategy = Meet Their Needs

Can someone help me with this formula?

Body:
Make a new column where you concatenate Power and interest.

  A     B           C            D
1 Power Interest    Concat       Result
2 High  Low         HighLow
3 High  High        HighHigh

Then somewhere down in the excel (or in another tab) make a relationship between inputs and outputs

     A      B           C           D
1000 Power  Interest    Concat      Result
1001 High   High        HighHigh    Manage Closely
1002 High   Low         HighLow     Kep Informed
1003 Low    High        LowHigh     Monitor
1004 Low    Low         LowLow      Meet Their Needs

finally use the following formula in the cell D2 and slide it down to all your rows

=VLOOKUP(C2,$C$1001:$D$1004,2)

Where C is the concatenated column, C1001:D1004 is the relationship table location.

You can then hide the column C if you wish.


问:
libvips - generate tiles starting from specific zoom level and specific coordinates
I am using windows cli version libvips. I want to generate map tiles for leaflet from image 8000px x 6000px. This image is old map of my town, and I want to display it on my website, but I am stuck on generating tiles.
How to tell libvips to generate tiles from zoom level 10 to 15. With command

```<code>dzsave input.jpg outputdir --layout google
</code>```

I receive tiles from zoom level 0 to 5.

And second question.
How to set bounds of my map? Generated tiles from above command cover the whole world.

答:
The libvips CLI lets you run any save operation (like jpegsave, tiffsave or dzsave) as part of the write step of a command. You select the saver with the filename suffix and you can pass any parameters in square brackets at the end of the filename (be careful not to use any spaces).

So these two commands do the same thing:

```<code>vips jpegsave x.jpg y.jpg --Q 90
vips copy x.jpg x.jpg[Q=90]
</code>```

The copy command will run jpegsave for you (it sees the .jpg suffix) and set Q to 90.

You can select dzsave with the .dz suffix. If your image is 50,000 x 50,000 pixels, you can save just the centre 50% with:

```<code>vips crop my-huge-map.jpg x.dz[layout=google] 12500 12500 25000 25000
</code>```

I'm not sure what you mean by "layers 10 to 15". Do you only want the low-res layers? Just do a shrink by eg. 16 before running dzsave.

Body:
I am using windows cli version libvips. I want to generate map tiles for leaflet from image 8000px x 6000px. This image is old map of my town, and I want to display it on my website, but I am stuck on generating tiles.
How to tell libvips to generate tiles from zoom level 10 to 15. With command

dzsave input.jpg outputdir --layout google

I receive tiles from zoom level 0 to 5.

And second question.
How to set bounds of my map? Generated tiles from above command cover the whole world.

Body:
The libvips CLI lets you run any save operation (like jpegsave, tiffsave or dzsave) as part of the write step of a command. You select the saver with the filename suffix and you can pass any parameters in square brackets at the end of the filename (be careful not to use any spaces).

So these two commands do the same thing:

vips jpegsave x.jpg y.jpg --Q 90
vips copy x.jpg x.jpg[Q=90]

The copy command will run jpegsave for you (it sees the .jpg suffix) and set Q to 90.

You can select dzsave with the .dz suffix. If your image is 50,000 x 50,000 pixels, you can save just the centre 50% with:

vips crop my-huge-map.jpg x.dz[layout=google] 12500 12500 25000 25000

I'm not sure what you mean by "layers 10 to 15". Do you only want the low-res layers? Just do a shrink by eg. 16 before running dzsave.


问:
Giving Error : Attempting to change the getter of an unconfigurable property in React native
I am working on the project in react-native but this is throwing an error

Attempting to change the getter of an unconfigurable property

```<code>import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import 'react-native-gesture-handler';
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
import LogInScreen from './screens/loginScreen';
import SignUpScreen from './screens/singupScreen';
import ActivitiesScreen from './screens/activitiesScreen';
import StackNavigator from './navigation/WelcomeStackNavigation';
import StackNavigator2 from './navigation/Stack2';
import { AppLoading } from 'expo';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';

function App() {
  return (
    <NavigationContainer>

    </NavigationContainer>
  );
}

export default App;
</code>```

When you remove the code snippet which is 'import { createAppContainer, createSwitchNavigator } from 'react-navigation';'
Then, the error will not show.
If you insert that again the error will be showing.

You can check the package.json file:

```<code>{
  "dependencies": {
    "firebase": "7.9.0",
    "react-is": "^16.8.0",
    "expo-font": "~8.4.0",
    "@firebase/app": "0.x.0",
    "styled-system": "*",
    "react-native-svg": "12.1.0",
    "react-navigation": "4.4.1",
    "styled-components": "*",
    "@firebase/app-types": "0.x.0",
    "@firebase/firestore": "*",
    "react-native-screens": "~2.15.2",
    "@react-navigation/stack": "^5.14.4",
    "react-native-reanimated": "~1.13.0",
    "@react-navigation/native": "^5.9.4",
    "react-native-size-matters": "*",
    "react-native-gesture-handler": "~1.8.0",
    "react-native-safe-area-context": "3.1.9",
    "react-native-floating-label-input": "*",
    "@react-native-community/masked-view": "0.1.10"
  }
}
</code>```

I am confused.

You can check this snack

答: I was getting same error. I just changed to expo version 43 on snack and then extracted the file on VSC, and it worked.</p>

Body:
I am working on the project in react-native but this is throwing an error

Attempting to change the getter of an unconfigurable property

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import 'react-native-gesture-handler';
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
import LogInScreen from './screens/loginScreen';
import SignUpScreen from './screens/singupScreen';
import ActivitiesScreen from './screens/activitiesScreen';
import StackNavigator from './navigation/WelcomeStackNavigation';
import StackNavigator2 from './navigation/Stack2';
import { AppLoading } from 'expo';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';

function App() {
  return (
    <NavigationContainer>

    </NavigationContainer>
  );
}

export default App;

When you remove the code snippet which is 'import { createAppContainer, createSwitchNavigator } from 'react-navigation';'
Then, the error will not show.
If you insert that again the error will be showing.

You can check the package.json file:

{
  "dependencies": {
    "firebase": "7.9.0",
    "react-is": "^16.8.0",
    "expo-font": "~8.4.0",
    "@firebase/app": "0.x.0",
    "styled-system": "*",
    "react-native-svg": "12.1.0",
    "react-navigation": "4.4.1",
    "styled-components": "*",
    "@firebase/app-types": "0.x.0",
    "@firebase/firestore": "*",
    "react-native-screens": "~2.15.2",
    "@react-navigation/stack": "^5.14.4",
    "react-native-reanimated": "~1.13.0",
    "@react-navigation/native": "^5.9.4",
    "react-native-size-matters": "*",
    "react-native-gesture-handler": "~1.8.0",
    "react-native-safe-area-context": "3.1.9",
    "react-native-floating-label-input": "*",
    "@react-native-community/masked-view": "0.1.10"
  }
}

I am confused.

You can check this snack


问:
Add multiple primary keys to a table
I have a table with a primary key available; I want to add another one in primary but can't add it.

SRNO
TRNDATE
RATE
AMT

1
08-02-2022
120
120

2
09-02-2022
170
170

3
10-02-2022
180
180

I want to add column Trndate to the primary key.

When I was try to add in primary following code

```<code>ALTER TABLE dbo.avgEnt
ADD CONSTRAINT PK_avgent PRIMARY KEY NONCLUSTERED (srno, trndate);
</code>```

I get an error:

Msg 1779, Level 16, State 0, Line 1

Table 'avgEnt' already has a primary key defined on it.

Msg 1750, Level 16, State 0, Line 1

Could not create constraint or index. See previous errors.

When I open the design of table and add primary key (SRNO, TRNDATE) then it works fine.

When I was trying to add by using the query, it does not work.

What happened when design windows save that time script i want.

My database version is SQL Server 2014.

答:
A table cannot have multiple PRIMARY KEYs, this is simply not allowed, there is not work around. It is by design.

A table can, however, have multiple UNIQUE INDEXes or UNIQUE CONSTRAINTs. These are not the same as a PRIMARY KEY but do offer similar functionality, and may well provide the solution you need. A column (or set of columns) that are part of a UNIQUE INDEX can also be the target of a FOREIGN KEY, which if your "need" for a second PRIMARY KEY is so you can use it as a FOREIGN KEY then this would also fulfil that requirement.

As an example, you might have something like this:

CREATE TABLE dbo.PrimaryTable (ID int IDENTITY,
                               SomeValue varchar(10) NULL,
                               AnotherIdentifier uniqueidentifier NOT NULL
                               CONSTRAINT PK_PrimaryTable PRIMARY KEY (ID));

CREATE UNIQUE INDEX UQ_PrimaryTable_AnotherIdentifier ON dbo.PrimaryTable (AnotherIdentifier);
GO

CREATE TABLE dbo.SecondaryTable (ID int IDENTITY,
                                 PrimaryID int NOT NULL,
                                 AnotherValue decimal(12,2) NOT NULL,
                                 CONSTRAINT PK_SecondaryTable PRIMARY KEY (ID),
                                 CONSTRAINT FK_SecondaryTable_PrimaryTable FOREIGN KEY (PrimaryID) REFERENCES dbo.PrimaryTable (ID));
GO

CREATE TABLE dbo.AnotherTable (ID int IDENTITY,
                               AnotherID uniqueidentifier NOT NULL,
                               OtherValue int NOT NULL,
                               CONSTRAINT PK_AnotherTable PRIMARY KEY (ID),
                               CONSTRAINT FK_SecondaryTable_PrimaryTable_AnotherIdentifier FOREIGN KEY (AnotherID) REFERENCES dbo.PrimaryTable (AnotherIdentifier));
GO
```
<p>So here you can see that <code>dbo.SecondaryTable</code> uses the <code>ID</code> column of <code>dbo.PrimaryTable</code> as it's <code>FOREIGN KEY</code>, however, <code>dbo.AnotherTable</code> uses the column <code>AnotherIdentifier</code> even though it isn't the <code>PRIMARY KEY</code>. This is because the column has a <code>UNIQUE INDEX</code> on it, meaning that data integrity can be maintained.</p>
<p>Otherwise, as I mentioned in the comments, you could split the table into 2 tables, and then have a 3rd table with a composite key to manage the relationship. So using the <code>dbo.PrimaryTable</code> you might have something like this:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE dbo.PrimaryTable (ID int IDENTITY,
                               SomeValue varchar(10) NULL,
                               CONSTRAINT PK_PrimaryTable PRIMARY KEY (ID));

CREATE TABLE dbo.AnotherPrimaryTable (AnotherIdentifier uniqueidentifier NOT NULL,
                                      CONSTRAINT PK_AnotherPrimaryTable PRIMARY KEY (AnotherIdentifier));
GO
CREATE TABLE dbo.PrimaryTableLink (ID int NOT NULL,
                                   AnotherIdentifier uniqueidentifier NOT NULL,
                                   CONSTRAINT PK_PrimaryTableLink PRIMARY KEY (ID,AnotherIdentifier),
                                   CONSTRAINT FK_PrimaryTableLink_PrimaryTable FOREIGN KEY (ID) REFERENCES dbo.PrimaryTable (ID),
                                   CONSTRAINT FK_PrimaryTableLink_AnotherPrimaryTable FOREIGN KEY (AnotherIdentifier) REFERENCES dbo.AnotherPrimaryTable (AnotherIdentifier));
</code>```

Which you use is up to you. It more depends on your design and requirements. I would likely only use the latter if you needed a many to many relationship, as with a one to one the UNIQUE INDEX serves the goal fine. If you wanted to use the multiple table solution for a one to one relationship, you'd likely need to also add UNIQUE INDEXes to the ID and AnotherIdentifier columns on dbo.PrimaryTableLink, which poses the question of why didn't you create said INDEX on the original column in dbo.PrimaryTable first?

Title: Add multiple primary keys to a table

Body:
I have a table with a primary key available; I want to add another one in primary but can't add it.

SRNO
TRNDATE
RATE
AMT

1
08-02-2022
120
120

2
09-02-2022
170
170

3
10-02-2022
180
180

I want to add column Trndate to the primary key.

When I was try to add in primary following code

ALTER TABLE dbo.avgEnt
ADD CONSTRAINT PK_avgent PRIMARY KEY NONCLUSTERED (srno, trndate);

I get an error:

Msg 1779, Level 16, State 0, Line 1

Table 'avgEnt' already has a primary key defined on it.

Msg 1750, Level 16, State 0, Line 1

Could not create constraint or index. See previous errors.

When I open the design of table and add primary key (SRNO, TRNDATE) then it works fine.

When I was trying to add by using the query, it does not work.

What happened when design windows save that time script i want.

My database version is SQL Server 2014.

Body:
A table cannot have multiple PRIMARY KEYs, this is simply not allowed, there is not work around. It is by design.

A table can, however, have multiple UNIQUE INDEXes or UNIQUE CONSTRAINTs. These are not the same as a PRIMARY KEY but do offer similar functionality, and may well provide the solution you need. A column (or set of columns) that are part of a UNIQUE INDEX can also be the target of a FOREIGN KEY, which if your "need" for a second PRIMARY KEY is so you can use it as a FOREIGN KEY then this would also fulfil that requirement.

As an example, you might have something like this:

CREATE TABLE dbo.PrimaryTable (ID int IDENTITY,
                               SomeValue varchar(10) NULL,
                               AnotherIdentifier uniqueidentifier NOT NULL
                               CONSTRAINT PK_PrimaryTable PRIMARY KEY (ID));

CREATE UNIQUE INDEX UQ_PrimaryTable_AnotherIdentifier ON dbo.PrimaryTable (AnotherIdentifier);
GO

CREATE TABLE dbo.SecondaryTable (ID int IDENTITY,
                                 PrimaryID int NOT NULL,
                                 AnotherValue decimal(12,2) NOT NULL,
                                 CONSTRAINT PK_SecondaryTable PRIMARY KEY (ID),
                                 CONSTRAINT FK_SecondaryTable_PrimaryTable FOREIGN KEY (PrimaryID) REFERENCES dbo.PrimaryTable (ID));
GO

CREATE TABLE dbo.AnotherTable (ID int IDENTITY,
                               AnotherID uniqueidentifier NOT NULL,
                               OtherValue int NOT NULL,
                               CONSTRAINT PK_AnotherTable PRIMARY KEY (ID),
                               CONSTRAINT FK_SecondaryTable_PrimaryTable_AnotherIdentifier FOREIGN KEY (AnotherID) REFERENCES dbo.PrimaryTable (AnotherIdentifier));
GO

So here you can see that dbo.SecondaryTable uses the ID column of dbo.PrimaryTable as it's FOREIGN KEY, however, dbo.AnotherTable uses the column AnotherIdentifier even though it isn't the PRIMARY KEY. This is because the column has a UNIQUE INDEX on it, meaning that data integrity can be maintained.

Otherwise, as I mentioned in the comments, you could split the table into 2 tables, and then have a 3rd table with a composite key to manage the relationship. So using the dbo.PrimaryTable you might have something like this:

CREATE TABLE dbo.PrimaryTable (ID int IDENTITY,
                               SomeValue varchar(10) NULL,
                               CONSTRAINT PK_PrimaryTable PRIMARY KEY (ID));

CREATE TABLE dbo.AnotherPrimaryTable (AnotherIdentifier uniqueidentifier NOT NULL,
                                      CONSTRAINT PK_AnotherPrimaryTable PRIMARY KEY (AnotherIdentifier));
GO
CREATE TABLE dbo.PrimaryTableLink (ID int NOT NULL,
                                   AnotherIdentifier uniqueidentifier NOT NULL,
                                   CONSTRAINT PK_PrimaryTableLink PRIMARY KEY (ID,AnotherIdentifier),
                                   CONSTRAINT FK_PrimaryTableLink_PrimaryTable FOREIGN KEY (ID) REFERENCES dbo.PrimaryTable (ID),
                                   CONSTRAINT FK_PrimaryTableLink_AnotherPrimaryTable FOREIGN KEY (AnotherIdentifier) REFERENCES dbo.AnotherPrimaryTable (AnotherIdentifier));

Which you use is up to you. It more depends on your design and requirements. I would likely only use the latter if you needed a many to many relationship, as with a one to one the UNIQUE INDEX serves the goal fine. If you wanted to use the multiple table solution for a one to one relationship, you'd likely need to also add UNIQUE INDEXes to the ID and AnotherIdentifier columns on dbo.PrimaryTableLink, which poses the question of why didn't you create said INDEX on the original column in dbo.PrimaryTable first?


问:
One dimensional array but multiple string
I want to make a multiple string of array but with just a one dimensional array, Is it possible?

```<code>#include <stdio.h>

int main()
{
    char name1[10];
    char name2[10];

    printf("Enter name1: ");
    scanf("%s", name1);

    printf("Enter name2: ");
    scanf("%s", name2);

    printf("\n%s", name1);
    printf("\n%s", name2);

    return 0;
}
</code>```

I just started to learn array and I wanted to try to get multiple input from user and display only specific of the elements.
This is one of the code I tried before but it does not run.

```<code>int main()
{
    char *name[10];

    int i = 1, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("enter day %d: ", i);
        scanf("%s", name[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("\n%s", name[0]);
    printf("\n%s", name[4]);

    return 0;
}
</code>```

答:
The reason your code does not work is the array of pointers char *name[10]; is uninitialized so you pass an invalid address name[i] to scanf().

You can initialize the array explicitly this way:

```<code>#include <stdio.h>

int main() {
    char name0[20], name1[20], name2[20], name3[20], name4[20];
    char name5[20], name6[20], name7[20], name8[20], name9[20];
    char *name[10] = { name0, name1, name2, name3, name4,
                       name5, name6, name7, name8, name9 };
    int i, input;
    printf("How many days a week: ");
    if (scanf("%d", &input) != 1 || input < 1 || input > 10) {
        fprintf(stderr, "invalid input\n");
        return 1;
    }

    for (i = 0; i < input; i++) {
        printf("enter day %d: ", i + 1);
        if (scanf("%19s", name[i]) != 1) {
            fprintf(stderr, "invalid input\n");
            return 1;
        }
    }

    //output wanted
    printf("%s\n", name[0]);
    if (input > 4)
        printf("%s\n", name[4]);

    return 0;
}
</code>```

Alternately, you can use a 2D array:

```<code>#include <stdio.h>

int main() {
    char name[10][20];
    int i, input;
    printf("How many days a week: ");
    if (scanf("%d", &input) != 1 || input < 1 || input > 10) {
        fprintf(stderr, "invalid input\n");
        return 1;
    }

    for (i = 0; i < input; i++) {
        printf("enter day %d: ", i + 1);
        if (scanf("%19s", name[i]) != 1) {
            fprintf(stderr, "invalid input\n");
            return 1;
        }
    }

    //output wanted
    printf("%s\n", name[0]);
    if (input > 4)
        printf("%s\n", name[4]);

    return 0;
}
</code>```

Body:
I want to make a multiple string of array but with just a one dimensional array, Is it possible?

#include <stdio.h>

int main()
{
    char name1[10];
    char name2[10];

    printf("Enter name1: ");
    scanf("%s", name1);

    printf("Enter name2: ");
    scanf("%s", name2);

    printf("\n%s", name1);
    printf("\n%s", name2);

    return 0;
}

I just started to learn array and I wanted to try to get multiple input from user and display only specific of the elements.
This is one of the code I tried before but it does not run.

int main()
{
    char *name[10];

    int i = 1, input;
    printf("How many days a week: ");
    scanf("%d", &input);

    do{
        printf("enter day %d: ", i);
        scanf("%s", name[i]);
        i++;
    }while(i < input);

    //output wanted
    printf("\n%s", name[0]);
    printf("\n%s", name[4]);

    return 0;
}

Body:
The reason your code does not work is the array of pointers char *name[10]; is uninitialized so you pass an invalid address name[i] to scanf().

You can initialize the array explicitly this way:

#include <stdio.h>

int main() {
    char name0[20], name1[20], name2[20], name3[20], name4[20];
    char name5[20], name6[20], name7[20], name8[20], name9[20];
    char *name[10] = { name0, name1, name2, name3, name4,
                       name5, name6, name7, name8, name9 };
    int i, input;
    printf("How many days a week: ");
    if (scanf("%d", &input) != 1 || input < 1 || input > 10) {
        fprintf(stderr, "invalid input\n");
        return 1;
    }

    for (i = 0; i < input; i++) {
        printf("enter day %d: ", i + 1);
        if (scanf("%19s", name[i]) != 1) {
            fprintf(stderr, "invalid input\n");
            return 1;
        }
    }

    //output wanted
    printf("%s\n", name[0]);
    if (input > 4)
        printf("%s\n", name[4]);

    return 0;
}

Alternately, you can use a 2D array:

#include <stdio.h>

int main() {
    char name[10][20];
    int i, input;
    printf("How many days a week: ");
    if (scanf("%d", &input) != 1 || input < 1 || input > 10) {
        fprintf(stderr, "invalid input\n");
        return 1;
    }

    for (i = 0; i < input; i++) {
        printf("enter day %d: ", i + 1);
        if (scanf("%19s", name[i]) != 1) {
            fprintf(stderr, "invalid input\n");
            return 1;
        }
    }

    //output wanted
    printf("%s\n", name[0]);
    if (input > 4)
        printf("%s\n", name[4]);

    return 0;
}


问:
How to test if a valid Method exists when params are involved
I have the following method:

```<code>    public MethodInfo FancyGetMethodInfo
         (object obj, string methodName, Type[] methodSignature)
    {
        return obj.GetType().GetMethod(methodName, methodSignature);
    }
</code>```

and for the sake of an example I have in my object I am passing the two methods

```<code>    public int Subtract(int a, int b) { return a - b; }

    public int Add(params int[] a) { return a.Sum(); }
</code>```

And when I execute the following lines I get these results:

```<code>        var SubMethod = FancyGetMethodInfo(obj, "Subtract",
                         new Type[] { typeof(int), typeof(int) });
        //I get a MethodInfo
        var AddMethod = FancyGetMethodInfo(obj, "Add",
                         new Type[] { typeof(int), typeof(int) });
        //I get a Null reference
</code>```

I'm sure this is because of the params in Add. Is there a clean way to get reference to my MethodInfo for my Add method given an arbitrary sized Type[] containing ints and only having access to the provided variables in my FancyGetMethodInfo method?

Edit:
More eloquently put by Jon Skeet, I want to perform the same binding as the C# compiler does in my method. it needs to work properly with subclasses, implicit casting, arbitrary length params, etc...

Also as requested, a relevant link here is: Determining if a parameter uses "params" using reflection in C#? which will get me as far as knowing that the method has a params.

答:
It's not because of the params (although that may pose an additional issue).

Try instead:
var AddMethod = FancyGetMethodInfo(obj, "Add",
                         new Type[] { typeof(int[]) });

Body:
I have the following method:

    public MethodInfo FancyGetMethodInfo
         (object obj, string methodName, Type[] methodSignature)
    {
        return obj.GetType().GetMethod(methodName, methodSignature);
    }

and for the sake of an example I have in my object I am passing the two methods

    public int Subtract(int a, int b) { return a - b; }

    public int Add(params int[] a) { return a.Sum(); }

And when I execute the following lines I get these results:

        var SubMethod = FancyGetMethodInfo(obj, "Subtract",
                         new Type[] { typeof(int), typeof(int) });
        //I get a MethodInfo
        var AddMethod = FancyGetMethodInfo(obj, "Add",
                         new Type[] { typeof(int), typeof(int) });
        //I get a Null reference

I'm sure this is because of the params in Add. Is there a clean way to get reference to my MethodInfo for my Add method given an arbitrary sized Type[] containing ints and only having access to the provided variables in my FancyGetMethodInfo method?

Edit:
More eloquently put by Jon Skeet, I want to perform the same binding as the C# compiler does in my method. it needs to work properly with subclasses, implicit casting, arbitrary length params, etc...

Also as requested, a relevant link here is: Determining if a parameter uses "params" using reflection in C#? which will get me as far as knowing that the method has a params.