问:
Python win32com - Class not registered error
I'm trying to control a device (Gamry Interface 5000 Potentiostat) via its COM interface using win32com.

# Imports
import win32com.client as client

# Get device list
devices = client.Dispatch('GamryCOM.GamryDeviceList')

# Iterate through devices
for i in range(devices.Count()):
    # Get device (this wors as we only have one connected yet)
    device = devices.EnumSections()[i]
    print(device)

# Setup potentiostat object
potentiostat = client.Dispatch('GamryCOM.GamryPstat')
```
<p>When I run this, I got the following error message:</p>
```IFC5000-10519
Traceback (most recent call last):
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 86, in _GetGoodDispatch
    IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\[...]\gamry_control_01.py", line 23, in <module>
    potentiostat = client.Dispatch('GamryCOM.GamryPstat', clsctx = pythoncom.CLSCTX_LOCAL_SERVER )
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147221164, 'Class not registered', None, None)
```

Funnily enough, the first dispatch-statement just works fine, Just the second one fails.

I'm using a 64 Bit Windows 11 setup and tested different Python environments:

Python 3.10 64 Bit, win32com-303 64 Bit

Python 3.9 32 Bit, win32com-303 32 Bit

I also tried using comtypes instead of win32com which resulted in the same error.

Thank you very much for your help!

Regards

答:
"Class not registered" means it cannot find the class factory for the class. That's an error independent of Python and has nothing to do with it...other than the bitness of Python (whether it is 32 or 64-bit, and whether the COM server is 32 or 64-bit). It also matters whether the server is In Process (a DLL) or Out of Process (EXE). For EXE, it really doesn't matter, but for an In-Process server, the bitness of the calling program and the COM server have to match.  In order to see if you have a bitness problem, do this...

Create the following VB Script, call it test.vbs

```<code>set obj = CreateObject("GamryCOM.GamryDeviceList")
MsgBox TypeName(obj)
</code>```

Call the script two times from the command line, one with the 64-bit VB Script engine, and once with the 32-bit engine. If you're running from a directory other where test.vbs is located, you'll have to supply the path to test.vbs as well.

64-bit engine:

```<code>c:\windows\system32\wscript.exe test.vbs
</code>```

32-bit engine:

```<code>c:\windows\syswow64\wscript.exe test.vbs
</code>```

If the object is correctly registered and an EXE server, it should succeed for the script run both as 32 and 64-bit. If the object is correctly registered and a DLL server, it will succeed for only one run of the above script. If the object is incorrectly registered, it will fail for the script run with both engines.

In the case of double failure, you will have to figure out how the producer of the COM object expects you to call it. It could be licensing is involved.

In the case of single failure, you will have to use a different bitness of Python to match the server, or if you're truly running 64-bit Python as you say, then maybe figure a way to host the 32-bit DLL in 64-bits using something like DllHost. I've never done it, but there are articles online on how to do it.

Body:
I'm trying to control a device (Gamry Interface 5000 Potentiostat) via its COM interface using win32com.

# Imports
import win32com.client as client

# Get device list
devices = client.Dispatch('GamryCOM.GamryDeviceList')

# Iterate through devices
for i in range(devices.Count()):
    # Get device (this wors as we only have one connected yet)
    device = devices.EnumSections()[i]
    print(device)

# Setup potentiostat object
potentiostat = client.Dispatch('GamryCOM.GamryPstat')

When I run this, I got the following error message:

IFC5000-10519
Traceback (most recent call last):
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 86, in _GetGoodDispatch
    IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221021, 'Operation unavailable', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:\Users\[...]\gamry_control_01.py", line 23, in <module>
    potentiostat = client.Dispatch('GamryCOM.GamryPstat', clsctx = pythoncom.CLSCTX_LOCAL_SERVER )
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\__init__.py", line 117, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch, userName, clsctx)
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 106, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "c:\Users\Rob\AppData\Local\Programs\Python\Python39-32\lib\site-packages\win32com\client\dynamic.py", line 88, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(
pywintypes.com_error: (-2147221164, 'Class not registered', None, None)

Funnily enough, the first dispatch-statement just works fine, Just the second one fails.

I'm using a 64 Bit Windows 11 setup and tested different Python environments:

Python 3.10 64 Bit, win32com-303 64 Bit

Python 3.9 32 Bit, win32com-303 32 Bit

I also tried using comtypes instead of win32com which resulted in the same error.

Thank you very much for your help!

Regards

Body:
"Class not registered" means it cannot find the class factory for the class. That's an error independent of Python and has nothing to do with it...other than the bitness of Python (whether it is 32 or 64-bit, and whether the COM server is 32 or 64-bit). It also matters whether the server is In Process (a DLL) or Out of Process (EXE). For EXE, it really doesn't matter, but for an In-Process server, the bitness of the calling program and the COM server have to match.  In order to see if you have a bitness problem, do this...

Create the following VB Script, call it test.vbs

set obj = CreateObject("GamryCOM.GamryDeviceList")
MsgBox TypeName(obj)

Call the script two times from the command line, one with the 64-bit VB Script engine, and once with the 32-bit engine. If you're running from a directory other where test.vbs is located, you'll have to supply the path to test.vbs as well.

64-bit engine:

c:\windows\system32\wscript.exe test.vbs

32-bit engine:

c:\windows\syswow64\wscript.exe test.vbs

If the object is correctly registered and an EXE server, it should succeed for the script run both as 32 and 64-bit. If the object is correctly registered and a DLL server, it will succeed for only one run of the above script. If the object is incorrectly registered, it will fail for the script run with both engines.

In the case of double failure, you will have to figure out how the producer of the COM object expects you to call it. It could be licensing is involved.

In the case of single failure, you will have to use a different bitness of Python to match the server, or if you're truly running 64-bit Python as you say, then maybe figure a way to host the 32-bit DLL in 64-bits using something like DllHost. I've never done it, but there are articles online on how to do it.


来源: stackexchange

问:
typeorm leftJoinAndSelect fail with camel case foreign key generated
Hello I posted an issue related to typeorm, node.js and joins on github but nobody has responded me so far, so I'm just curious if anyone can help me here. I would be so grateful, because I tried everything and nothing has worked.

Basically everything works fine for me, I love the library because it's super powerful, but when it comes to joins it generates camel case foreign key name because originally it's driver_id and when I check the generated sql query the output contains driverId which I don't want and obviously it doesn't work. I don't see any error in my code, so maybe someone could spot one.

Here's the submitted issue on github and everything is explained there: github typeorm issue

答:
you should use @JoinColumn() decorator

change TripDriversEntity class like this

@ManyToOne(() => DriverEntity, (driver: DriverEntity) => driver.trips)
@JoinColumn({name: OPTIONAL})
driver: DriverEntity

```

ContentLicense: CC BY-SA 4.0


问:
Fancy box with carousel/sliding
I have a problem facing related fancy box. I want to achieve UI: images in fancybox with carousel option to slide the items.

Here is the UI i need to achieve:

here is my code:

  <link rel="stylesheet" type="text/css" href="jquery.fancybox.min.css">
  <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css'>

```

Can somebody help me to sort out this problem. Thank you. If you have any question let me know.

答:
You can put multiple elements inside carousel slide element. Then, for example, use CSS to create two columns. Example using Tailwind CSS and Carousel 4:</p>
```<code><div class="carousel__slide grid grid-cols-2 gap-4">
  <a href="https://lipsum.app/id/1/900x600" data-fancybox="gallery">
    <img src="https://lipsum.app/id/1/600x400" />
  </a>
  <a href="https://lipsum.app/id/2/900x600" data-fancybox="gallery">
    <img src="https://lipsum.app/id/2/600x400" />
  </a>
</div>
</code>```

Title: Fancy box with carousel/sliding

Body:
I have a problem facing related fancy box. I want to achieve UI: images in fancybox with carousel option to slide the items.

Here is the UI i need to achieve:

here is my code:

  <link rel="stylesheet" type="text/css" href="jquery.fancybox.min.css">
  <link rel='stylesheet' href='https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css'>

Can somebody help me to sort out this problem. Thank you. If you have any question let me know.

Body:
You can put multiple elements inside carousel slide element. Then, for example, use CSS to create two columns. Example using Tailwind CSS and Carousel 4:

<div class="carousel__slide grid grid-cols-2 gap-4">
  <a href="https://lipsum.app/id/1/900x600" data-fancybox="gallery">
    <img src="https://lipsum.app/id/1/600x400" />
  </a>
  <a href="https://lipsum.app/id/2/900x600" data-fancybox="gallery">
    <img src="https://lipsum.app/id/2/600x400" />
  </a>
</div>


问:
Does Firebase Firestore keep a local copy of snapshot
I am using firebase firestore for my chat room application.

I have a function to send messages to firebase as

```<code>const sendMessageHandler = message => {
  if (message) {
    firestore()
      .collection(`ChatRooms/${roomId}/messages`)
      .doc(moment().format('YYYY-MM-DD-HH-mm-sssss'))
      .set({
        message: Encrypt(message),
        userId: userId,
      });
  }
};
</code>```

and I am fetching messages into flatlist only from firestore as

```<code>// this messages const is getting data only from firestore
const [messages, setMessage] = useState([]);

firestore()
  .collection(`ChatRooms/${roomId}/messages`)
  .onSnapshot(
    querySnapshot => {
      const messages = [];
      querySnapshot.forEach(dataSnapshot => {
        messages.push({
          id: dataSnapshot.id,
          message: dataSnapshot.data().message,
          userId: dataSnapshot.data().userId,
        });
      });
      setMessage(messages.reverse());
      setLoading(false);
    },
    error => {
      console.log('error : ', error);
    },
  );

// And now I am using this messages somewhere in return function of a component as :

<FlatList
  data={messages}
  renderItem={flatListItemRenderer}
  inverted={true}
/>
</code>```

Notice I am fetching only from firestore and not locally.

Now I turned off the internet and tried sending messages so this happens

The data has not been updated to firestore (of course because of no internet), but the flatlist has been updated with the new message !!

The only possibility I can think of is that the setter methods of firestore is storing data in both local and remote database and the getter method is first getting snapshot from local database and then remote database.

So the question is does @react-native-firebase/firestore keep a local snapshot also and updates both local and remote snapshot of data whenever we change something?

Github Link

Edit :

Firestore docs says
Firestore provides out of the box support for offline capabilities. When reading and writing data, Firestore uses a local database which synchronizes automatically with the server.This functionality is enabled by default, however it can be disabled if you need it to be disabled

I tried turning off persistence, but this property is related to storing data offline not the state. i.e, now when my app loads it fetch all the data directly from server(previously fetching from storage and server both), but the flatlist still updates with the new message(maybe it is storing some state like useState also???)

答:
The Firestore SDK keeps a local copy of:

All data that you have an active listener for.

All pending writes.

In addition, if offline persistence is enabled, it also keeps a local copy of data that your code has recently read.

When you make a write operation, the SDK:

Writes your operation to its queue of pending writes.

Fires an event for any local listeners.

Tries to synchronize the pending write with the server.

Steps 1 and 2 always happen, regardless of whether you are online or offline. Only step 3 won't complete immediately when you are offline.

Body:
I am using firebase firestore for my chat room application.

I have a function to send messages to firebase as

const sendMessageHandler = message => {
  if (message) {
    firestore()
      .collection(`ChatRooms/${roomId}/messages`)
      .doc(moment().format('YYYY-MM-DD-HH-mm-sssss'))
      .set({
        message: Encrypt(message),
        userId: userId,
      });
  }
};

and I am fetching messages into flatlist only from firestore as

// this messages const is getting data only from firestore
const [messages, setMessage] = useState([]);

firestore()
  .collection(`ChatRooms/${roomId}/messages`)
  .onSnapshot(
    querySnapshot => {
      const messages = [];
      querySnapshot.forEach(dataSnapshot => {
        messages.push({
          id: dataSnapshot.id,
          message: dataSnapshot.data().message,
          userId: dataSnapshot.data().userId,
        });
      });
      setMessage(messages.reverse());
      setLoading(false);
    },
    error => {
      console.log('error : ', error);
    },
  );

// And now I am using this messages somewhere in return function of a component as :

<FlatList
  data={messages}
  renderItem={flatListItemRenderer}
  inverted={true}
/>

Notice I am fetching only from firestore and not locally.

Now I turned off the internet and tried sending messages so this happens

The data has not been updated to firestore (of course because of no internet), but the flatlist has been updated with the new message !!

The only possibility I can think of is that the setter methods of firestore is storing data in both local and remote database and the getter method is first getting snapshot from local database and then remote database.

So the question is does @react-native-firebase/firestore keep a local snapshot also and updates both local and remote snapshot of data whenever we change something?

Github Link

Edit :

Firestore docs says
Firestore provides out of the box support for offline capabilities. When reading and writing data, Firestore uses a local database which synchronizes automatically with the server.This functionality is enabled by default, however it can be disabled if you need it to be disabled

I tried turning off persistence, but this property is related to storing data offline not the state. i.e, now when my app loads it fetch all the data directly from server(previously fetching from storage and server both), but the flatlist still updates with the new message(maybe it is storing some state like useState also???)


问:
How to update a value based on previous value in an array of objects?
I am trying to update every current value based on the previous value of another property.

Actually, I need to do the task with dates, but just to keep it simple, I'll explain my problem with simple numbers.

I have

Start, which is 1

Stop, which is already defined

End

Duration, which is already defined

My goal

Start = Duration of previous index + End of previous index

End = Start + Stop of current value

To illustrate, I added the screenshot of the table, how it should look like:

Current view:

Code below and sandbox link

```<code>import React from "react";
import { AgGridReact } from "ag-grid-react";
import "./styles.css";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
  let start = 1;
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  const defaultColDef = {
    flex: 1,
    editable: true
  };

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
    },
    {
      headerName: "start",
      field: "updatedStart"
    },
    { headerName: "stop", field: "stop" },
    {
      headerName: "end",
      field: "end"
    },
    {
      headerName: "duration",
      field: "duration",
      colId: "duration"
    }
  ];
  const rowData = React.useMemo(
    () => [
      {
        name: "John",
        stop: 10,
        duration: 5
      },
      {
        name: "David",
        stop: 15,
        duration: 8
      },
      {
        name: "Dan",
        stop: 20,
        duration: 6
      }
    ],
    []
  );

  const rowDataWithStart = React.useMemo(() => {
    return (
      rowData &&
      rowData.map((row, i) => ({
        ...row,
        start: start
      }))
    );
  }, [start, rowData]);

  const rowDataWitEnd = React.useMemo(() => {
    return (
      rowDataWithStart &&
      rowDataWithStart.map((row, i) => ({
        ...row,
        end: row.start + row.stop
      }))
    );
  }, [rowDataWithStart]);

//this function(rowDataWitUpdatedStart) should get the previous value of end and duration and get the total
  const rowDataWitUpdatedStart = React.useMemo(() => {
    return (
      rowDataWitEnd &&
      rowDataWitEnd.map((row, i) => ({
        ...row,
        updatedStart: row.end + row.duration
      }))
    );
  }, [rowDataWitEnd]);

  return (
    <div className="App">
      <h1 align="center">React-App</h1>
      <div className="ag-theme-alpine">
        <AgGridReact
          columnDefs={columnDefs}
          rowData={rowDataWitUpdatedStart}
          defaultColDef={defaultColDef}
          domLayout={"autoHeight"}
          onGridReady={onGridReady}
        ></AgGridReact>
      </div>
    </div>
  );
}

export default App;
</code>```

I have tried to do the task making a use of valueGetter from the library I use: AG Grid, but seems to be not the best approach. See my previous question
Any help will be appreciated

答:
I would loop through all elements, keeping a list of processed entries (result) and just add the start and end onto the item.

(Of course the first one is an anomaly as you need to hardcode the start to be at 1)

```<code>    const result = [];
    for (let i = 0; i < rowData.length; i++) {
      const thisValue = rowData[i];
      if (i === 0) {
        const firstValue = { ...thisValue, start: 1, end: 1 + thisValue.stop };
        result.push(firstValue);
      } else {
        const previousValue = result[i - 1];
        const start = previousValue.end + previousValue.duration;
        const end = start + thisValue.stop;
        result.push({ ...thisValue, start, end });
      }
    }

    return result;
  }, [rowData]);
</code>```

You can view this on my forked sandbox

Body:
I am trying to update every current value based on the previous value of another property.

Actually, I need to do the task with dates, but just to keep it simple, I'll explain my problem with simple numbers.

I have

Start, which is 1

Stop, which is already defined

End

Duration, which is already defined

My goal

Start = Duration of previous index + End of previous index

End = Start + Stop of current value

To illustrate, I added the screenshot of the table, how it should look like:

Current view:

Code below and sandbox link

import React from "react";
import { AgGridReact } from "ag-grid-react";
import "./styles.css";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
  let start = 1;
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  const defaultColDef = {
    flex: 1,
    editable: true
  };

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
    },
    {
      headerName: "start",
      field: "updatedStart"
    },
    { headerName: "stop", field: "stop" },
    {
      headerName: "end",
      field: "end"
    },
    {
      headerName: "duration",
      field: "duration",
      colId: "duration"
    }
  ];
  const rowData = React.useMemo(
    () => [
      {
        name: "John",
        stop: 10,
        duration: 5
      },
      {
        name: "David",
        stop: 15,
        duration: 8
      },
      {
        name: "Dan",
        stop: 20,
        duration: 6
      }
    ],
    []
  );

  const rowDataWithStart = React.useMemo(() => {
    return (
      rowData &&
      rowData.map((row, i) => ({
        ...row,
        start: start
      }))
    );
  }, [start, rowData]);

  const rowDataWitEnd = React.useMemo(() => {
    return (
      rowDataWithStart &&
      rowDataWithStart.map((row, i) => ({
        ...row,
        end: row.start + row.stop
      }))
    );
  }, [rowDataWithStart]);

//this function(rowDataWitUpdatedStart) should get the previous value of end and duration and get the total
  const rowDataWitUpdatedStart = React.useMemo(() => {
    return (
      rowDataWitEnd &&
      rowDataWitEnd.map((row, i) => ({
        ...row,
        updatedStart: row.end + row.duration
      }))
    );
  }, [rowDataWitEnd]);

  return (

React-App

        <AgGridReact
          columnDefs={columnDefs}
          rowData={rowDataWitUpdatedStart}
          defaultColDef={defaultColDef}
          domLayout={"autoHeight"}
          onGridReady={onGridReady}
        ></AgGridReact>

  );
}

export default App;

I have tried to do the task making a use of valueGetter from the library I use: AG Grid, but seems to be not the best approach. See my previous question
Any help will be appreciated

Body:
I would loop through all elements, keeping a list of processed entries (result) and just add the start and end onto the item.

(Of course the first one is an anomaly as you need to hardcode the start to be at 1)

    const result = [];
    for (let i = 0; i < rowData.length; i++) {
      const thisValue = rowData[i];
      if (i === 0) {
        const firstValue = { ...thisValue, start: 1, end: 1 + thisValue.stop };
        result.push(firstValue);
      } else {
        const previousValue = result[i - 1];
        const start = previousValue.end + previousValue.duration;
        const end = start + thisValue.stop;
        result.push({ ...thisValue, start, end });
      }
    }

    return result;
  }, [rowData]);

You can view this on my forked sandbox


问:
C++ Win32 Padding zeros to an int via to_wstring
I am trying to learn C++ Win32. I built a timer class for a game environment. Typical game timer and it works well. I have this function that I would like to display the current game time with.

std::wstring Time::DisplayGameTime()
{
    std::wstring Label = L"Current Time: ";

    std::wstring daysText = L" " + std::to_wstring(Days()); //Returns int
    std::wstring monthsText = L", " + std::to_wstring(Months()); //Returns int
    std::wstring yearsText = L", " + std::to_wstring(Years()); // Returns int
    std::wstring hoursText = L" " + std::to_wstring(Hours()); // Returns int
    std::wstring minutesText = L" : " + std::to_wstring(Minutes()); // Returns int

    std::wstring message = Label + daysText + monthsText + yearsText + hoursText + minutesText;
    return message;
}
```

This works well too, except the minutes integer only prints one digit until it reaches 10. I would like to pad a leading zero to it like you would find in a normal time clock. Since I am using std::to_wstring, I cannot use format specifiers like in a swprintf_s buffer. I have tried to figure out how to use a wstringstream for this but none of what I've tried has worked.

The goal is to use this function to convert to LPCWSTR later on for DrawText to display to the Window.

答:
You can use the traditional imperative "brute-force" way of solving this:

int DaysVal = Days();
std::wstring W = (DaysVal < 10 ? L"0" : L"") + std::to_wstring(DaysVal);
```
<p>Or.. use <code>std::stringstream</code> with <code>std::setw</code> and <code>std::setfill</code> (from <code><iomanip></code>).</p>
<pre class="lang-cpp prettyprint-override"><code>std::wstringstream WS;
WS << std::setw(2) << std::setfill(L'0') << Days();
std::wstring W = WS.str();
</code>```

PS: Features from <iomanip> also work on std::cout and other streams, so  std::(w)stringstream is unnecessary with I/O!

EDIT: And if someone's looking for a solution utilizing snprintf():

char CB[128];
std::snprintf(CB, sizeof(CB), "%.*i", NumDigits, Num);
```
<p>Using precision (<code>%.*i</code>) is superior to using width (<code>%*i</code>), since the second one operates on total of characters and not number of digits!</p>
<p>EDIT(2): To be future-proof, I'm also including a solution using <code>std::format()</code>:</p>
<p>I haven't played with {fmt} for too long, so I have no idea how to achieve the same result as with <code>printf()</code>. For now, it should suffice (but expect to have one digit less with negative numbers):</p>
<pre class="lang-cpp prettyprint-override"><code>std::wstring W = fmt::format(L"{:+0{}}", Num, NumDigits);
</code>```

Body:
I am trying to learn C++ Win32. I built a timer class for a game environment. Typical game timer and it works well. I have this function that I would like to display the current game time with.

std::wstring Time::DisplayGameTime()
{
    std::wstring Label = L"Current Time: ";

    std::wstring daysText = L" " + std::to_wstring(Days()); //Returns int
    std::wstring monthsText = L", " + std::to_wstring(Months()); //Returns int
    std::wstring yearsText = L", " + std::to_wstring(Years()); // Returns int
    std::wstring hoursText = L" " + std::to_wstring(Hours()); // Returns int
    std::wstring minutesText = L" : " + std::to_wstring(Minutes()); // Returns int

    std::wstring message = Label + daysText + monthsText + yearsText + hoursText + minutesText;
    return message;
}

This works well too, except the minutes integer only prints one digit until it reaches 10. I would like to pad a leading zero to it like you would find in a normal time clock. Since I am using std::to_wstring, I cannot use format specifiers like in a swprintf_s buffer. I have tried to figure out how to use a wstringstream for this but none of what I've tried has worked.

The goal is to use this function to convert to LPCWSTR later on for DrawText to display to the Window.

Body:
You can use the traditional imperative "brute-force" way of solving this:

int DaysVal = Days();
std::wstring W = (DaysVal < 10 ? L"0" : L"") + std::to_wstring(DaysVal);

Or.. use std::stringstream with std::setw and std::setfill (from <iomanip>).

std::wstringstream WS;
WS << std::setw(2) << std::setfill(L'0') << Days();
std::wstring W = WS.str();

PS: Features from <iomanip> also work on std::cout and other streams, so  std::(w)stringstream is unnecessary with I/O!

EDIT: And if someone's looking for a solution utilizing snprintf():

char CB[128];
std::snprintf(CB, sizeof(CB), "%.*i", NumDigits, Num);

Using precision (%.*i) is superior to using width (%*i), since the second one operates on total of characters and not number of digits!

EDIT(2): To be future-proof, I'm also including a solution using std::format():

I haven't played with {fmt} for too long, so I have no idea how to achieve the same result as with printf(). For now, it should suffice (but expect to have one digit less with negative numbers):

std::wstring W = fmt::format(L"{:+0{}}", Num, NumDigits);


问:
Want to send images using gifted chat with messages, and store them to firebase and fetch them back , and show in the chat
I want to send images with messages using gifted chat ,
Here is my code:

```<code>// for send message

const onSend =(messageArray) => {

    const msg = messageArray[0]
    const mymsg = {
        ...msg,
        sentBy:user.uid,
        sentTo:uid,
        createdAt:new Date()
    }
    setMessages(previousMessages => GiftedChat.append(previousMessages,mymsg))
    const docid  = uid > user.uid ? user.uid+ "-" + uid : uid+"-"+user.uid

    firestore().collection('chatrooms')
        .doc(docid)
        .collection('messages')
        .add({...mymsg,createdAt:firestore.FieldValue.serverTimestamp()})
}
</code>```

from here am sending messages and store them to firebase and showing fetching them back from firebase.

```<code>// display code

<GiftedChat
    messages={messages}
    onSend={text => onSend(text)}

    user={{
        _id: user.uid,
    }}

    alwaysShowSend
    placeholder='Message'
    renderSend={renderSend}
    renderBubble={(props)=>{
        return <Bubble
            {...props}
            wrapperStyle={{
                right: {
                    backgroundColor:"#efc100",
                },
                left:{
                    marginLeft: -40
                }
            }}
        />
    }}
</code>```

thanks in advance

答:
Let's split the problem into small subproblems.

Get image from media library

const pickImageasync = async () => {
 const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();

 let imgURI = null;
 const hasStoragePermissionGranted = status === "granted";

if(!hasStoragePermissionGranted) return null;

 let result = await ImagePicker.launchImageLibraryAsync({
   mediaTypes: ImagePicker.MediaTypeOptions.Images,
   allowsEditing: true,
   aspect: [4, 4],
   quality: 1,
 });

 if (!result.cancelled) {
   imgURI = result.uri;
 }

 return imgURI;
};

```
<ol start="2">
<li>Upload an image to Firebase Storage</li>
</ol>
<pre class="lang-js prettyprint-override"><code>const uploadImageToStorage= async (imgURI ) => {
  const ref = `messages/${[FILE_REFERENCE_HERE]}`

  const imgRef = firebase.storage().ref(ref);

  const metadata = { contentType: "image/jpg" };

  // Fetch image data as BLOB from device file manager

  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function (e) {
      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", imgURI, true);
    xhr.send(null);
  });

  // Put image Blob data to firebase servers
  await imgRef.put(blob, metadata);

  // We're done with the blob, close and release it
  blob.close();

  // Image permanent URL
  const url = await imgRef.getDownloadURL();

  return url
};

</code>```

Update message document with image permanent URI

const  localImgURI = "file://path_to_file" // Replace with real path of uploaded image
const imgPermanentURL = await uploadImageToStorage(localImgURI)
 firestore().collection('chatrooms')
    .doc(docid)
    .collection('messages')
    .doc(messageId).update({image:imgPermanentURL})

```

Body:
I want to send images with messages using gifted chat ,
Here is my code:

// for send message

const onSend =(messageArray) => {

    const msg = messageArray[0]
    const mymsg = {
        ...msg,
        sentBy:user.uid,
        sentTo:uid,
        createdAt:new Date()
    }
    setMessages(previousMessages => GiftedChat.append(previousMessages,mymsg))
    const docid  = uid > user.uid ? user.uid+ "-" + uid : uid+"-"+user.uid

    firestore().collection('chatrooms')
        .doc(docid)
        .collection('messages')
        .add({...mymsg,createdAt:firestore.FieldValue.serverTimestamp()})
}

from here am sending messages and store them to firebase and showing fetching them back from firebase.

// display code

<GiftedChat
    messages={messages}
    onSend={text => onSend(text)}

    user={{
        _id: user.uid,
    }}

    alwaysShowSend
    placeholder='Message'
    renderSend={renderSend}
    renderBubble={(props)=>{
        return <Bubble
            {...props}
            wrapperStyle={{
                right: {
                    backgroundColor:"#efc100",
                },
                left:{
                    marginLeft: -40
                }
            }}
        />
    }}

thanks in advance

Body:
Let's split the problem into small subproblems.

Get image from media library

const pickImageasync = async () => {
 const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();

 let imgURI = null;
 const hasStoragePermissionGranted = status === "granted";

if(!hasStoragePermissionGranted) return null;

 let result = await ImagePicker.launchImageLibraryAsync({
   mediaTypes: ImagePicker.MediaTypeOptions.Images,
   allowsEditing: true,
   aspect: [4, 4],
   quality: 1,
 });

 if (!result.cancelled) {
   imgURI = result.uri;
 }

 return imgURI;
};

Upload an image to Firebase Storage

const uploadImageToStorage= async (imgURI ) => {
  const ref = `messages/${[FILE_REFERENCE_HERE]}`

  const imgRef = firebase.storage().ref(ref);

  const metadata = { contentType: "image/jpg" };

  // Fetch image data as BLOB from device file manager

  const blob = await new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.onload = function () {
      resolve(xhr.response);
    };
    xhr.onerror = function (e) {
      reject(new TypeError("Network request failed"));
    };
    xhr.responseType = "blob";
    xhr.open("GET", imgURI, true);
    xhr.send(null);
  });

  // Put image Blob data to firebase servers
  await imgRef.put(blob, metadata);

  // We're done with the blob, close and release it
  blob.close();

  // Image permanent URL
  const url = await imgRef.getDownloadURL();

  return url
};

Update message document with image permanent URI

const  localImgURI = "file://path_to_file" // Replace with real path of uploaded image
const imgPermanentURL = await uploadImageToStorage(localImgURI)
 firestore().collection('chatrooms')
    .doc(docid)
    .collection('messages')
    .doc(messageId).update({image:imgPermanentURL})


问:
Easy way to iterate through multiple std::vectors in C++
I have two std::vectors of same type, and I need to iterate through both of them using the same routine. Something like this:

```<code>std::vector<int> values1, values2;
int counter = 0;
for (int val : values1) counter += val;
for (int val : values2) counter += val;
</code>```

Is there any simple way to write the last two lines in a single loop, to avoid code repetition? Something that would look like this:

```<code>std::vector<int> values1, values2;
int counter = 0;
for (int val : values1, values2) counter += val;
</code>```

答:
I used something like this to iterate through 3 different vectors of different size where one vector was dependent of the two other vectors (first_vector is dependent on the other vectors).</p>
```<code>#include <iostream>
#include <vector>
int main() {
  std::vector<int> first_vector{50, 20, 30, 5000};
  std::vector<int> second_vector{10};
  std::vector<int> third_vector{500, 10};
  for (int i = 0, j = 0, k = 0; i < first_vector.size(); ++i, ++j, ++k) {
    if (j == second_vector.size()) {
      j = 0;
    }
    if (k == third_vector.size()) {
      k = 0;
    }
    std::cout << first_vector[i] << '|' << second_vector[j] << '|'
              << third_vector[k] << '\n';
    std::cin.get();
  }
  return 0;
}

</code>```

Body:
I have two std::vectors of same type, and I need to iterate through both of them using the same routine. Something like this:

std::vector<int> values1, values2;
int counter = 0;
for (int val : values1) counter += val;
for (int val : values2) counter += val;

Is there any simple way to write the last two lines in a single loop, to avoid code repetition? Something that would look like this:

std::vector<int> values1, values2;
int counter = 0;
for (int val : values1, values2) counter += val;

Body:
I used something like this to iterate through 3 different vectors of different size where one vector was dependent of the two other vectors (first_vector is dependent on the other vectors).

#include <iostream>
#include <vector>
int main() {
  std::vector<int> first_vector{50, 20, 30, 5000};
  std::vector<int> second_vector{10};
  std::vector<int> third_vector{500, 10};
  for (int i = 0, j = 0, k = 0; i < first_vector.size(); ++i, ++j, ++k) {
    if (j == second_vector.size()) {
      j = 0;
    }
    if (k == third_vector.size()) {
      k = 0;
    }
    std::cout << first_vector[i] << '|' << second_vector[j] << '|'
              << third_vector[k] << '\n';
    std::cin.get();
  }
  return 0;
}


问:
Telegram: Bad Request: failed to get HTTP URL content: two similar links: one works, one doesn't
I'm trying to send two gifs to Telegram:

First:

```<code>https://preview.redd.it/1dsyzqgv3os21.gif?s=c4c426909c653ae159c6bd36a79542245b8dd124
</code>```

Request link:

```<code> https://api.telegram.org/botXXX...XXX/sendAnimation?chat_id=@XXXX&animation=https%3A%2F%2Fpreview.redd.it%2F1dsyzqgv3os21.gif%3Fs%3Dc4c426909c653ae159c6bd36a79542245b8dd124
</code>```

Second:

```<code>https://external-preview.redd.it/LD9iy2VqTJPrkBtOCKE9jBdJA3003epxng2LwOIzBzk.gif?s=75a8452ac1000ef27b7cf95b6535163b8cd671ec
</code>```

Request link:

```<code>https://api.telegram.org/botXXX...XXX/sendAnimation?chat_id=@XXXX&animation=https%3A%2F%2Fexternal-preview.redd.it%2FLD9iy2VqTJPrkBtOCKE9jBdJA3003epxng2LwOIzBzk.gif%3Fs%3D75a8452ac1000ef27b7cf95b6535163b8cd671ec
</code>```

Despite them being rather similar in their structure, only the first one works.

When I try to send the second request I get:

```<code>{
    "ok": false,
    "error_code": 400,
    "description": "Bad Request: failed to get HTTP URL content"
}
</code>```

Why is that? What can I do to fix it?

答:
This is a problem with Telegram's CDN I believe.

I had made a bot to fetch content from Instagram and upload it on Telegram.

This had happened a lot back then so I implemented a mechanism to fetch the photo using my own server and then send the photo by uploading it rather than passing the direct link to Telegram.

Hope this helps others as well.

Body:
I'm trying to send two gifs to Telegram:

First:

https://preview.redd.it/1dsyzqgv3os21.gif?s=c4c426909c653ae159c6bd36a79542245b8dd124

Request link:

 https://api.telegram.org/botXXX...XXX/sendAnimation?chat_id=@XXXX&animation=https%3A%2F%2Fpreview.redd.it%2F1dsyzqgv3os21.gif%3Fs%3Dc4c426909c653ae159c6bd36a79542245b8dd124

Second:

https://external-preview.redd.it/LD9iy2VqTJPrkBtOCKE9jBdJA3003epxng2LwOIzBzk.gif?s=75a8452ac1000ef27b7cf95b6535163b8cd671ec

Request link:

https://api.telegram.org/botXXX...XXX/sendAnimation?chat_id=@XXXX&animation=https%3A%2F%2Fexternal-preview.redd.it%2FLD9iy2VqTJPrkBtOCKE9jBdJA3003epxng2LwOIzBzk.gif%3Fs%3D75a8452ac1000ef27b7cf95b6535163b8cd671ec

Despite them being rather similar in their structure, only the first one works.

When I try to send the second request I get:

{
    "ok": false,
    "error_code": 400,
    "description": "Bad Request: failed to get HTTP URL content"
}

Why is that? What can I do to fix it?


问:
Mongodb Mongoose sort and paginate chat messages
I am making a chat app where 10 messages are loaded per page. The messages are sorted from oldest to latest, so the new messages come in bottom and old messages are in top. I tried to use skip() and limit() methods it didnt work.

let count = page*10

MessageModel.find(find_query).sort({createdAt: 'asc'}).skip(count-10).limit(10).exec();```
</div>
</div>
</p>
<p>for example:</p>
<p>let these be my messages sorted oldest to newest: <code>["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]</code></p>
<p>the above query returns the data like this in
1st page: <code>["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]</code></p>
<p>2nd page : <code>["11", "12"]</code></p>
<p>but I want it to return</p>
<p>in 1st page: <code>["3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]</code></p>
<p>in 2nd page: <code>["1", "2"]</code></p>
<p><strong>EDIT:</strong>
I tried sorting it into descending and reversing, this seemed to fix the issue.</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-js lang-js prettyprint-override"><code>let count = page*10

const messages = await MessageModel.find(find_query).sort({createdAt: 'desc'}).skip(count-10).limit(10).exec();

const re_messages = messages.reverse()</code>```

答:
Since you want to display messages 3 to 12 first, you need to sort using 'desc' instead of 'asc', so as to get the newest messages first. This will give you ["12", "11", ... "4", "3"]. Now all you have to do is to invert this array to get ["3", "4", ... "11", "12"]:

```<code>let count = page*10

let messages = await MessageModel
                        .find(find_query)
                        .sort({createdAt: 'desc'}) // get the latest ones
                        .skip(count-10)
                        .limit(10)
                        .exec()
                        .lean(); // Get a simple array

messages.reverse(); // ["3", "4", ... "11", "12"]
</code>```

Body:
I am making a chat app where 10 messages are loaded per page. The messages are sorted from oldest to latest, so the new messages come in bottom and old messages are in top. I tried to use skip() and limit() methods it didnt work.

let count = page*10

MessageModel.find(find_query).sort({createdAt: 'asc'}).skip(count-10).limit(10).exec();

for example:

let these be my messages sorted oldest to newest: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

the above query returns the data like this in
1st page: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

2nd page : ["11", "12"]

but I want it to return

in 1st page: ["3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]

in 2nd page: ["1", "2"]

EDIT:
I tried sorting it into descending and reversing, this seemed to fix the issue.

let count = page*10

const messages = await MessageModel.find(find_query).sort({createdAt: 'desc'}).skip(count-10).limit(10).exec();

const re_messages = messages.reverse()

Body:
Since you want to display messages 3 to 12 first, you need to sort using 'desc' instead of 'asc', so as to get the newest messages first. This will give you ["12", "11", ... "4", "3"]. Now all you have to do is to invert this array to get ["3", "4", ... "11", "12"]:

let count = page*10

let messages = await MessageModel
                        .find(find_query)
                        .sort({createdAt: 'desc'}) // get the latest ones
                        .skip(count-10)
                        .limit(10)
                        .exec()
                        .lean(); // Get a simple array

messages.reverse(); // ["3", "4", ... "11", "12"]


问:
Avoid repeating config between Conan profile and CMake
I have been learning Conan for a personal project, and I have a question that I haven't been able to answer from looking at the docs and examples.

There seems to be an awkward lack of interaction between Conan's "profiles" and CMake.  What I mean is: There are a number of different build parameters that must be manually kept in sync - running CMake with different parameters than the ones that were chosen during conan install will result in build errors.

To give a more concrete example, here are two of my configs and how I would use them to build:

```<code>$ cat ~/.conan/profiles/gcc_debug
[settings]
os=Linux
os_build=Linux
arch=x86_64
arch_build=x86_64
compiler=gcc
compiler.version=10
compiler.libcxx=libstdc++11
build_type=Debug
[options]
[build_requires]
[env]

$ export CC=/usr/bin/gcc
$ export CXX=/usr/bin/g++
$ conan install ../src --profile gcc_debug
$ cmake ../src -GNinja -DCMAKE_BUILD_TYPE=Debug
$ cmake --build .
</code>```
```<code>$ cat ~/.conan/profiles/clang_cl_release
[settings]
os=Windows
os_build=Windows
arch=x86_64
arch_build=x86_64
compiler=Visual Studio
compiler.version=16
compiler.toolset=ClangCL
build_type=Release
[options]
[build_requires]
[env]

$ conan install ../src --profile clang_cl_release
$ cmake ../src -G"Visual Studio 16 2019" -TClangCL
$ cmake --build . --config=Release
</code>```

In the first example, I have to repeat gcc and Debug.

In the second one, I have to repeat Visual Studio, 16, ClangCL, and Release.

Having to repeat myself so many times feels smelly, especially when these options are spread out across multiple long-running commands, and forgetting one just option can result in non-obvious error messages.  It also seems weird to me that Conan doesn't just enforce (override) the appropriate CMake vars when you call cmake_basic_setup(); it already knows what values it expects, and blows up if they don't match.

What is the recommended way to handle this?

答:
See recommended conan usage: https://github.com/conan-io/cmake-conan</p>
```<code>set(CONAN_PROFILE_NAME ${CMAKE_SYSTEM_NAME}-${CMAKE_GENERATOR})
execute_process(COMMAND ${CONAN_CMD} profile new ${CONAN_PROFILE_NAME} --detect ERROR_QUIET)
conan_cmake_autodetect(settings)

# REPEAT THIS FOR EACH OF YOUR REMOTES
conan_cmake_configure(REQUIRES zlib/1.2.0 GENERATORS cmake_find_package)
conan_cmake_install(PATH_OR_REFERENCE .
                BUILD missing
                REMOTE conancenter
                PROFILE ${CONAN_PROFILE_NAME}
                SETTINGS ${settings})

find_package(zlib)
</code>```

Body:
I have been learning Conan for a personal project, and I have a question that I haven't been able to answer from looking at the docs and examples.

There seems to be an awkward lack of interaction between Conan's "profiles" and CMake.  What I mean is: There are a number of different build parameters that must be manually kept in sync - running CMake with different parameters than the ones that were chosen during conan install will result in build errors.

To give a more concrete example, here are two of my configs and how I would use them to build:

$ cat ~/.conan/profiles/gcc_debug
[settings]
os=Linux
os_build=Linux
arch=x86_64
arch_build=x86_64
compiler=gcc
compiler.version=10
compiler.libcxx=libstdc++11
build_type=Debug
[options]
[build_requires]
[env]

$ export CC=/usr/bin/gcc
$ export CXX=/usr/bin/g++
$ conan install ../src --profile gcc_debug
$ cmake ../src -GNinja -DCMAKE_BUILD_TYPE=Debug
$ cmake --build .

$ cat ~/.conan/profiles/clang_cl_release
[settings]
os=Windows
os_build=Windows
arch=x86_64
arch_build=x86_64
compiler=Visual Studio
compiler.version=16
compiler.toolset=ClangCL
build_type=Release
[options]
[build_requires]
[env]

$ conan install ../src --profile clang_cl_release
$ cmake ../src -G"Visual Studio 16 2019" -TClangCL
$ cmake --build . --config=Release

In the first example, I have to repeat gcc and Debug.

In the second one, I have to repeat Visual Studio, 16, ClangCL, and Release.

Having to repeat myself so many times feels smelly, especially when these options are spread out across multiple long-running commands, and forgetting one just option can result in non-obvious error messages.  It also seems weird to me that Conan doesn't just enforce (override) the appropriate CMake vars when you call cmake_basic_setup(); it already knows what values it expects, and blows up if they don't match.

What is the recommended way to handle this?

Body:
See recommended conan usage: https://github.com/conan-io/cmake-conan

set(CONAN_PROFILE_NAME ${CMAKE_SYSTEM_NAME}-${CMAKE_GENERATOR})
execute_process(COMMAND ${CONAN_CMD} profile new ${CONAN_PROFILE_NAME} --detect ERROR_QUIET)
conan_cmake_autodetect(settings)

# REPEAT THIS FOR EACH OF YOUR REMOTES
conan_cmake_configure(REQUIRES zlib/1.2.0 GENERATORS cmake_find_package)
conan_cmake_install(PATH_OR_REFERENCE .
                BUILD missing
                REMOTE conancenter
                PROFILE ${CONAN_PROFILE_NAME}
                SETTINGS ${settings})

find_package(zlib)


问:
Update Segmented Progress Bar When CollectionView Index is Changed Swift
Working Example Video

I am trying to create an onboarding view such as Instagram stories with a progress bar on top of the view.

So far I was able to animate to the second or third index in the given time. This animation also changes stack view progress bar. But when I try to scroll to the next or previous collection view index I can not show this action inside the progress bar.

I can read the current page index with page control but can not reflect this reading to progress bar.

```<code>class OnboardingViewController: UIViewController, SegmentedProgressBarDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var stackView: UIStackView!

    private var spb: SegmentedProgressBar!

    var currentPage = 0

    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.numberOfPages = slides.count
        return pageControl
    }()

    //Burası Presenter'dan gelecek.
    var slides: [OnboardingSlide] = [
        OnboardingSlide(title: "Delicious Dishes", image: #imageLiteral(resourceName: "1")),
        OnboardingSlide(title: "World-Class Chefs", image: #imageLiteral(resourceName: "2")),
        OnboardingSlide(title: "Instant World-Wide Delivery", image: #imageLiteral(resourceName: "3"))
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        spb = SegmentedProgressBar(numberOfSegments: slides.count, duration: 3)
        spb.frame = CGRect(x: 15, y: 56, width: collectionView.frame.width - 30, height: 4)
        spb.delegate = self
        spb.topColor = UIColor.white
        spb.bottomColor = UIColor.white.withAlphaComponent(0.25)
        spb.padding = 2
        collectionView.delegate = self
        collectionView.dataSource = self
        stackView.addArrangedSubview(spb)
        spb.startAnimation()
        collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedView)))
    }

    func segmentedProgressBarChangedIndex(index: Int) {
        updateView(index: index)
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }

    func segmentedProgressBarFinished() {
        print("Finished!")
    }

    @objc private func tappedView() {
        spb.isPaused = !spb.isPaused
    }

    private func updateView(index: Int) {
        print("index: \(index)")
        let indexPath = IndexPath(row: index, section: 0)
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }

    @IBAction func loginButtonTapped(_ sender: UIButton) {
    }

    @IBAction func signupButtonTapped(_ sender: UIButton) {
    }

}

extension OnboardingViewController: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return slides.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCollectionViewCell.identifier, for: indexPath) as! OnboardingCollectionViewCell
        cell.setup(slides[indexPath.row])
        return cell
    }

}

extension OnboardingViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let width = scrollView.frame.width
        currentPage = Int(scrollView.contentOffset.x / width)
        pageControl.currentPage = currentPage
        updateView(index: currentPage)
        print("current page: \(currentPage)")
    }
}
</code>```

I have used
https://github.com/D-32/SegmentedProgressBar

as the segmentedProgressBar

```<code>class OnboardingCollectionViewCell: UICollectionViewCell {

    static let identifier = String(describing: OnboardingCollectionViewCell.self)

    @IBOutlet weak var slideImageView: UIImageView!
    @IBOutlet weak var slideTitleLabel: UILabel!

    func setup(_ slide: OnboardingSlide) {
        slideImageView.image = slide.image
        slideTitleLabel.text = slide.title
    }
}

struct OnboardingSlide {
    let title: String
    let image: UIImage
}
</code>```

答:
```<code>extension OnboardingViewController: UICollectionViewDelegateFlowLayout {

    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        if scrollView.panGestureRecognizer .translation(in: view).x > 0 {
            spb.rewind()
            } else {
                spb.skip()
            }
    }
}
</code>```

with this, I was able to understand if collection view was scrolled left or right. Thus calling related functions inside the spb does the trick.

Body:
Working Example Video

I am trying to create an onboarding view such as Instagram stories with a progress bar on top of the view.

So far I was able to animate to the second or third index in the given time. This animation also changes stack view progress bar. But when I try to scroll to the next or previous collection view index I can not show this action inside the progress bar.

I can read the current page index with page control but can not reflect this reading to progress bar.

class OnboardingViewController: UIViewController, SegmentedProgressBarDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var stackView: UIStackView!

    private var spb: SegmentedProgressBar!

    var currentPage = 0

    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.numberOfPages = slides.count
        return pageControl
    }()

    //Burası Presenter'dan gelecek.
    var slides: [OnboardingSlide] = [
        OnboardingSlide(title: "Delicious Dishes", image: #imageLiteral(resourceName: "1")),
        OnboardingSlide(title: "World-Class Chefs", image: #imageLiteral(resourceName: "2")),
        OnboardingSlide(title: "Instant World-Wide Delivery", image: #imageLiteral(resourceName: "3"))
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        spb = SegmentedProgressBar(numberOfSegments: slides.count, duration: 3)
        spb.frame = CGRect(x: 15, y: 56, width: collectionView.frame.width - 30, height: 4)
        spb.delegate = self
        spb.topColor = UIColor.white
        spb.bottomColor = UIColor.white.withAlphaComponent(0.25)
        spb.padding = 2
        collectionView.delegate = self
        collectionView.dataSource = self
        stackView.addArrangedSubview(spb)
        spb.startAnimation()
        collectionView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tappedView)))
    }

    func segmentedProgressBarChangedIndex(index: Int) {
        updateView(index: index)
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }

    func segmentedProgressBarFinished() {
        print("Finished!")
    }

    @objc private func tappedView() {
        spb.isPaused = !spb.isPaused
    }

    private func updateView(index: Int) {
        print("index: \(index)")
        let indexPath = IndexPath(row: index, section: 0)
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
    }

    @IBAction func loginButtonTapped(_ sender: UIButton) {
    }

    @IBAction func signupButtonTapped(_ sender: UIButton) {
    }

}

extension OnboardingViewController: UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return slides.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OnboardingCollectionViewCell.identifier, for: indexPath) as! OnboardingCollectionViewCell
        cell.setup(slides[indexPath.row])
        return cell
    }

}

extension OnboardingViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
    }

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let width = scrollView.frame.width
        currentPage = Int(scrollView.contentOffset.x / width)
        pageControl.currentPage = currentPage
        updateView(index: currentPage)
        print("current page: \(currentPage)")
    }
}

I have used
https://github.com/D-32/SegmentedProgressBar

as the segmentedProgressBar

class OnboardingCollectionViewCell: UICollectionViewCell {

    static let identifier = String(describing: OnboardingCollectionViewCell.self)

    @IBOutlet weak var slideImageView: UIImageView!
    @IBOutlet weak var slideTitleLabel: UILabel!

    func setup(_ slide: OnboardingSlide) {
        slideImageView.image = slide.image
        slideTitleLabel.text = slide.title
    }
}

struct OnboardingSlide {
    let title: String
    let image: UIImage
}

Body:
extension OnboardingViewController: UICollectionViewDelegateFlowLayout {

    func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
        if scrollView.panGestureRecognizer .translation(in: view).x > 0 {
            spb.rewind()
            } else {
                spb.skip()
            }
    }
}

with this, I was able to understand if collection view was scrolled left or right. Thus calling related functions inside the spb does the trick.


问:
VSCode Python Debugger stops suddenly
after installing Windows updates today, debugging is not working anymore.

This is my active debug configuration:

```<code>"launch": {
  "version": "0.2.0",
  "configurations": [
    {
      "name": "DEBUG CURR",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "internalConsole",
      "justMyCode": false,
      "stopOnEntry": false,
    }...
</code>```

When I start the debugger, the menu pops up briefly for 1-2 seconds. But then it closes. There is no output in the console.

It does not stop at set breakpoints.

Does anybody have the same problem? Is there a solution?

System settings

OS: Microsoft Windows 10 Enterprise (10.0.17763 Build 17763)

VSCode version 1.64.0

Python version: 3.8.11 (in the active Anaconda Environment)

Installed VSCode extensions:

Python (Microsoft) version: v2022.0.1786462952

Pylance (Microsoft) version: v2022.2.0

答:
It's an issue with the latest Python Extension for VSCode.

Downgrading the python extension to v2021.12.1559732655 fixes the problem.

Title: VSCode Python Debugger stops suddenly

Body:
after installing Windows updates today, debugging is not working anymore.

This is my active debug configuration:

"launch": {
  "version": "0.2.0",
  "configurations": [
    {
      "name": "DEBUG CURR",
      "type": "python",
      "request": "launch",
      "program": "${file}",
      "console": "internalConsole",
      "justMyCode": false,
      "stopOnEntry": false,
    }...

When I start the debugger, the menu pops up briefly for 1-2 seconds. But then it closes. There is no output in the console.

It does not stop at set breakpoints.

Does anybody have the same problem? Is there a solution?

System settings

OS: Microsoft Windows 10 Enterprise (10.0.17763 Build 17763)

VSCode version 1.64.0

Python version: 3.8.11 (in the active Anaconda Environment)

Installed VSCode extensions:

Python (Microsoft) version: v2022.0.1786462952

Pylance (Microsoft) version: v2022.2.0


问:
C: Checking command line argument is integer or not?
Signature of isdigit

```<code>int isdigit(int c);
</code>```

Signature of atoi

```<code>int atoi(const char *nptr);
</code>```

I just wanted to check whether the command line argument passed was an integer or not.Here is the C Code:

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

int main(int argc, char *argv[])
{
    if (argc == 1)
        return -1;

    printf ("Hai, you have executed the program : %s\n", argv[0]);
    if (isdigit(atoi(argv[1])))
        printf ("%s is a number\n", argv[1]);
    else
        printf ("%s is not a number\n", argv[1]);
    return 0;
}
</code>```

But the output is not as expected, when I am passing a valid number:

```<code>$ ./a.out 123
Hai, you have executed the program : ./a.out
123 is not a number
$ ./a.out add
Hai, you have executed the program : ./a.out
add is not a number
</code>```

I couldn't figure out the error.

答:
Here is the simplest solution which also checks if users enters more than two arguments

```<code>// check for valid key
{
    for (int i = 0, n = strlen(argv[1]); i < n; i++)
    {
        if (!isdigit(argv[1][i]))
        {
            return false;
        }
    }
    return true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Signature of isdigit

int isdigit(int c);

Signature of atoi

int atoi(const char *nptr);

I just wanted to check whether the command line argument passed was an integer or not.Here is the C Code:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    if (argc == 1)
        return -1;

    printf ("Hai, you have executed the program : %s\n", argv[0]);
    if (isdigit(atoi(argv[1])))
        printf ("%s is a number\n", argv[1]);
    else
        printf ("%s is not a number\n", argv[1]);
    return 0;
}

But the output is not as expected, when I am passing a valid number:

$ ./a.out 123
Hai, you have executed the program : ./a.out
123 is not a number
$ ./a.out add
Hai, you have executed the program : ./a.out
add is not a number

I couldn't figure out the error.

Body:
Here is the simplest solution which also checks if users enters more than two arguments

// check for valid key
{
    for (int i = 0, n = strlen(argv[1]); i < n; i++)
    {
        if (!isdigit(argv[1][i]))
        {
            return false;
        }
    }
    return true;
}


问:
Android Manifest permissions issue
I have an app where im using uses-permission tags in the AndroidManifest.xml to give some permissions to my app, eg CAMERA. But when i check the permissions through my phone's settings all the given permissions are denied and i have to manually change it to allow. What could be wrong? Thanks!

答:
In higher Android versions the user needs to allow the permissions.
You must to show a dialog asking about the permissions

https://developer.android.com/training/permissions/requesting

Title: Android Manifest permissions issue


问:
Annotation Validation Error when trying to install Vault on OpenShift
Following this tutorial on installing Vault with Helm on OpenShift, I encountered the following error after executing the command:

```<code>bash
helm install vault hashicorp/vault -n $VAULT_NAMESPACE -f my_values.yaml
</code>```

For the config:

```<code>values.yaml
bash
echo '# Custom values for the Vault chart
global:
  # If deploying to OpenShift
  openshift: true
server:
  dev:
    enabled: true
  serviceAccount:
    create: true
    name: vault-sa
injector:
  enabled: true
authDelegator:
  enabled: true' > my_values.yaml
</code>```

The error:

```<code>$ helm install vault hashicorp/vault -n $VAULT_NAMESPACE -f values.yaml
Error: INSTALLATION FAILED: rendered manifests contain a resource that already exists. Unable to continue with install: ClusterRole "vault-agent-injector-clusterrole" in namespace "" exists and cannot be imported into the current release: invalid ownership metadata; annotation validation error: key "meta.helm.sh/release-namespace" must equal "my-vault-1": current value is "my-vault-0"
</code>```

What exactly is happening, or how can I reset this specific name space to point to the right release namespace?

答:
Have you by chance tried the exact same thing before, because that is what the error is hinting.
If we dissect the error, we get the to the root of the problem:

```<code>Error: INSTALLATION FAILED: rendered manifests contain a resource that already exists.
</code>```

So something on the cluster already exists that you were trying to deploy via the helm chart.

```<code>Unable to continue with install:
</code>```

Helm is aborting due to this failure

```<code>ClusterRole "vault-agent-injector-clusterrole" in namespace "" exists
</code>```

So the cluster role vault-agent-injector-clusterrole that the helm chart is supposed to put onto the cluster already exsits. ClusterRoles aren't namespace specific, hence the "namespace" is blank.

```<code>and cannot be imported into the current release: invalid ownership metadata; annotation validation error: key "meta.helm.sh/release-namespace" must equal "my-vault-1": current value is "my-vault-0"
</code>```

The default behavior is to try to import existing resources that this chart requires, but it is not possible, because the owner of that ClusterRole is different from the deployment.

To fix this, you can remove the existing deployment of your chart and then give it an other try and it should work as expected.

Make sure all resources are gone. For this particular one you can check with kubectl get clusterroles

Body:
Following this tutorial on installing Vault with Helm on OpenShift, I encountered the following error after executing the command:

bash
helm install vault hashicorp/vault -n $VAULT_NAMESPACE -f my_values.yaml

For the config:

values.yaml
bash
echo '# Custom values for the Vault chart
global:
  # If deploying to OpenShift
  openshift: true
server:
  dev:
    enabled: true
  serviceAccount:
    create: true
    name: vault-sa
injector:
  enabled: true
authDelegator:
  enabled: true' > my_values.yaml

The error:

$ helm install vault hashicorp/vault -n $VAULT_NAMESPACE -f values.yaml
Error: INSTALLATION FAILED: rendered manifests contain a resource that already exists. Unable to continue with install: ClusterRole "vault-agent-injector-clusterrole" in namespace "" exists and cannot be imported into the current release: invalid ownership metadata; annotation validation error: key "meta.helm.sh/release-namespace" must equal "my-vault-1": current value is "my-vault-0"

What exactly is happening, or how can I reset this specific name space to point to the right release namespace?

Body:
Have you by chance tried the exact same thing before, because that is what the error is hinting.
If we dissect the error, we get the to the root of the problem:

Error: INSTALLATION FAILED: rendered manifests contain a resource that already exists.

So something on the cluster already exists that you were trying to deploy via the helm chart.

Unable to continue with install:

Helm is aborting due to this failure

ClusterRole "vault-agent-injector-clusterrole" in namespace "" exists

So the cluster role vault-agent-injector-clusterrole that the helm chart is supposed to put onto the cluster already exsits. ClusterRoles aren't namespace specific, hence the "namespace" is blank.

and cannot be imported into the current release: invalid ownership metadata; annotation validation error: key "meta.helm.sh/release-namespace" must equal "my-vault-1": current value is "my-vault-0"

The default behavior is to try to import existing resources that this chart requires, but it is not possible, because the owner of that ClusterRole is different from the deployment.

To fix this, you can remove the existing deployment of your chart and then give it an other try and it should work as expected.

Make sure all resources are gone. For this particular one you can check with kubectl get clusterroles


问:
Why does keycloak hide the "Service-account-admin-cli" user under "Users" section?
I was trying to call keycloak's REST api to create new users under a realm and I was following this tutorial:
https://www.appsdeveloperblog.com/keycloak-rest-api-create-a-new-user/

I was able to configure the Admin-cli client as below:

and I was able to get the access token by using the client id and secret:

However, when I make a POST request to /auth/admin/realms/myapp/users with the bearer token, it fails to create a user and I got an "unknow_error"

I searched through the internet and community and documentation but there was no clue. Eventually after hours and hours of trying, I found a solution:

You need to first go to clients --> admin_cli --> Sessions:

Then click on the user "Service-account-admin-cli" and configure such that it has admin role

Then, the previous POST request will successfully create a new user.

I cannot understand why this user "Service-account-admin-cli" is hidden under the users section:

Why would it be hidden??? How are people supposed to find this user (Service-account-admin-cli) and configure it?  Does keycloak expect people to find it by clicking clients --> admin_cli --> Sessions and then see the user from there??

答:
Just did the same tutorial and had the same problem. Thank you for your post! It helped me to figure out the solution. I don't know if that is due to a newer Keycloak-version but I don't even see the session of the service-account.

Instead of going through the session-menu you could instead go to:

clients -> admin-cli -> service account roles

And then add "manage-users" from:

client roles -> realm-management

I think that's how it's supposed to work.


问:
Error: Failed to download metadata for repo 'appstream': Cannot prepare internal mirrorlist: No URLs in mirrorlist
I am trying to download java using yum on centOs which I specified in Dockerfile.
After pulling centOs image the run crushed and throw this error!?
also to mention that my server instance is AWS EC2!</p>
```<code>Step 2/9 : RUN yum install java -y
 ---> Running in 39fc233aa965
CentOS Linux 8 - AppStream                      184  B/s |  38  B     00:00
Error: Failed to download metadata for repo 'appstream': Cannot prepare internal mirrorlist: No URLs in mirrorlist
The command '/bin/sh -c yum install java -y' returned a non-zero code: 1
</code>```

答:
If you don't already have it, you'll need the gpg keys:

```<code>wget 'http://mirror.centos.org/centos/8-stream/BaseOS/x86_64/os/Packages/centos-gpg-keys-8-3.el8.noarch.rpm'
sudo rpm -i 'centos-gpg-keys-8-3.el8.noarch.rpm'
</code>```

Then it's as simple as transitioning like so:

```<code>dnf --disablerepo '*' --enablerepo=extras swap centos-linux-repos centos-stream-repos
</code>```

Don't worry -- it doesn't remove any repos, it simply temporarily ignores all of yours, and downloads information regarding the new mirrors.

You may at this point want to actually upgrade your packages:

```<code>sudo dnf distro-sync
</code>```

You'll now be able to use "yum" as usual.

Body:
I am trying to download java using yum on centOs which I specified in Dockerfile.
After pulling centOs image the run crushed and throw this error!?
also to mention that my server instance is AWS EC2!

Step 2/9 : RUN yum install java -y
 ---> Running in 39fc233aa965
CentOS Linux 8 - AppStream                      184  B/s |  38  B     00:00
Error: Failed to download metadata for repo 'appstream': Cannot prepare internal mirrorlist: No URLs in mirrorlist
The command '/bin/sh -c yum install java -y' returned a non-zero code: 1

Body:
If you don't already have it, you'll need the gpg keys:

wget 'http://mirror.centos.org/centos/8-stream/BaseOS/x86_64/os/Packages/centos-gpg-keys-8-3.el8.noarch.rpm'
sudo rpm -i 'centos-gpg-keys-8-3.el8.noarch.rpm'

Then it's as simple as transitioning like so:

dnf --disablerepo '*' --enablerepo=extras swap centos-linux-repos centos-stream-repos

Don't worry -- it doesn't remove any repos, it simply temporarily ignores all of yours, and downloads information regarding the new mirrors.

You may at this point want to actually upgrade your packages:

sudo dnf distro-sync

You'll now be able to use "yum" as usual.


问:
How to use loop in new date function to return day of week
I have this code and I'd like to return days of week based in this constant:

```<code>    const dayOfWeek = {
              '0': 'Sun',
              '1': 'Mon',
              '2': 'Tue',
              '3': 'Wed',
              '4': 'Thu',
              '5': 'Fri',
              '6': 'Sat',
            }

 info.forEach(function (information, counter) {
            // Get date
            var dateConvert = new Date()
            var date = (dateConvert.getDay());
            // Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length === infoPerRow) {

              // Create new row and class
              row = document.createElement("div");
              row.classList.add("row");
              rowCity = document.createElement("h1");
              rowCity.classList.add("rowCity");

              //Append the row to the fragment
              fragment.appendChild(rowCity);
              fragment.appendChild(row);

            }
            console.log(row);
            //Update the content of row
            rowCity.innerHTML = `<h2>${name} - ${country}</h2><br><form onSubmit={this.handleDelete}><button type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form><br>`;
            row.innerHTML += `<div><h3>${dayOfWeek[date]}</h3><br><h2>${iconCodes[information.icon]}</h2><br><h5>${information.temp} ºC</h5><br><h6>${information.description}</h6></div>`;
          });
</code>```

I expect to have something like this in this loop. That are 8 days. The first is current day and then the next 7 days:

Mon
-1.33 ºC overcast clouds

Tue
-2.34 ºC broken clouds

EDIT: I did it

```<code>info.forEach(function (information, counter) {
            // Get date
            var dateConvert = new Date(information.dt)
            var date = (dateConvert.toLocaleString("en-us", { weekday: "short" }));
            console.log(date)
            // Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length === infoPerRow) {

              // Create new row and class
              row = document.createElement("div");
              row.classList.add("row");
              rowCity = document.createElement("h1");
              rowCity.classList.add("rowCity");

              //Append the row to the fragment
              fragment.appendChild(rowCity);
              fragment.appendChild(row);

            }
            console.log(row);
            //Update the content of row
            rowCity.innerHTML = `<h2>${name} - ${country}</h2><form onSubmit={this.handleDelete}><button class="btn" type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form><br>`;
            row.innerHTML += `<div><h3>${date}</h3><br><h2>${iconCodes[information.icon]}</h2><br><h5>${information.temp} ºC</h5><br><h6>${information.description}</h6></div>`;
          });
</code>```

But I get all days Tue. Like this:

Tue // Here is today, Mon
19.5 ºC clear sky

Tue // Ok here
15.62 ºC clear sky

Tue // Wed
16.01 ºC clear sky

and so on

答:
```<code>const dayOfWeek = {
  "0": "Sun",
  "1": "Mon",
  "2": "Tue",
  "3": "Wed",
  "4": "Thu",
  "5": "Fri",
  "6": "Sat",
};
const nextDay = input => {
  const output = new Date(input.valueOf());
  output.setDate(output.getDate() + 1);
  return output;
};

let day = new Date();
for (let i = 0; i < 7; i++) {
  console.log(day.toLocaleString("en-us", { weekday: "short" }));
  console.log(dayOfWeek[day.getDay()]);

  day = nextDay(day);
}
</code>```

The 2 log statements have the same output.
The first produces the result you are after without the object and the second by indexing your constant

EDIT:
Or to do it inside the loop you have...

```<code>let today = new Date();
const addDays = (input, days) => {
      const output = new Date(input.valueOf());
      output.setDate(output.getDate() + days);
      return output;
    };
 info.forEach(function (information, counter) {
            var day = addDays(today, counter);

            // render details
          });
</code>```

And finally... directly from the info data

```<code>const info = { dt: 1644245080 };
const date = new Date(info.dt);
console.log(date.toLocaleString("en-us", { weekday: "short" }));
</code>```

Body:
I have this code and I'd like to return days of week based in this constant:

    const dayOfWeek = {
              '0': 'Sun',
              '1': 'Mon',
              '2': 'Tue',
              '3': 'Wed',
              '4': 'Thu',
              '5': 'Fri',
              '6': 'Sat',
            }

 info.forEach(function (information, counter) {
            // Get date
            var dateConvert = new Date()
            var date = (dateConvert.getDay());
            // Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length === infoPerRow) {

              // Create new row and class
              row = document.createElement("div");
              row.classList.add("row");
              rowCity = document.createElement("h1");
              rowCity.classList.add("rowCity");

              //Append the row to the fragment
              fragment.appendChild(rowCity);
              fragment.appendChild(row);

            }
            console.log(row);
            //Update the content of row
            rowCity.innerHTML = `<h2>${name} - ${country}</h2><br><form onSubmit={this.handleDelete}><button type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form><br>`;
            row.innerHTML += `<div><h3>${dayOfWeek[date]}</h3><br><h2>${iconCodes[information.icon]}</h2><br><h5>${information.temp} ºC</h5><br><h6>${information.description}</h6></div>`;
          });

I expect to have something like this in this loop. That are 8 days. The first is current day and then the next 7 days:

Mon
-1.33 ºC overcast clouds

Tue
-2.34 ºC broken clouds

EDIT: I did it

info.forEach(function (information, counter) {
            // Get date
            var dateConvert = new Date(information.dt)
            var date = (dateConvert.toLocaleString("en-us", { weekday: "short" }));
            console.log(date)
            // Check if first itteration or if the row is full
            if (counter === 0 || row.querySelectorAll("p").length === infoPerRow) {

              // Create new row and class
              row = document.createElement("div");
              row.classList.add("row");
              rowCity = document.createElement("h1");
              rowCity.classList.add("rowCity");

              //Append the row to the fragment
              fragment.appendChild(rowCity);
              fragment.appendChild(row);

            }
            console.log(row);
            //Update the content of row
            rowCity.innerHTML = `<h2>${name} - ${country}</h2><form onSubmit={this.handleDelete}><button class="btn" type="submit" id="add" onClick={this.handleDelete}>Remove City</button></form><br>`;
            row.innerHTML += `<div><h3>${date}</h3><br><h2>${iconCodes[information.icon]}</h2><br><h5>${information.temp} ºC</h5><br><h6>${information.description}</h6></div>`;
          });

But I get all days Tue. Like this:

Tue // Here is today, Mon
19.5 ºC clear sky

Tue // Ok here
15.62 ºC clear sky

Tue // Wed
16.01 ºC clear sky

and so on

Body:
const dayOfWeek = {
  "0": "Sun",
  "1": "Mon",
  "2": "Tue",
  "3": "Wed",
  "4": "Thu",
  "5": "Fri",
  "6": "Sat",
};
const nextDay = input => {
  const output = new Date(input.valueOf());
  output.setDate(output.getDate() + 1);
  return output;
};

let day = new Date();
for (let i = 0; i < 7; i++) {
  console.log(day.toLocaleString("en-us", { weekday: "short" }));
  console.log(dayOfWeek[day.getDay()]);

  day = nextDay(day);
}

The 2 log statements have the same output.
The first produces the result you are after without the object and the second by indexing your constant

EDIT:
Or to do it inside the loop you have...

let today = new Date();
const addDays = (input, days) => {
      const output = new Date(input.valueOf());
      output.setDate(output.getDate() + days);
      return output;
    };
 info.forEach(function (information, counter) {
            var day = addDays(today, counter);

            // render details
          });

And finally... directly from the info data

const info = { dt: 1644245080 };
const date = new Date(info.dt);
console.log(date.toLocaleString("en-us", { weekday: "short" }));


问:
Swift - IOS : How to measure height and width of item from within layout
I have a collectionviewcell with multiple textfields, pictures and labels together. The data is dynamically added, which can have shorter or longer labels and pictures making each cell of collectionview having different height and width. I want to measure the width and height of my collectionviewcell programatically to do multiple things, amongst them is also setting number of columns according to width and height of my cell as per different orientation.
Any ideas how can a width and height be measured?
The layout is drawn on main storyboard without any extra xib. I'll highly appreciate the response</p>

答:
Generally speaking, you shouldn't have to know your view's dimensions (sometimes, but rarely). For instance, I've written a view that mimics the behavior and look of Apple HealthKit's move/exercise/stand rings, and extended it so it can display as many rings as you want, and display a percentage value (e.g. "80%") of the innermost ring or, if you prefer, use a closure to include another subview inside the innermost ring. With all of this, I didn't need to know the view's dimensions.

The trick to it is really to invert your thinking a bit. Try to push configuration into the view, and make your view adaptable.

You mentioned that alignment is challenging; yes, but once you really get the hang of it, it's powerful. I'd recommend this reference on how to make the best use of alignment guides, it's an excellent explanation: https://swiftui-lab.com/alignment-guides/

But if all else fails and you are absolutely determined to use the view's dimensions, take a look at GeometryReader:

```<code>GeometryReader { geometry in
    HStack(spacing: 0) {
        Text("Left")
            .font(.largeTitle)
            .foregroundColor(.black)
            .frame(width: geometry.size.width * 0.33)
            .background(Color.yellow)
        Text("Right")
            .font(.largeTitle)
            .foregroundColor(.black)
            .frame(width: geometry.size.width * 0.67)
            .background(Color.orange)
    }
}
.frame(height: 50)
</code>```

Check out Hacking with Swift for a more in-depth explanation: https://www.hackingwithswift.com/quick-start/swiftui/how-to-provide-relative-sizes-using-geometryreader

Be careful with GeometryReader though. Look at using it in a .background() or .overlay() to avoid altering your view. The catch-22 with it is that in order to figure out your view's dimensions, GeometryReader creates a view that fills all available space... and this actually can affect the layout of your view. But if you put it in an overlay, you can avoid the problem. Using it tends to be more work than just figuring out how to do the layout without needing to know dimensions. That's how SwiftUI is designed to work.

Body:
Generally speaking, you shouldn't have to know your view's dimensions (sometimes, but rarely). For instance, I've written a view that mimics the behavior and look of Apple HealthKit's move/exercise/stand rings, and extended it so it can display as many rings as you want, and display a percentage value (e.g. "80%") of the innermost ring or, if you prefer, use a closure to include another subview inside the innermost ring. With all of this, I didn't need to know the view's dimensions.

The trick to it is really to invert your thinking a bit. Try to push configuration into the view, and make your view adaptable.

You mentioned that alignment is challenging; yes, but once you really get the hang of it, it's powerful. I'd recommend this reference on how to make the best use of alignment guides, it's an excellent explanation: https://swiftui-lab.com/alignment-guides/

But if all else fails and you are absolutely determined to use the view's dimensions, take a look at GeometryReader:

GeometryReader { geometry in
    HStack(spacing: 0) {
        Text("Left")
            .font(.largeTitle)
            .foregroundColor(.black)
            .frame(width: geometry.size.width * 0.33)
            .background(Color.yellow)
        Text("Right")
            .font(.largeTitle)
            .foregroundColor(.black)
            .frame(width: geometry.size.width * 0.67)
            .background(Color.orange)
    }
}
.frame(height: 50)

Check out Hacking with Swift for a more in-depth explanation: https://www.hackingwithswift.com/quick-start/swiftui/how-to-provide-relative-sizes-using-geometryreader

Be careful with GeometryReader though. Look at using it in a .background() or .overlay() to avoid altering your view. The catch-22 with it is that in order to figure out your view's dimensions, GeometryReader creates a view that fills all available space... and this actually can affect the layout of your view. But if you put it in an overlay, you can avoid the problem. Using it tends to be more work than just figuring out how to do the layout without needing to know dimensions. That's how SwiftUI is designed to work.


问:
how to locate an id of the button to click when id is dynamic in robot framework
I am new to robot framework and learned few basics of robot framework. when i tried to create a new account in facebook , i have used id element of "create new account" but everytime new id is generated when its open an new page. can someone help to make me understand how to click a button when id is dynamic.

```<code>*** Settings ***

Library    SeleniumLibrary

*** Test Cases ***

facebooklogin

    open browser    https://www.facebook.com/    firefox
    maximize browser window
    set selenium timeout    10s
    click button    id:u_0_d_si
</code>```

Error message : Button with locator 'id:u_0_d_si' not found.

答:
sometimes this works great on dynamic elements:</p>
```<code>${element1}=  Asign Id To Element  contains...etc
Execute Javascript   arguments[0].click();   Arguments   ${element1}
</code>```

Body:
I am new to robot framework and learned few basics of robot framework. when i tried to create a new account in facebook , i have used id element of "create new account" but everytime new id is generated when its open an new page. can someone help to make me understand how to click a button when id is dynamic.

*** Settings ***

Library    SeleniumLibrary

*** Test Cases ***

facebooklogin

    open browser    https://www.facebook.com/    firefox
    maximize browser window
    set selenium timeout    10s
    click button    id:u_0_d_si

Error message : Button with locator 'id:u_0_d_si' not found.

Body:
sometimes this works great on dynamic elements:

${element1}=  Asign Id To Element  contains...etc
Execute Javascript   arguments[0].click();   Arguments   ${element1}