问:
Start SCS server from another class (WinForms)
I'm trying to implement a SCS framework server with WinForms in C# but I am having issues making it work. The server standalone works fine when using it in the Main method (no WinForms).  I have a client-sided and a server-sided sample code from the SCS framework that I'm trying to implement in WinForms together with some of my own code. It all went well until I decided to try and use WinForms aswell (I had to move the server code to a class of it's own).

I am not getting any errors when I am starting the server, however I can't connect with the client anymore (worked before I moved the server to a class of its own). Client gets System.Net.Sockets.SocketException. On the server-side, I get the error System.InvalidOperationException when the client is trying to connect.

This is my Form1.cs:

```<code>using System;
using System.Windows.Forms;

namespace Server_Test
{
    public partial class Form1 : Form
    {
        public static Form1 Self;
        Server server = new Server();

        public Form1()
        {
            InitializeComponent();
            Self = this;
        }

        public void rtb1Text(string text)
        {
            richTextBox1.AppendText(text);
        }

        public void rtb2Text(string text)
        {
            richTextBox2.Text = text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text.EndsWith("Start"))
            {
                button1.Text = "Stop";
                server.ServerInit();
            }
            else if (button1.Text.EndsWith("Stop"))
            {
                button1.Text = "Start";
                // Does nothing atm
            }
        }
    }
}
</code>```

And this is my Server.cs

```<code>using System;
using Hik.Communication.Scs.Communication.EndPoints.Tcp;
using Hik.Communication.Scs.Communication.Messages;
using Hik.Communication.Scs.Server;

namespace Server_Test
{
    class Server
    {
        public void ServerInit()
        {
            // Create a server that listens 10085 TCP port for incoming connections
            var server = ScsServerFactory.CreateServer(new ScsTcpEndPoint(10085));

            // Register events of the server to be informed about clients
            server.ClientConnected += Server_ClientConnected;
            server.ClientDisconnected += Server_ClientDisconnected;

            // Start the server
            server.Start();

            // Form1.Self.rtb1Text("Server has been started successfully.\n");
            Console.WriteLine("Server has been started successfully.\n");
        }

        static void Server_ClientConnected(object sender, ServerClientEventArgs e)
        {
            Form1.Self.rtb1Text("A new client with ID: " + e.Client.ClientId + " has connected.\n");

            // Register to MessageReceived event to receive messages from new client
            e.Client.MessageReceived += Client_MessageReceived;
        }

        static void Server_ClientDisconnected(object sender, ServerClientEventArgs e)
        {
            Form1.Self.rtb1Text("A client is disconnected! Client Id = " + e.Client.ClientId + "\n");
        }

        static async void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            var message = e.Message as ScsTextMessage; // Server only accepts text messages
            if (message == null)
            {
                return;
            }

            //Get a reference to the client
            var client = (IScsServerClient)sender;

            Form1.Self.rtb1Text("Client (ID:" + client.ClientId + ") sent a request: " + message.Text + "\n");

            switch (message.Text)
            {
                case "api":
                    HttpPost httpPost = new HttpPost();
                    var apiResponse = await httpPost.SendPost("robot_info");

                    //Send reply message to the client
                    client.SendMessage(
                        new ScsTextMessage(
                            apiResponse,
                            message.MessageId //Set first message's id as replied message id
                            ));
                    break;
                default:
                    break;
            }
        }
    }
}
</code>```

My guess is that I'm doing something wrong when creating a new instance of the Server class and how I'm initializing/starting the server. Might be something else though, I've tried debugging but it didn't make me any smarter.

Any ideas?

Body:
I'm trying to implement a SCS framework server with WinForms in C# but I am having issues making it work. The server standalone works fine when using it in the Main method (no WinForms).  I have a client-sided and a server-sided sample code from the SCS framework that I'm trying to implement in WinForms together with some of my own code. It all went well until I decided to try and use WinForms aswell (I had to move the server code to a class of it's own).

I am not getting any errors when I am starting the server, however I can't connect with the client anymore (worked before I moved the server to a class of its own). Client gets System.Net.Sockets.SocketException. On the server-side, I get the error System.InvalidOperationException when the client is trying to connect.

This is my Form1.cs:

using System;
using System.Windows.Forms;

namespace Server_Test
{
    public partial class Form1 : Form
    {
        public static Form1 Self;
        Server server = new Server();

        public Form1()
        {
            InitializeComponent();
            Self = this;
        }

        public void rtb1Text(string text)
        {
            richTextBox1.AppendText(text);
        }

        public void rtb2Text(string text)
        {
            richTextBox2.Text = text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text.EndsWith("Start"))
            {
                button1.Text = "Stop";
                server.ServerInit();
            }
            else if (button1.Text.EndsWith("Stop"))
            {
                button1.Text = "Start";
                // Does nothing atm
            }
        }
    }
}

And this is my Server.cs

using System;
using Hik.Communication.Scs.Communication.EndPoints.Tcp;
using Hik.Communication.Scs.Communication.Messages;
using Hik.Communication.Scs.Server;

namespace Server_Test
{
    class Server
    {
        public void ServerInit()
        {
            // Create a server that listens 10085 TCP port for incoming connections
            var server = ScsServerFactory.CreateServer(new ScsTcpEndPoint(10085));

            // Register events of the server to be informed about clients
            server.ClientConnected += Server_ClientConnected;
            server.ClientDisconnected += Server_ClientDisconnected;

            // Start the server
            server.Start();

            // Form1.Self.rtb1Text("Server has been started successfully.\n");
            Console.WriteLine("Server has been started successfully.\n");
        }

        static void Server_ClientConnected(object sender, ServerClientEventArgs e)
        {
            Form1.Self.rtb1Text("A new client with ID: " + e.Client.ClientId + " has connected.\n");

            // Register to MessageReceived event to receive messages from new client
            e.Client.MessageReceived += Client_MessageReceived;
        }

        static void Server_ClientDisconnected(object sender, ServerClientEventArgs e)
        {
            Form1.Self.rtb1Text("A client is disconnected! Client Id = " + e.Client.ClientId + "\n");
        }

        static async void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            var message = e.Message as ScsTextMessage; // Server only accepts text messages
            if (message == null)
            {
                return;
            }

            //Get a reference to the client
            var client = (IScsServerClient)sender;

            Form1.Self.rtb1Text("Client (ID:" + client.ClientId + ") sent a request: " + message.Text + "\n");

            switch (message.Text)
            {
                case "api":
                    HttpPost httpPost = new HttpPost();
                    var apiResponse = await httpPost.SendPost("robot_info");

                    //Send reply message to the client
                    client.SendMessage(
                        new ScsTextMessage(
                            apiResponse,
                            message.MessageId //Set first message's id as replied message id
                            ));
                    break;
                default:
                    break;
            }
        }
    }
}

My guess is that I'm doing something wrong when creating a new instance of the Server class and how I'm initializing/starting the server. Might be something else though, I've tried debugging but it didn't make me any smarter.

Any ideas?


来源: stackexchange

问:
Bootstrap 5: Box in a row disappers after I hover on it
I want to display some elements in boxes with a hover-effect on the website. Two boxes are usualy in a row. If the number of elements is unequal the last box get displayed in the last row alone.

If it's the case and I hover on this last box, the box disappers and the hover effect doesn't working. If the row is filled with two boxes all works fine.

I haven't found any solution to slove it.

How I can solve this behaviour of boxes which are alone in a row?

ContentLicense: CC BY-SA 4.0


问:
How can I make std:::cin take input up to the first non-integar and then discard the rest?
The

way this code currently functions is that if a non-number is input it will set the error flag, clear the error then ignore.

However if A user inputs a number followed by a non number such as 2garbage1 it will succeed and pass 5 into the first variable \n into the next variable and garbage1 into the third variable.

```<code>
>
</code>```
```<code>do {
    std::cout << "\n\nPlease Enter the number of Names you would like to store: ";
    std::cin >> noOfNames;  // get user input for the number of names the user would like to enter.

    if (!(valid_input = std::cin.good())) { // if valid input does not = true
        std::cout << "That input is invalid!\n";
        std::cin.clear(); //Clear stream to remove error flag
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore everything and deliminate with \n

    }
} while (!valid_input);

for (int i = 0; i < noOfNames; i++) //forloop which will iterate through the number of names getting user input on each iteration
{
    std::cout << "Enter name #" << i + 1 << ": "; // the i + 1 will avoid displaying name #1 as name #0 since i begins at 0
    std::cin >> tempName; // get user input and store it in tempName
    vec2.push_back(tempName); // add tempName to vec2
}
</code>```

If 2garbage1 was input it would output this:

"Please enter the number of names you would like to store: 2garbage1

Name #1 =

Name #2 = garbage1

obviously that's not ideal and I'd like to discard anything after the final number.

Links and resources so I can read up/watch videos about the topic too would be appreciated I can't seem to find exactly what I'm looking for on google and even if I do I'd like to understand what the code is doing.

Body:
The

way this code currently functions is that if a non-number is input it will set the error flag, clear the error then ignore.

However if A user inputs a number followed by a non number such as 2garbage1 it will succeed and pass 5 into the first variable \n into the next variable and garbage1 into the third variable.

>

do {
    std::cout << "\n\nPlease Enter the number of Names you would like to store: ";
    std::cin >> noOfNames;  // get user input for the number of names the user would like to enter.

    if (!(valid_input = std::cin.good())) { // if valid input does not = true
        std::cout << "That input is invalid!\n";
        std::cin.clear(); //Clear stream to remove error flag
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // ignore everything and deliminate with \n

    }
} while (!valid_input);

for (int i = 0; i < noOfNames; i++) //forloop which will iterate through the number of names getting user input on each iteration
{
    std::cout << "Enter name #" << i + 1 << ": "; // the i + 1 will avoid displaying name #1 as name #0 since i begins at 0
    std::cin >> tempName; // get user input and store it in tempName
    vec2.push_back(tempName); // add tempName to vec2
}

If 2garbage1 was input it would output this:

"Please enter the number of names you would like to store: 2garbage1

Name #1 =

Name #2 = garbage1

obviously that's not ideal and I'd like to discard anything after the final number.

Links and resources so I can read up/watch videos about the topic too would be appreciated I can't seem to find exactly what I'm looking for on google and even if I do I'd like to understand what the code is doing.


问:
map form group properties back to an existing object in angular
I currently want to map user information from an angular reactive form back to my existing user object. The caveat is my user object I want to update has some additional properties so doing something like...

```<code>this.user = this.userDetailsForm.value
</code>```

would just overwrite the whole object and losing information such as user id that is not on the form group but it on the user. Without having to manually map each field in the form group is there an easier way to map property to property?

Body:
I currently want to map user information from an angular reactive form back to my existing user object. The caveat is my user object I want to update has some additional properties so doing something like...

this.user = this.userDetailsForm.value

would just overwrite the whole object and losing information such as user id that is not on the form group but it on the user. Without having to manually map each field in the form group is there an easier way to map property to property?


问:
How to block or noindex a specific image in GatsbyJS?
I am using Gatsby 5 for my website. I want to No Index specific images on my website. So That the Image don't appear in Search Result.

I am using gatsby-plugin-image for rendering image. Please let me know how to do that.

I have tried to search for the solution but haven't found any.


问:
How retrieve specific element object from data list mongo db in NodeJs?
I use this method to retrieve data list

```<code>exports.getAllUser = (req, res) => {
User.find()
.then((user) => {
  return res.send(user);
})
.catch((err) => {
  return res.status(500).json({
    message: err,
  });
});
};
</code>```

Json Result

```<code>[
{
    "_id": "63a15f05530ef46e890bb650",
    "UserId": "joe",
    "FullName": "Joe",
    "Email": abc@gmail.com",
    "Password": "$2b$10$MjQzZvKViJgmKv7Ksdq4RufF5aEWKdBbnDMvoeH4MmPJKcUN7J96.",
    "Role": "63a133a2d02f67477b9106af",
    "CreatedDateTime": "2022-12-20T07:06:42.487Z",
    "UpdatedDateTime": "2022-12-20T07:06:45.947Z",
    "__v": 0
},
{
    "_id": "63a1619a945bc6efe79e457c",
    "UserId": "jacky",
    "FullName": "Jacky",
    "Email": "cde@gmail.com",
    "Password": "$2b$10$598.n1jiI11ZzIhMg46bce.rDvmIOBmV0IRHEIVsygrGSgYV/kZD.",
    "Role": "63a133a2d02f67477b9106af",
    "CreatedDateTime": "2022-12-20T07:16:55.595Z",
    "UpdatedDateTime": "2022-12-20T07:17:46.323Z",
    "__v": 0
}
]
</code>```

The problem is I don't want to retrieve password field element how to retrieve data list not include password element to get data response.

I want to get json data like this.

```<code> [
  {
"_id": "63a15f05530ef46e890bb650",
"UserId": "joe",
"FullName": "Joe",
"Email": abc@gmail.com",
"Role": "63a133a2d02f67477b9106af",
 },
 {
 "_id": "63a1619a945bc6efe79e457c",
"UserId": "jacky",
"FullName": "Jacky",
"Email": "cde@gmail.com",
"Role": "63a133a2d02f67477b9106af",
}
]
</code>```

Body:
I use this method to retrieve data list

exports.getAllUser = (req, res) => {
User.find()
.then((user) => {
  return res.send(user);
})
.catch((err) => {
  return res.status(500).json({
    message: err,
  });
});
};

Json Result

[
{
    "_id": "63a15f05530ef46e890bb650",
    "UserId": "joe",
    "FullName": "Joe",
    "Email": abc@gmail.com",
    "Password": "$2b$10$MjQzZvKViJgmKv7Ksdq4RufF5aEWKdBbnDMvoeH4MmPJKcUN7J96.",
    "Role": "63a133a2d02f67477b9106af",
    "CreatedDateTime": "2022-12-20T07:06:42.487Z",
    "UpdatedDateTime": "2022-12-20T07:06:45.947Z",
    "__v": 0
},
{
    "_id": "63a1619a945bc6efe79e457c",
    "UserId": "jacky",
    "FullName": "Jacky",
    "Email": "cde@gmail.com",
    "Password": "$2b$10$598.n1jiI11ZzIhMg46bce.rDvmIOBmV0IRHEIVsygrGSgYV/kZD.",
    "Role": "63a133a2d02f67477b9106af",
    "CreatedDateTime": "2022-12-20T07:16:55.595Z",
    "UpdatedDateTime": "2022-12-20T07:17:46.323Z",
    "__v": 0
}
]

The problem is I don't want to retrieve password field element how to retrieve data list not include password element to get data response.

I want to get json data like this.

 [
  {
"_id": "63a15f05530ef46e890bb650",
"UserId": "joe",
"FullName": "Joe",
"Email": abc@gmail.com",
"Role": "63a133a2d02f67477b9106af",
 },
 {
 "_id": "63a1619a945bc6efe79e457c",
"UserId": "jacky",
"FullName": "Jacky",
"Email": "cde@gmail.com",
"Role": "63a133a2d02f67477b9106af",
}
]


问:
Bad Request: One or more of the contents is not owned by the author. All contents must be owned by the author
I've been trying to POST an image to linkedin via the API given by linkedin: https://api.linkedin.com/v2/ugcPosts

Here are some of the steps I followed according to their documentation:

Step 1: Register the image,

Response I get:

```<code>{
    "value": {
        "mediaArtifact": "urn:li:digitalmediaMediaArtifact:(urn:li:digitalmediaAsset:C4D22AQHnSETazVUUiw,urn:li:digitalmediaMediaArtifactClass:feedshare-uploadedImage)",
        "uploadMechanism": {
            "com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest": {
                "uploadUrl": "https://api.linkedin.com/mediaUpload/C4D22AQHnSETazVUUiw/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQKy8KTj9ZExhAAAAYUvD_6GEclpKOZdwJvPF682Ld1UUb6h0V7VvAtpuA&app=206373578&sync=0&v=beta&ut=3dh6EETZGM5WA1",
                "headers": {
                    "media-type-family": "STILLIMAGE"
                }
            }
        },
        "asset": "urn:li:digitalmediaAsset:C4D22AQHnSETazVUUiw",
        "assetRealTimeTopic": "urn:li-realtime:digitalmediaAssetUpdatesTopic:urn:li:digitalmediaAsset:C4D22AQHnSETazVUUiw"
    }
}
</code>```

Step 2: Upload the image using upload URL from Step 1
Response: 201 Created status code with no message

Checked the status, it's says available: https://api.linkedin.com/v2/assets/C4D22AQHnSETazVUUiw

```<code>{
    "recipes": [
        {
            "recipe": "urn:li:digitalmediaRecipe:feedshare-image",
            "status": "AVAILABLE"
        }
    ],
    "serviceRelationships": [
        {
            "relationshipType": "OWNER",
            "identifier": "urn:li:userGeneratedContent"
        }
    ],
    "mediaTypeFamily": "STILLIMAGE",
    "created": 1671531855410,
    "id": "C4D22AQHnSETazVUUiw",
    "lastModified": 1671531901231,
    "status": "ALLOWED"
}
</code>```

Now when I am trying to POST it to the endpoint: https://api.linkedin.com/v2/ugcPosts

It's giving 400 bad Request with the following Error:

```<code>{
    "errorDetailType": "com.linkedin.common.error.BadRequest",
    "message": "com.linkedin.content.common.exception.BadRequestResponseException: One or more of the contents is not owned by the author. All contents must be owned by the author",
    "errorDetails": {
        "inputErrors": [
            {
                "description": "Content(s) you provided must be owned by post author",
                "input": {},
                "code": "INVALID_CONTENT_OWNERSHIP"
            }
        ]
    },
    "status": 400
}
</code>```

I've given all permissions to it:

r_emailaddress, r_liteprofile, w_member_social

Body:
I've been trying to POST an image to linkedin via the API given by linkedin: https://api.linkedin.com/v2/ugcPosts

Here are some of the steps I followed according to their documentation:

Step 1: Register the image,

Response I get:

{
    "value": {
        "mediaArtifact": "urn:li:digitalmediaMediaArtifact:(urn:li:digitalmediaAsset:C4D22AQHnSETazVUUiw,urn:li:digitalmediaMediaArtifactClass:feedshare-uploadedImage)",
        "uploadMechanism": {
            "com.linkedin.digitalmedia.uploading.MediaUploadHttpRequest": {
                "uploadUrl": "https://api.linkedin.com/mediaUpload/C4D22AQHnSETazVUUiw/feedshare-uploadedImage/0?ca=vector_feedshare&cn=uploads&m=AQKy8KTj9ZExhAAAAYUvD_6GEclpKOZdwJvPF682Ld1UUb6h0V7VvAtpuA&app=206373578&sync=0&v=beta&ut=3dh6EETZGM5WA1",
                "headers": {
                    "media-type-family": "STILLIMAGE"
                }
            }
        },
        "asset": "urn:li:digitalmediaAsset:C4D22AQHnSETazVUUiw",
        "assetRealTimeTopic": "urn:li-realtime:digitalmediaAssetUpdatesTopic:urn:li:digitalmediaAsset:C4D22AQHnSETazVUUiw"
    }
}

Step 2: Upload the image using upload URL from Step 1
Response: 201 Created status code with no message

Checked the status, it's says available: https://api.linkedin.com/v2/assets/C4D22AQHnSETazVUUiw

{
    "recipes": [
        {
            "recipe": "urn:li:digitalmediaRecipe:feedshare-image",
            "status": "AVAILABLE"
        }
    ],
    "serviceRelationships": [
        {
            "relationshipType": "OWNER",
            "identifier": "urn:li:userGeneratedContent"
        }
    ],
    "mediaTypeFamily": "STILLIMAGE",
    "created": 1671531855410,
    "id": "C4D22AQHnSETazVUUiw",
    "lastModified": 1671531901231,
    "status": "ALLOWED"
}

Now when I am trying to POST it to the endpoint: https://api.linkedin.com/v2/ugcPosts

It's giving 400 bad Request with the following Error:

{
    "errorDetailType": "com.linkedin.common.error.BadRequest",
    "message": "com.linkedin.content.common.exception.BadRequestResponseException: One or more of the contents is not owned by the author. All contents must be owned by the author",
    "errorDetails": {
        "inputErrors": [
            {
                "description": "Content(s) you provided must be owned by post author",
                "input": {},
                "code": "INVALID_CONTENT_OWNERSHIP"
            }
        ]
    },
    "status": 400
}

I've given all permissions to it:

r_emailaddress, r_liteprofile, w_member_social


问:
How to return value from Quartz Scheduler Job to View
In ASP.NET MVC Project, I have created a scheduler job, I am using Quartz.net 3.0.7

I need to know if this Job is finished executed to make some changes in the View or ASP.NET Form

I can know if my Job is finished by using Quartz Job Listener:

public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default)
{
    throw new NotImplementedException();
}
```

But I cannot use ViewBag or Session to pass value to detect that because it related to request and has life time and my Job may take long time.

Is there any way to do that or not?

Body:
In ASP.NET MVC Project, I have created a scheduler job, I am using Quartz.net 3.0.7

I need to know if this Job is finished executed to make some changes in the View or ASP.NET Form

I can know if my Job is finished by using Quartz Job Listener:

public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default)
{
    throw new NotImplementedException();
}

But I cannot use ViewBag or Session to pass value to detect that because it related to request and has life time and my Job may take long time.

Is there any way to do that or not?


问:
react native iOS pod install stuck on Installing glog (0.3.5)
I'm on m1 chip and when I ran pod install in my project's ios/ folder, the operation gets stuck at -> Installing glog (0.3.5), I waited for like 1 hr and 40 mins, but still it Was stuck at the same step. My internet is working fine. After a while growing through similar question answers on SO/Github, I added --verbose argument to get the logs of what is happening behind the scenes, and below is the output (not going forward after patching file config.sub step):

```<code>-> Installing glog (0.3.5)
 > Git download
 > Git download
     $ /usr/bin/git clone https://github.com/google/glog.git
     /var/folders/0y/rq93q_q13xl4p8kf4qmnld480000gn/T/d20221220-78496-8l9458 --template=
     --single-branch --depth 1 --branch v0.3.5
     Cloning into '/var/folders/0y/rq93q_q13xl4p8kf4qmnld480000gn/T/d20221220-78496-8l9458'...
     Note: switching to 'a6a166db069520dbbd653c97c2e5b12e08a8bb26'.

     You are in 'detached HEAD' state. You can look around, make experimental
     changes and commit them, and you can discard any commits you make in this
     state without impacting any branches by switching back to a branch.

     If you want to create a new branch to retain commits you create, you may
     do so (now or later) by using -c with the switch command. Example:

       git switch -c <new-branch-name>

     Or undo this operation with:

       git switch -

     Turn off this advice by setting config variable advice.detachedHead to false

 > Running prepare command
   $ /bin/bash -c  set -e #!/bin/bash # Copyright (c) Meta Platforms, Inc. and affiliates.
   # # This source code is licensed under the MIT license found in the # LICENSE file in
   the root directory of this source tree.  set -e
   PLATFORM_NAME="${PLATFORM_NAME:-iphoneos}" CURRENT_ARCH="${CURRENT_ARCH}"  if [ -z
   "$CURRENT_ARCH" ] || [ "$CURRENT_ARCH" == "undefined_arch" ]; then     # Xcode 10 beta
   sets CURRENT_ARCH to "undefined_arch", this leads to incorrect linker arg.     # it's
   better to rely on platform name as fallback because architecture differs between
   simulator and device      if [[ "$PLATFORM_NAME" == *"simulator"* ]]; then
   CURRENT_ARCH="x86_64"     else         CURRENT_ARCH="arm64"     fi fi  if [
   "$CURRENT_ARCH" == "arm64" ]; then     cat <<\EOF >>fix_glog_0.3.5_apple_silicon.patch
   diff --git a/config.sub b/config.sub index 1761d8b..43fa2e8 100755 --- a/config.sub +++
   b/config.sub @@ -1096,6 +1096,9 @@ case $basic_machine in        basic_machine=z8k-unknown
   os=-sim          ;; +    arm64-*) +      basic_machine=$(echo $basic_machine | sed
   's/arm64/aarch64/') +        ;;      none)       basic_machine=none-none     os=-none EOF      patch
   -p1 config.sub fix_glog_0.3.5_apple_silicon.patch fi  export CC="$(xcrun -find -sdk
   $PLATFORM_NAME cc) -arch $CURRENT_ARCH -isysroot $(xcrun -sdk $PLATFORM_NAME
   --show-sdk-path)" export CXX="$CC"  # Remove automake symlink if it exists if [ -h
   "test-driver" ]; then     rm test-driver fi  # Manually disable gflags include to fix
   issue https://github.com/facebook/react-native/issues/28446 sed -i ''
   's/\@ac_cv_have_libgflags\@/0/' src/glog/logging.h.in sed -i ''
   's/HAVE_LIB_GFLAGS/HAVE_LIB_GFLAGS_DISABLED/' src/config.h.in  ./configure --host
   arm-apple-darwin  cat << EOF >> src/config.h /* Add in so we have Apple Target
   Conditionals */ #ifdef __APPLE__ #include <TargetConditionals.h> #include
   <Availability.h> #endif  /* Special configuration for ucontext */ #undef HAVE_UCONTEXT_H
   #undef PC_FROM_UCONTEXT #if defined(__x86_64__) #define PC_FROM_UCONTEXT
   uc_mcontext->__ss.__rip #elif defined(__i386__) #define PC_FROM_UCONTEXT
   uc_mcontext->__ss.__eip #endif EOF  # Prepare exported header include
   EXPORTED_INCLUDE_DIR="exported/glog" mkdir -p exported/glog cp -f
   src/glog/log_severity.h "$EXPORTED_INCLUDE_DIR/" cp -f src/glog/logging.h
   "$EXPORTED_INCLUDE_DIR/" cp -f src/glog/raw_logging.h "$EXPORTED_INCLUDE_DIR/" cp -f
   src/glog/stl_logging.h "$EXPORTED_INCLUDE_DIR/" cp -f src/glog/vlog_is_on.h
   "$EXPORTED_INCLUDE_DIR/"
   patching file config.sub
</code>```

Podfile:

```<code>require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '13.0'
install! 'cocoapods', :deterministic_uuids => false

target 'myapp' do
  use_expo_modules!
  post_integrate do |installer|
    begin
      expo_patch_react_imports!(installer)
    rescue => e
      Pod::UI.warn e
    end
  end
  config = use_native_modules!
  # config = use_frameworks!
  use_frameworks! :linkage => :static
  $RNFirebaseAsStaticFramework = true

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config[:reactNativePath],
    # Hermes is now enabled by default. Disable by setting this flag to false.
    # Upcoming versions of React Native may rely on get_default_flags(), but
    # we make it explicit here to aid in the React Native upgrade process.
    :hermes_enabled => true,
    :fabric_enabled => flags[:fabric_enabled],
   :flipper_configuration => FlipperConfiguration.disabled,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'myappTests' do
    inherit! :complete
    # Pods for testing
  end
  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end
</code>```

Output of npx react-native info:

```<code>info Fetching system and libraries information...
System:
    OS: macOS 12.5
    CPU: (8) arm64 Apple M1
    Memory: 1.20 GB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.13.2 - ~/.nvm/versions/node/v16.13.2/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v16.13.2/bin/yarn
    npm: 8.1.2 - ~/.nvm/versions/node/v16.13.2/bin/npm
    Watchman: 2022.12.12.00 - /opt/homebrew/bin/watchman
  Managers:
    CocoaPods: 1.11.3 - /opt/homebrew/bin/pod
  SDKs:
    iOS SDK:
      Platforms: DriverKit 22.1, iOS 16.1, macOS 13.0, tvOS 16.1, watchOS 9.1
    Android SDK:
      API Levels: 29, 30, 31, 33
      Build Tools: 30.0.3, 31.0.0, 33.0.0
      System Images: android-31 | Google Play ARM 64 v8a
      Android NDK: Not Found
  IDEs:
    Android Studio: 2021.3 AI-213.7172.25.2113.9123335
    Xcode: 14.1/14B47b - /usr/bin/xcodebuild
  Languages:
    Java: 11.0.17 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: Not Found
    react-native: Not Found
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found
</code>```

Can someone shed some light on this matter?

If anyone require any more information about the project/env, please ask, I'll try to provide it!

Thank you in advance!

Body:
I'm on m1 chip and when I ran pod install in my project's ios/ folder, the operation gets stuck at -> Installing glog (0.3.5), I waited for like 1 hr and 40 mins, but still it Was stuck at the same step. My internet is working fine. After a while growing through similar question answers on SO/Github, I added --verbose argument to get the logs of what is happening behind the scenes, and below is the output (not going forward after patching file config.sub step):

-> Installing glog (0.3.5)
 > Git download
 > Git download
     $ /usr/bin/git clone https://github.com/google/glog.git
     /var/folders/0y/rq93q_q13xl4p8kf4qmnld480000gn/T/d20221220-78496-8l9458 --template=
     --single-branch --depth 1 --branch v0.3.5
     Cloning into '/var/folders/0y/rq93q_q13xl4p8kf4qmnld480000gn/T/d20221220-78496-8l9458'...
     Note: switching to 'a6a166db069520dbbd653c97c2e5b12e08a8bb26'.

     You are in 'detached HEAD' state. You can look around, make experimental
     changes and commit them, and you can discard any commits you make in this
     state without impacting any branches by switching back to a branch.

     If you want to create a new branch to retain commits you create, you may
     do so (now or later) by using -c with the switch command. Example:

       git switch -c <new-branch-name>

     Or undo this operation with:

       git switch -

     Turn off this advice by setting config variable advice.detachedHead to false

 > Running prepare command
   $ /bin/bash -c  set -e #!/bin/bash # Copyright (c) Meta Platforms, Inc. and affiliates.
   # # This source code is licensed under the MIT license found in the # LICENSE file in
   the root directory of this source tree.  set -e
   PLATFORM_NAME="${PLATFORM_NAME:-iphoneos}" CURRENT_ARCH="${CURRENT_ARCH}"  if [ -z
   "$CURRENT_ARCH" ] || [ "$CURRENT_ARCH" == "undefined_arch" ]; then     # Xcode 10 beta
   sets CURRENT_ARCH to "undefined_arch", this leads to incorrect linker arg.     # it's
   better to rely on platform name as fallback because architecture differs between
   simulator and device      if [[ "$PLATFORM_NAME" == *"simulator"* ]]; then
   CURRENT_ARCH="x86_64"     else         CURRENT_ARCH="arm64"     fi fi  if [
   "$CURRENT_ARCH" == "arm64" ]; then     cat <<\EOF >>fix_glog_0.3.5_apple_silicon.patch
   diff --git a/config.sub b/config.sub index 1761d8b..43fa2e8 100755 --- a/config.sub +++
   b/config.sub @@ -1096,6 +1096,9 @@ case $basic_machine in        basic_machine=z8k-unknown
   os=-sim          ;; +    arm64-*) +      basic_machine=$(echo $basic_machine | sed
   's/arm64/aarch64/') +        ;;      none)       basic_machine=none-none     os=-none EOF      patch
   -p1 config.sub fix_glog_0.3.5_apple_silicon.patch fi  export CC="$(xcrun -find -sdk
   $PLATFORM_NAME cc) -arch $CURRENT_ARCH -isysroot $(xcrun -sdk $PLATFORM_NAME
   --show-sdk-path)" export CXX="$CC"  # Remove automake symlink if it exists if [ -h
   "test-driver" ]; then     rm test-driver fi  # Manually disable gflags include to fix
   issue https://github.com/facebook/react-native/issues/28446 sed -i ''
   's/\@ac_cv_have_libgflags\@/0/' src/glog/logging.h.in sed -i ''
   's/HAVE_LIB_GFLAGS/HAVE_LIB_GFLAGS_DISABLED/' src/config.h.in  ./configure --host
   arm-apple-darwin  cat << EOF >> src/config.h /* Add in so we have Apple Target
   Conditionals */ #ifdef __APPLE__ #include <TargetConditionals.h> #include
   <Availability.h> #endif  /* Special configuration for ucontext */ #undef HAVE_UCONTEXT_H
   #undef PC_FROM_UCONTEXT #if defined(__x86_64__) #define PC_FROM_UCONTEXT
   uc_mcontext->__ss.__rip #elif defined(__i386__) #define PC_FROM_UCONTEXT
   uc_mcontext->__ss.__eip #endif EOF  # Prepare exported header include
   EXPORTED_INCLUDE_DIR="exported/glog" mkdir -p exported/glog cp -f
   src/glog/log_severity.h "$EXPORTED_INCLUDE_DIR/" cp -f src/glog/logging.h
   "$EXPORTED_INCLUDE_DIR/" cp -f src/glog/raw_logging.h "$EXPORTED_INCLUDE_DIR/" cp -f
   src/glog/stl_logging.h "$EXPORTED_INCLUDE_DIR/" cp -f src/glog/vlog_is_on.h
   "$EXPORTED_INCLUDE_DIR/"
   patching file config.sub

Podfile:

require File.join(File.dirname(`node --print "require.resolve('expo/package.json')"`), "scripts/autolinking")
require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '13.0'
install! 'cocoapods', :deterministic_uuids => false

target 'myapp' do
  use_expo_modules!
  post_integrate do |installer|
    begin
      expo_patch_react_imports!(installer)
    rescue => e
      Pod::UI.warn e
    end
  end
  config = use_native_modules!
  # config = use_frameworks!
  use_frameworks! :linkage => :static
  $RNFirebaseAsStaticFramework = true

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config[:reactNativePath],
    # Hermes is now enabled by default. Disable by setting this flag to false.
    # Upcoming versions of React Native may rely on get_default_flags(), but
    # we make it explicit here to aid in the React Native upgrade process.
    :hermes_enabled => true,
    :fabric_enabled => flags[:fabric_enabled],
   :flipper_configuration => FlipperConfiguration.disabled,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'myappTests' do
    inherit! :complete
    # Pods for testing
  end
  post_install do |installer|
    react_native_post_install(installer)
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

Output of npx react-native info:

info Fetching system and libraries information...
System:
    OS: macOS 12.5
    CPU: (8) arm64 Apple M1
    Memory: 1.20 GB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.13.2 - ~/.nvm/versions/node/v16.13.2/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v16.13.2/bin/yarn
    npm: 8.1.2 - ~/.nvm/versions/node/v16.13.2/bin/npm
    Watchman: 2022.12.12.00 - /opt/homebrew/bin/watchman
  Managers:
    CocoaPods: 1.11.3 - /opt/homebrew/bin/pod
  SDKs:
    iOS SDK:
      Platforms: DriverKit 22.1, iOS 16.1, macOS 13.0, tvOS 16.1, watchOS 9.1
    Android SDK:
      API Levels: 29, 30, 31, 33
      Build Tools: 30.0.3, 31.0.0, 33.0.0
      System Images: android-31 | Google Play ARM 64 v8a
      Android NDK: Not Found
  IDEs:
    Android Studio: 2021.3 AI-213.7172.25.2113.9123335
    Xcode: 14.1/14B47b - /usr/bin/xcodebuild
  Languages:
    Java: 11.0.17 - /usr/bin/javac
  npmPackages:
    @react-native-community/cli: Not Found
    react: Not Found
    react-native: Not Found
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found

Can someone shed some light on this matter?

If anyone require any more information about the project/env, please ask, I'll try to provide it!

Thank you in advance!


问:
set default download directory Chrome karate dsl
I need to specify the directory path where I want the files to be downloaded.
The test I am doing with Karate DSL and the browser is chrome

I have tried several options, but the files are always downloaded in the /downloads folder.
This is my code:

```<code>Feature: download json

@debug
Scenario: download json
    * configure driver = { type: 'chrome', addOptions:["--add_experimental_option('prefs','C:\\workspaces\\gs\\src\test\\java\\ui_gs\\qa')"]}
    Given driver 'http://localhost:52330/src/test/java/ui_gs/encrypt_json.html'
    And input('#rol','adm')
    And input('#usuario','users')
    When click('#button_json')
    Then match text('#user_AES') != 'null'
</code>```

The test writes to two input fields. Clicking on the field with id "button_json" downloads a json file.

Body:
I need to specify the directory path where I want the files to be downloaded.
The test I am doing with Karate DSL and the browser is chrome

I have tried several options, but the files are always downloaded in the /downloads folder.
This is my code:

Feature: download json

@debug
Scenario: download json
    * configure driver = { type: 'chrome', addOptions:["--add_experimental_option('prefs','C:\\workspaces\\gs\\src\test\\java\\ui_gs\\qa')"]}
    Given driver 'http://localhost:52330/src/test/java/ui_gs/encrypt_json.html'
    And input('#rol','adm')
    And input('#usuario','users')
    When click('#button_json')
    Then match text('#user_AES') != 'null'

The test writes to two input fields. Clicking on the field with id "button_json" downloads a json file.


问:
Dot1x not working, allthough LOG-s from freeradius return "Login OK"
I don't now where to look for this particular issue anymore. I have gone numerus time through freeradius configuration and configuration on cisco switch, but I am just unable to find the problem.

My enviroment:

Ubuntu 20.04.5 LTS

FreeRADIUS Version 3.0.20

MariaDB 10.6.11

Cisco C2960X switch

Issue:

I have dot1x configured on Cisco C2960X switch.

On Ubuntu I have freeradius v3 up and running.

Freeradius is able to connact to database, where my users are stored.

I am ussing EAP-TTLS/PAP.

Win10 laptop ethernet card (cable) is configured to use EAP-TTLS/PAP

When trying to connect Win10 laptop over the cable, I am asked to put in the user credentials, afterwards I have to accept the certificate and the authentication is in progress.

In the same time, when looking under Freeradius LOG-s, I get "Login OK" for the user, so user is accepted...great.

But on Win10 laptop authentication fails, allthough Freeradius did accept the user.

When DEBUG-ing Freeradius, everything seems OK:
"Login OK: [user@domain.com] (from client sbl-3 port 50320 cli 38-2C-4A-XX-XX-XX via TLS tunnel)"

When DEBUG-ing C2960x switch, I see an error:
"dot1x-packet:[xxxx.xxxx.xxxx, Gi1/0/19] Added username in dot1x"
"dot1x-packet:[xxxx.xxxx.xxxx, Gi1/0/19] Dot1x did not receive any key data"
"dot1x-ev:[xxxx.xxxx.xxxx, Gi1/0/19] Received Authz fail (result: 2) for the client 0x87000405 (xxxx.xxxx.xxxx)"
"dot1x-sm:[xxxx.xxxx.xxxx, Gi1/0/19] Posting_AUTHZ_FAIL on Client 0x87000405"

But the funny thing is, I have another VM set up with freeradius v2, which connects to the same MariaDB as freeradius v3. With no changes made on C2960X switch (port configuration, aaa etc.) except ofcourse to configure radius server to redirect to another VM (freeradius v2), everything works great. I can se "Login OK" under freeradius LOGs, and Win10 laptop is authenticated and ready to use wired connection.

As it looks like, when using Freeradius v3, I have a problem in the last stage (authorization). But if using Freeradius v2, I have no issue and Win10 laptop is authenticated and ready to use wired connection.

I would really appreciate some help if someone ran into same issue.

Kind Regards, Tomaz

I compared freeradius configuration on both VM, for freeradius v2 and freeradius v3

I debuged freeradius

I debbuged C2960x switch

I recorded traffic with WireShark on Win10 laptop


问:
Google Apps Script Timing out due to large number of files on G-Drive
Hi I have a lot of files on my G-drive and I wanted to delete them so I am trying an app script which I found online

`

```<code>// NEW FUNCTION TO GET LIST OF EMPTY FOLDERS

function getEmptyFolders() {

    // Get sheet
    var sheet = SpreadsheetApp.getActive().getSheetByName('Manage Empty Folders')
    if (!sheet) {
        SpreadsheetApp.getActive().insertSheet('Manage Empty Folders')
    }

    var sheet = SpreadsheetApp.getActive().getSheetByName('Manage Empty Folders')
    var clearContent = sheet.clear()

    var folders = DriveApp.getFolders()

    var fileArray = [
        ["Folder Name", "Folder Id", "Folder URL"]
    ]
    while (folders.hasNext()) {

        var folder = folders.next()

        // If the folder has no files or child folder in it, call them out.
        if (folder.getFiles().hasNext() == false && folder.getFolders().hasNext() == false) {

            var name = folder.getName()
            var id = folder.getId()
            var url = folder.getUrl()

            // Push empty folder details into array
            fileArray.push([name, id, url])
        }
    }
</code>```

`

However whenever I run this it hangs and takes a lot of time and then the error message "Script limit exceeded" pops up which is obvious since there are a billion files out there in the drive. I can go iteratively like per 100 or per 1000 however the script may allow but the minute i use the line :   var folders = DriveApp.getFolders() I guess this is taking time to fetch all folders and causing the scripts to fail. any idea how to select them manually like 100-200 files at a time please ?

i tried putting a for loop but so long as it takes to read the getfolders() i think there is no way to limit that?

Body:
Hi I have a lot of files on my G-drive and I wanted to delete them so I am trying an app script which I found online

`

// NEW FUNCTION TO GET LIST OF EMPTY FOLDERS

function getEmptyFolders() {

    // Get sheet
    var sheet = SpreadsheetApp.getActive().getSheetByName('Manage Empty Folders')
    if (!sheet) {
        SpreadsheetApp.getActive().insertSheet('Manage Empty Folders')
    }

    var sheet = SpreadsheetApp.getActive().getSheetByName('Manage Empty Folders')
    var clearContent = sheet.clear()

    var folders = DriveApp.getFolders()

    var fileArray = [
        ["Folder Name", "Folder Id", "Folder URL"]
    ]
    while (folders.hasNext()) {

        var folder = folders.next()

        // If the folder has no files or child folder in it, call them out.
        if (folder.getFiles().hasNext() == false && folder.getFolders().hasNext() == false) {

            var name = folder.getName()
            var id = folder.getId()
            var url = folder.getUrl()

            // Push empty folder details into array
            fileArray.push([name, id, url])
        }
    }

`

However whenever I run this it hangs and takes a lot of time and then the error message "Script limit exceeded" pops up which is obvious since there are a billion files out there in the drive. I can go iteratively like per 100 or per 1000 however the script may allow but the minute i use the line :   var folders = DriveApp.getFolders() I guess this is taking time to fetch all folders and causing the scripts to fail. any idea how to select them manually like 100-200 files at a time please ?

i tried putting a for loop but so long as it takes to read the getfolders() i think there is no way to limit that?


问:
How to load and preprocess image and numeric data from pandas dataframe in tensorflow batch by batch and still ensure the order?
I have a big dataset (~60000 images and numeric data) as a pandas data frame. The images are stored with the image path. But there are too many images to load and preprocess at once. So I want to load/preprocess the images and numeric data batch by batch and feed it to the network to train. What is the best way to do that and still ensure that the order is right?

My pandas DF is structured as follows:

```<code>["image_path", "numeric_data1", "numeric_data2", "numeric_data3", "boundingBox.x_center", "boundingBox.y_center", "boundingBox.width", "boundingBox.height", "numeric_data4", "label"]
</code>```

I have a multi data network so I have to split the data in image/numeric data/labels but still have to ensure the order.

I tried to preprocess the data in another script and save it as a pickle file. But there is still a memory problem.

Body:
I have a big dataset (~60000 images and numeric data) as a pandas data frame. The images are stored with the image path. But there are too many images to load and preprocess at once. So I want to load/preprocess the images and numeric data batch by batch and feed it to the network to train. What is the best way to do that and still ensure that the order is right?

My pandas DF is structured as follows:

["image_path", "numeric_data1", "numeric_data2", "numeric_data3", "boundingBox.x_center", "boundingBox.y_center", "boundingBox.width", "boundingBox.height", "numeric_data4", "label"]

I have a multi data network so I have to split the data in image/numeric data/labels but still have to ensure the order.

I tried to preprocess the data in another script and save it as a pickle file. But there is still a memory problem.


问:
The basic profile information is not being displayed using Instagram API
I am trying to create a login with instagram form. However at the callback.php, there is no information displayed.

Kindly let me know what could be the possible issue.

Callback.php:

```<code><?php
    session_start();

    if (isset($_GET['error'])) {
        header('Location: login.php');
        exit();
    }

    require "InstagramAPI.php";

    $data = $Instagram->getAccessTokenAndUserDetails($_GET['code']);

    $_SESSION['loggedIn'] = 1;
    $_SESSION['accessToken'] = $data['access_token'];
    $_SESSION['id'] = $data['user']['id'];
    $_SESSION['username'] = $data['user']['username'];
    $_SESSION['bio'] = $data['user']['bio'];
    $_SESSION['website'] = $data['user']['website'];
    $_SESSION['fullName'] = $data['user']['full_name'];
    $_SESSION['profilePicture'] = $data['user']['profile_picture'];

    header('Location: index.php');
    exit();
?>
</code>```

Body:
I am trying to create a login with instagram form. However at the callback.php, there is no information displayed.

Kindly let me know what could be the possible issue.

Callback.php:

<?php
    session_start();

    if (isset($_GET['error'])) {
        header('Location: login.php');
        exit();
    }

    require "InstagramAPI.php";

    $data = $Instagram->getAccessTokenAndUserDetails($_GET['code']);

    $_SESSION['loggedIn'] = 1;
    $_SESSION['accessToken'] = $data['access_token'];
    $_SESSION['id'] = $data['user']['id'];
    $_SESSION['username'] = $data['user']['username'];
    $_SESSION['bio'] = $data['user']['bio'];
    $_SESSION['website'] = $data['user']['website'];
    $_SESSION['fullName'] = $data['user']['full_name'];
    $_SESSION['profilePicture'] = $data['user']['profile_picture'];

    header('Location: index.php');
    exit();
?>


问:
Universal proxy configuration for Python urllib3
I am trying to use and install a python library according to the instructions at: https://pypi.org/project/ai4bharat-transliteration/. My system is behind a corporate proxy and I am able to use pip and other libraries including urllib3 to access the internet when I am writing code from scratch.

However, in this case, the library wants to access some files over internet when running:

```<code>`e = XlitEngine("hi", beam_width=10, rescore=True)`
</code>```

And that results in a wall of urllib3 proxy related errors, the first of which is:

```<code>Downloading Multilingual model for transliteration
SSL certificate not verified...
/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host '172.xx.yy.zzz'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 700, in urlopen
    self._prepare_proxy(conn)
  File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 996, in _prepare_proxy
    conn.connect()
  File "/usr/local/lib/python3.8/dist-packages/urllib3/connection.py", line 369, in connect
    self._tunnel()
  File "/usr/lib/python3.8/http/client.py", line 901, in _tunnel
    (version, code, message) = response._read_status()
  File "/usr/lib/python3.8/http/client.py", line 277, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.8/socket.py", line 669, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 439, in send
    resp = conn.urlopen(
  File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 787, in urlopen
    retries = retries.increment(
  File "/usr/local/lib/python3.8/dist-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='objects.githubusercontent.com', port=443): Max retries exceeded with url: /github-production-release-asset-2e65be/487173539/4ef3b62d-385b-4a3a-9ab1-a3cc55764ef3?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20221220%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221220T101158Z&X-Amz-Expires=300&X-Amz-Signature=d24db49d92188df3dbf8a0f1a05126bdaae8bf42289befe734331a41b336f11c&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=487173539&response-content-disposition=attachment%3B%20filename%3Dindicxlit-en-indic-v1.0.zip&response-content-type=application%2Foctet-stream (Caused by ProxyError('Cannot connect to proxy.', timeout('timed out')))

</code>```

Where 172.xx.yy.zzz is the url to my proxy and I am guessing that the warning regarding the SSL certificate is just a warning and the problem is the proxy configuration of urllib3.

If so, is there a way to set a universal proxy which will be honored by urllib3 before the library is called by the XlitEngine package installed above. I am reluctant to attempt any changes to the XlitEngine package installed above. I tried posting the issue on Github for XlitEngine but have not received any response so far.

If it is of any consequence, I am using Python 3.8.10 on a headless Ubuntu 20.04 Server Virtual Machine.
Cheers!

Body:
I am trying to use and install a python library according to the instructions at: https://pypi.org/project/ai4bharat-transliteration/. My system is behind a corporate proxy and I am able to use pip and other libraries including urllib3 to access the internet when I am writing code from scratch.

However, in this case, the library wants to access some files over internet when running:

`e = XlitEngine("hi", beam_width=10, rescore=True)`

And that results in a wall of urllib3 proxy related errors, the first of which is:

Downloading Multilingual model for transliteration
SSL certificate not verified...
/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host '172.xx.yy.zzz'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 700, in urlopen
    self._prepare_proxy(conn)
  File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 996, in _prepare_proxy
    conn.connect()
  File "/usr/local/lib/python3.8/dist-packages/urllib3/connection.py", line 369, in connect
    self._tunnel()
  File "/usr/lib/python3.8/http/client.py", line 901, in _tunnel
    (version, code, message) = response._read_status()
  File "/usr/lib/python3.8/http/client.py", line 277, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.8/socket.py", line 669, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/requests/adapters.py", line 439, in send
    resp = conn.urlopen(
  File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 787, in urlopen
    retries = retries.increment(
  File "/usr/local/lib/python3.8/dist-packages/urllib3/util/retry.py", line 592, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='objects.githubusercontent.com', port=443): Max retries exceeded with url: /github-production-release-asset-2e65be/487173539/4ef3b62d-385b-4a3a-9ab1-a3cc55764ef3?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20221220%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20221220T101158Z&X-Amz-Expires=300&X-Amz-Signature=d24db49d92188df3dbf8a0f1a05126bdaae8bf42289befe734331a41b336f11c&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=487173539&response-content-disposition=attachment%3B%20filename%3Dindicxlit-en-indic-v1.0.zip&response-content-type=application%2Foctet-stream (Caused by ProxyError('Cannot connect to proxy.', timeout('timed out')))

Where 172.xx.yy.zzz is the url to my proxy and I am guessing that the warning regarding the SSL certificate is just a warning and the problem is the proxy configuration of urllib3.

If so, is there a way to set a universal proxy which will be honored by urllib3 before the library is called by the XlitEngine package installed above. I am reluctant to attempt any changes to the XlitEngine package installed above. I tried posting the issue on Github for XlitEngine but have not received any response so far.

If it is of any consequence, I am using Python 3.8.10 on a headless Ubuntu 20.04 Server Virtual Machine.
Cheers!


问:
How to resample and extend datetime data in this pandas DataFrame?
if have a DataFrame like the one in the photo (https://i.stack.imgur.com/5u3WR.png), and I would like to have, for each grid point the same time series (repeated over and over again), namely:

```<code>t_index_np = np.arange('2013-01-01', '2022-12-31 23:00:00', dtype='datetime64[h]')
</code>```

The frequency is hourly.

You have to take into account that for many grid points there is only one associated date.

What I have tried so far is using a for cycle with resample and pd.merge, but the problem there is that it doesn't work for such points (those with only one date data). Concerning the Total Power column, it must be forward-filled.

Thanks in advance!

Body:
if have a DataFrame like the one in the photo (https://i.stack.imgur.com/5u3WR.png), and I would like to have, for each grid point the same time series (repeated over and over again), namely:

t_index_np = np.arange('2013-01-01', '2022-12-31 23:00:00', dtype='datetime64[h]')

The frequency is hourly.

You have to take into account that for many grid points there is only one associated date.

What I have tried so far is using a for cycle with resample and pd.merge, but the problem there is that it doesn't work for such points (those with only one date data). Concerning the Total Power column, it must be forward-filled.

Thanks in advance!


问:
How to extract resultSet of Query in JpaRepository
I have a Query which returns 3 arrays or 3 columns with values

```<code>@Query(value = "SELECT UNNEST (array_agg(distinct area)) as areas, UNNEST (array_agg(distinct type)) as types,UNNEST (array_agg(distinct type)) as subtypes FROM subject_settings", nativeQuery = true)
Map<String, Collection<String>> findAllUniqueAttributesValues ();
</code>```

My goal is to put the result of query to the Map<String, Collection<String>>. Where string is a column name and Collection  is all distinct values of column.

Also, I don`t want to use DTO.

I tried to make query simply (withount Unnest), but could not take a result. In that case I had an Exception: No Dialect mapping for JDBC type: 2003

By the way, i need to use only one query instead of three.

Body:
I have a Query which returns 3 arrays or 3 columns with values

@Query(value = "SELECT UNNEST (array_agg(distinct area)) as areas, UNNEST (array_agg(distinct type)) as types,UNNEST (array_agg(distinct type)) as subtypes FROM subject_settings", nativeQuery = true)
Map<String, Collection<String>> findAllUniqueAttributesValues ();

My goal is to put the result of query to the Map<String, Collection<String>>. Where string is a column name and Collection  is all distinct values of column.

Also, I don`t want to use DTO.

I tried to make query simply (withount Unnest), but could not take a result. In that case I had an Exception: No Dialect mapping for JDBC type: 2003

By the way, i need to use only one query instead of three.


问:
OpenCV Python Stitching: Define custom keypoints / matches skipping feature detector & matcher
I'm trying to implement the panorama stitching via OpenCV into our process, but want to use control points / matches gathered from PTGui.

PTGui however just lists the keypoints and the matches between images, no angles or additional data.

When using the normal workflow, the feature set is a list of ImageFeatures containing some parameters and a list of Keypoints.

Since I'm using OpenCV in Python, I don't really know how to create the list of ImageFeatures from scratch.

This is the current implementation, which doesn't work:

```<code>f1 = cv.detail_ImageFeatures()
f1.img_idx = 0
f1.descriptors = None
f1.img_size = (1920, 1080)
f1.keypoints = (
    cv.KeyPoint(1412.0, 734.0, 5.0),
    cv.KeyPoint(1415.0, 856.0, 5.0),
    cv.KeyPoint(1398.0, 885.0, 5.0)
)

...

features = [f1, f2, ...]
</code>```

I get the following error when using my custom list just on the next step, which would be the matching: cv2.error: Conversion error: features

In addition to the custom ImageFeatures, I would also need custom matches. According to the documentation, these should be a MatchesInfo struct containing matches of type DMatch.

These are currently implemented as follows, but can't be tested since the above error already occurs beforehand:

```<code>matches = (
  cv.detail_MatchesInfo(confidence=1.0, dst_img_idx=1, H=None, inliers_mask=None, matches=(
    cv.DMatch(0, 0, 0.0),
    cv.DMatch(1, 1, 0.0),
    cv.DMatch(2, 2, 0.0)), num_inliers=None, src_img_idx=0),
  ...
)
</code>```

So I was wondering, if it is even possible to "import" custom control points and matches using OpenCV Python. If yes, what would have to be changed to make it work.

Body:
I'm trying to implement the panorama stitching via OpenCV into our process, but want to use control points / matches gathered from PTGui.

PTGui however just lists the keypoints and the matches between images, no angles or additional data.

When using the normal workflow, the feature set is a list of ImageFeatures containing some parameters and a list of Keypoints.

Since I'm using OpenCV in Python, I don't really know how to create the list of ImageFeatures from scratch.

This is the current implementation, which doesn't work:

f1 = cv.detail_ImageFeatures()
f1.img_idx = 0
f1.descriptors = None
f1.img_size = (1920, 1080)
f1.keypoints = (
    cv.KeyPoint(1412.0, 734.0, 5.0),
    cv.KeyPoint(1415.0, 856.0, 5.0),
    cv.KeyPoint(1398.0, 885.0, 5.0)
)

...

features = [f1, f2, ...]

I get the following error when using my custom list just on the next step, which would be the matching: cv2.error: Conversion error: features

In addition to the custom ImageFeatures, I would also need custom matches. According to the documentation, these should be a MatchesInfo struct containing matches of type DMatch.

These are currently implemented as follows, but can't be tested since the above error already occurs beforehand:

matches = (
  cv.detail_MatchesInfo(confidence=1.0, dst_img_idx=1, H=None, inliers_mask=None, matches=(
    cv.DMatch(0, 0, 0.0),
    cv.DMatch(1, 1, 0.0),
    cv.DMatch(2, 2, 0.0)), num_inliers=None, src_img_idx=0),
  ...
)

So I was wondering, if it is even possible to "import" custom control points and matches using OpenCV Python. If yes, what would have to be changed to make it work.


问:
receiving notification from the Github about organization and private repositories
I have connected my personal GitHub account to the company I am working at. if I change anything in the organization related repositories, my colleagues will receive a notification about that but what if I change my own repositories which belong my account? is there anyway that my colleagues receive notification about my own repositories?


问:
Python multiprocessing - concurrent/parallel operations on files
I'm currently can't get my head around a problem that I'm having. I have a (main) python script that checks (on infinite loop) if a specific file showed up in designated path and do some operations on it. I want to be able to create a new thread/proccess every time it finds a new file, because there will be situations when 2 or 3 files appear at once and I want to calculate all of them at the same time. My prototype solution was to create another python script that takes a file name as an sys.argv arugment and every time main script finds a file it is using subprocess.popen(["python3", "anotherScript.py", "fileName.csv"]). It is working fine but I know it's not very elegant and I want to change those old scirpts to better ones using OOP.

Some examplary code how it works now:

```<code>while True:
   #check if a file appeared in PATH
   if len(os.listdir(PATH)) > 0:
      fileName = os.listdir(PATH)[0]

      #move this file to another location so it won't be calculated more than once
      os.system(f"mv '{PATH}{fileName}' {ANOTHER_PATH}")

      #script.py reads data from file, does some calculations on the data (
      #calculations take about 5-15 seconds) and deletes the file
      c = f"python3 script.py {ANOTHER_PATH}{fileName}".split(" ")
      subprocess.popen(c)
</code>```

Ideally I would want it to create a new object for every new file in PATH, do some newObject.calculations() in parallel and probably delete the new object after calculations are done. What would be the best approach for this problem?

Body:
I'm currently can't get my head around a problem that I'm having. I have a (main) python script that checks (on infinite loop) if a specific file showed up in designated path and do some operations on it. I want to be able to create a new thread/proccess every time it finds a new file, because there will be situations when 2 or 3 files appear at once and I want to calculate all of them at the same time. My prototype solution was to create another python script that takes a file name as an sys.argv arugment and every time main script finds a file it is using subprocess.popen(["python3", "anotherScript.py", "fileName.csv"]). It is working fine but I know it's not very elegant and I want to change those old scirpts to better ones using OOP.

Some examplary code how it works now:

while True:
   #check if a file appeared in PATH
   if len(os.listdir(PATH)) > 0:
      fileName = os.listdir(PATH)[0]

      #move this file to another location so it won't be calculated more than once
      os.system(f"mv '{PATH}{fileName}' {ANOTHER_PATH}")

      #script.py reads data from file, does some calculations on the data (
      #calculations take about 5-15 seconds) and deletes the file
      c = f"python3 script.py {ANOTHER_PATH}{fileName}".split(" ")
      subprocess.popen(c)

Ideally I would want it to create a new object for every new file in PATH, do some newObject.calculations() in parallel and probably delete the new object after calculations are done. What would be the best approach for this problem?


问:
ValueError: Found input variables with inconsistent numbers of samples: [29100, 27300]
The dataset is from a survey about 91 art pieces from 300 people. The first 91 columns are the preference ratings for each painting scored 1-7. The 91 columns after that are their ratings for the “energy” of the painting. Additionally, there are more columns that represent demographic information of each person. I am supposed to create a regression model to predict preference rating from energy rating and demographic. I was able to do a single regression with this code but multiple isnt working. What's wrong?

```<code>rate = data[:,0:91] #isolate preference ratings
energy = data[:,91:182] #isolate energy ratings
demo = data[:,215:221] #isolate demographic ratings
demo[np.isnan(demo)] = 4.68
comb = np.concatenate((energy,demo),axis=1)
x = comb.reshape(-1,1)
y = rate.reshape(-1,1)
ourModel = LinearRegression().fit(x, y)
rSq = ourModel.score(x,y)
slope = ourModel.coef_
intercept = ourModel.intercept_
yHat = slope * x + intercept
print(rSq)

plt.plot(x,y,'o',)
plt.xlabel('Energy + Demographic')
plt.ylabel('Preference')
plt.plot(x,yHat,color='orange',linewidth=3)
plt.title('Predicting Art Preference from Energy and Demographic')
plt.show()
</code>```

It is an issue with the reshaping but I've tried a lot of things and to no avail.

```<code>  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356, in compat_exec
    exec(code, globals, locals)

  File "/Users/pwigglybie/Downloads/CapstoneProject.py", line 132, in <module>
    ourModel = LinearRegression().fit(x, y)

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/sklearn/linear_model/_base.py", line 684, in fit
    X, y = self._validate_data(

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/sklearn/base.py", line 596, in _validate_data
    X, y = check_X_y(X, y, **check_params)

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/sklearn/utils/validation.py", line 1092, in check_X_y
    check_consistent_length(X, y)

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/sklearn/utils/validation.py", line 387, in check_consistent_length
    raise ValueError(

ValueError: Found input variables with inconsistent numbers of samples: [29100, 27300]
</code>```

Body:
The dataset is from a survey about 91 art pieces from 300 people. The first 91 columns are the preference ratings for each painting scored 1-7. The 91 columns after that are their ratings for the “energy” of the painting. Additionally, there are more columns that represent demographic information of each person. I am supposed to create a regression model to predict preference rating from energy rating and demographic. I was able to do a single regression with this code but multiple isnt working. What's wrong?

rate = data[:,0:91] #isolate preference ratings
energy = data[:,91:182] #isolate energy ratings
demo = data[:,215:221] #isolate demographic ratings
demo[np.isnan(demo)] = 4.68
comb = np.concatenate((energy,demo),axis=1)
x = comb.reshape(-1,1)
y = rate.reshape(-1,1)
ourModel = LinearRegression().fit(x, y)
rSq = ourModel.score(x,y)
slope = ourModel.coef_
intercept = ourModel.intercept_
yHat = slope * x + intercept
print(rSq)

plt.plot(x,y,'o',)
plt.xlabel('Energy + Demographic')
plt.ylabel('Preference')
plt.plot(x,yHat,color='orange',linewidth=3)
plt.title('Predicting Art Preference from Energy and Demographic')
plt.show()

It is an issue with the reshaping but I've tried a lot of things and to no avail.

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/spyder_kernels/py3compat.py", line 356, in compat_exec
    exec(code, globals, locals)

  File "/Users/pwigglybie/Downloads/CapstoneProject.py", line 132, in <module>
    ourModel = LinearRegression().fit(x, y)

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/sklearn/linear_model/_base.py", line 684, in fit
    X, y = self._validate_data(

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/sklearn/base.py", line 596, in _validate_data
    X, y = check_X_y(X, y, **check_params)

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/sklearn/utils/validation.py", line 1092, in check_X_y
    check_consistent_length(X, y)

  File "/Users/pwigglybie/opt/anaconda3/lib/python3.9/site-packages/sklearn/utils/validation.py", line 387, in check_consistent_length
    raise ValueError(

ValueError: Found input variables with inconsistent numbers of samples: [29100, 27300]


问:
How to eliminate WAR foldername from Tomcat URL?
Lets say i have a war called mywar.war and its deployed in apache tomcat. Upon startup its exploded into a directory called mywar inside webapps folder of tomcat.
This effectively means that i need to use mywar inside the URL like http:\\localhost:8080\mywar\xxx.

Is there any way so that i could directly access like this http:\\localhost:8080\xxx by still keeping the exploded mywar folder inside webapps.

Please note that i don't have any UI access to tomcat so whatever setting i need to do to achieve above has to be via configuration itself.

Is their any URL rewrite kinda thing in tomcat?

Any suggestions?


问:
Beam window not triggering
I have the following code, which reads messages from pubsub. I expect to hit a breakpoint in the TrackSpeed() method when a window has been created, which never happens. Although I see log outputs from the ExtractStationSpeedFn()

Example log from there:

INFORMATION: processing element
DeviceData{deviceId='d2fa82a7-d70e-4057-8d4f-769c21815195', value=0.0,
sensorId='b0f40aa4-696a-43be-bc3c-ffa4b36a8df5', formulaId='null',
timeInNanoSeconds=1671533073470000000,
receivedTimeInNanoSeconds=1671533073486702000}

What am I doing wrong?

Main method:

```<code>        pipeline.apply("Read PubSub messages",
                    PubsubIO.
                    readStrings().
                    fromSubscription("projects/seepex-cs/subscriptions/sensor-data-test_beam_6244029550622585075"))

            .apply(ParDo.of(new ExtractStationSpeedFn()))
            .apply(
                    Window.into(FixedWindows.of(Duration.standardSeconds(30)))

            )
            .apply(new TrackSpeed())
            .apply("print", ParDo.of(new PrintElementFn()));
</code>```

ExtractStationSpeedFn

```<code>static class ExtractStationSpeedFn extends DoFn<String, KV<String, DeviceData>> {
    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    @ProcessElement
    public void processElement(ProcessContext c) {

        String message = c.element();
        DeviceData data = new Gson().fromJson(message, DeviceData.class);

        String sourceId = data.getSensorId() != null ? data.getSensorId() : data.getFormulaId();

        KV<String, DeviceData> outputValue = KV.of(sourceId, data);
        c.output(outputValue);

        LOG.info("processing element {}", data);
    }
}
</code>```

TrackSpeed

```<code>static class TrackSpeed extends PTransform<PCollection<KV<String, DeviceData>>, PCollection<Bucket>> {
    @Override
    public PCollection<Bucket> expand(PCollection<KV<String, DeviceData>> stationSpeed) {
        // Apply a GroupByKey transform to collect a list of all station
        // readings for a given route.
        PCollection<KV<String, Iterable<DeviceData>>> timeGroup = stationSpeed.apply(GroupByKey.create());

        PCollection<Bucket> stats = timeGroup.apply(ParDo.of(new GatherStats()));
        return stats;
    }
}
</code>```

Title: Beam window not triggering

Body:
I have the following code, which reads messages from pubsub. I expect to hit a breakpoint in the TrackSpeed() method when a window has been created, which never happens. Although I see log outputs from the ExtractStationSpeedFn()

Example log from there:

INFORMATION: processing element
DeviceData{deviceId='d2fa82a7-d70e-4057-8d4f-769c21815195', value=0.0,
sensorId='b0f40aa4-696a-43be-bc3c-ffa4b36a8df5', formulaId='null',
timeInNanoSeconds=1671533073470000000,
receivedTimeInNanoSeconds=1671533073486702000}

What am I doing wrong?

Main method:

        pipeline.apply("Read PubSub messages",
                    PubsubIO.
                    readStrings().
                    fromSubscription("projects/seepex-cs/subscriptions/sensor-data-test_beam_6244029550622585075"))

            .apply(ParDo.of(new ExtractStationSpeedFn()))
            .apply(
                    Window.into(FixedWindows.of(Duration.standardSeconds(30)))

            )
            .apply(new TrackSpeed())
            .apply("print", ParDo.of(new PrintElementFn()));

ExtractStationSpeedFn

static class ExtractStationSpeedFn extends DoFn<String, KV<String, DeviceData>> {
    private final Logger LOG = LoggerFactory.getLogger(this.getClass());

    @ProcessElement
    public void processElement(ProcessContext c) {

        String message = c.element();
        DeviceData data = new Gson().fromJson(message, DeviceData.class);

        String sourceId = data.getSensorId() != null ? data.getSensorId() : data.getFormulaId();

        KV<String, DeviceData> outputValue = KV.of(sourceId, data);
        c.output(outputValue);

        LOG.info("processing element {}", data);
    }
}

TrackSpeed

static class TrackSpeed extends PTransform<PCollection<KV<String, DeviceData>>, PCollection<Bucket>> {
    @Override
    public PCollection<Bucket> expand(PCollection<KV<String, DeviceData>> stationSpeed) {
        // Apply a GroupByKey transform to collect a list of all station
        // readings for a given route.
        PCollection<KV<String, Iterable<DeviceData>>> timeGroup = stationSpeed.apply(GroupByKey.create());

        PCollection<Bucket> stats = timeGroup.apply(ParDo.of(new GatherStats()));
        return stats;
    }
}


问:
How to resolve 503 error on sentrifugo deployed on aws lightsail instance
Every time I try to add an employee, it throws me 503 error. FYI - this is a fresh installation of sentrifugo and I was able to add one employee which is shown in "Add reporting manager". However, employee listing says no employees.

And while I didnt see any errors while creating department, I dont see the same in Leave management options (for example). Can someone quickly assist on this please?


问:
What method can I use in Typescript to print limited characters on each line, taking both words and spaces into account?
I am using the substring method to limit the number of characters on each line. The issue I am facing is that the word breaks when the character limit is reached. I want whole words to be preserved. Are there any functions or logic which can limit by character count without breaking up words?

let MaxCharPerLine = 10;

let Inctext = "Sample text to print 10 charachters each line";

for (let i = 0; i < Inctext.length; i += MaxCharPerLine) {
  console.log(Inctext.substring(i, i + MaxCharPerLine))
}```
</div>
</div>
</p>
<p>Output:</p>
```Sample tex
t to print
 10 charac
hters each
 line
```
<p>Output I want:</p>
```Sample
text to
print 10
characters
each line
```

Body:
I am using the substring method to limit the number of characters on each line. The issue I am facing is that the word breaks when the character limit is reached. I want whole words to be preserved. Are there any functions or logic which can limit by character count without breaking up words?

let MaxCharPerLine = 10;

let Inctext = "Sample text to print 10 charachters each line";

for (let i = 0; i < Inctext.length; i += MaxCharPerLine) {
  console.log(Inctext.substring(i, i + MaxCharPerLine))
}

Output:

Sample tex
t to print
 10 charac
hters each
 line

Output I want:

Sample
text to
print 10
characters
each line


问:
Removing duplicates
I'm trying to filter out duplicated values of a list.

There may be some designated function whom I'm not aware of, so I tried doing this with a for loop.
But I find the result disturbing: instead of doing the desired task properly, the program outputs every second element, whether it is duplicated whether it's not.

Why is this??

```<code>ln_1="But But we all went yesterday to the mall and had some fun wow yesterday"
lnsplt1=ln_1.split()
for word in lnsplt1:
    if word in lnsplt1:
       lnsplt1.remove(word)
</code>```

and the output is:

['But', 'all', 'the', 'and', 'some', 'wow', 'yesterday']

Title: Removing duplicates

Body:
I'm trying to filter out duplicated values of a list.

There may be some designated function whom I'm not aware of, so I tried doing this with a for loop.
But I find the result disturbing: instead of doing the desired task properly, the program outputs every second element, whether it is duplicated whether it's not.

Why is this??

ln_1="But But we all went yesterday to the mall and had some fun wow yesterday"
lnsplt1=ln_1.split()
for word in lnsplt1:
    if word in lnsplt1:
       lnsplt1.remove(word)

and the output is:

['But', 'all', 'the', 'and', 'some', 'wow', 'yesterday']


问:
Easy way to prevent rails console displaying numbers (decimal, float, integers) in scientific notation?
Is there some default configuration that can be altered to prevent scientific notation in the rails console without having to configure it on a per-column basis? (i.e. I'd like to just run some config line once somewhere and have it apply across all tables/columns for that app, if possible).

Example

Here is an example where scientific notation sort of gets in the way

```<code>Product.first

cost: 0.99999998999923e12,
currency: "USD",
charge: 0.55e1,
charge_currency: "AUD",
price: 0.5e2,
price_currency: "AUD"
</code>```

I'd prefer to see 999999989999.23 instead of 0.99999998999923e12, 5.5 instead of 0.55e1, 50 instead of 0.5e2. I find regular numbers much more natural and easy to read.

What I know so far

There are a couple of ideas in the answers to Rails console shows value in scientific notation, but both are on a per column/attribute basis.

Note

I'd be happy to install a gem (I already use pry if that helps), and basically want a convenient way of avoiding scientific notation when displaying integers/floats/decimals but without having to write code specific to the model/columns/types.

Body:
Is there some default configuration that can be altered to prevent scientific notation in the rails console without having to configure it on a per-column basis? (i.e. I'd like to just run some config line once somewhere and have it apply across all tables/columns for that app, if possible).

Example

Here is an example where scientific notation sort of gets in the way

Product.first

cost: 0.99999998999923e12,
currency: "USD",
charge: 0.55e1,
charge_currency: "AUD",
price: 0.5e2,
price_currency: "AUD"

I'd prefer to see 999999989999.23 instead of 0.99999998999923e12, 5.5 instead of 0.55e1, 50 instead of 0.5e2. I find regular numbers much more natural and easy to read.

What I know so far

There are a couple of ideas in the answers to Rails console shows value in scientific notation, but both are on a per column/attribute basis.

Note

I'd be happy to install a gem (I already use pry if that helps), and basically want a convenient way of avoiding scientific notation when displaying integers/floats/decimals but without having to write code specific to the model/columns/types.


问:
Why the event receiver persist all the emitted values.how to listen to the most recent emitted value only
as shown in the below posted code, i emit an event as shown in section emitting an event. the value to be emitted is a string and the log-statement confirm that as shown in the below posted screen-shot.
the problem i am facing, is as i am registered to listen to the emitted event as shown in section ngOnInit below, i receive several values for the emitted value param as shown in the screen-shot.

in other words, assume that the event in emitting an event section is emitted on button clicks, for the first click

```<code>console.log("this.selectedSite.id:",this.selectedSite.id) displays 202207070658 which is the most recent emitted value. this line behave correctly as is displays the most recent value as expected
</code>```

but the problem is in the ngOnInit section- For the first click "first emittance to the event",

```<code>console.log("******************selectedSiteID:",this.selectedSiteID) displays 202226081143
after clicking two times, it displays: 202226081143 and 202228011057
after clicking four time, it displays the values shown in the screen shot
</code>```

i would like to receive only the most recent emitted value only. how can i achieve that

service:

```<code>export class FromSiteMapToVisOptionsService {
private broadcastEmitterToAckSelectedSiteID:Subject<string> = new ReplaySubject<string>();
constructor() { }

  public emitToAckSelectedSiteID(param) {
    this.broadcastEmitterToAckSelectedSiteID.next(param)
  }
  public getBroadcastEmitterToAckSelectedSiteID() {
    return this.broadcastEmitterToAckSelectedSiteID.asObservable()
  }
}
</code>```

ngOnInit:

```<code> this.subscriptionOnAckSelectedSiteID = this._FromSiteMapToVisOptionsService.getBroadcastEmitterToAckSelectedSiteID().subscribe((param:string)=>{
  this.selectedSiteID = param
  this.storedSelectedSiteID = this._PersistStateService.getItem(this.keySelectedSiteID)
  console.log("******************selectedSiteID:",this.selectedSiteID)
})
</code>```

emitting an event

```<code>// assume it will be emitted on button clicks
this.subscriptionEventEmitterToRequestSelectedSiteID = this._FromVisOptionsToSiteMapService.getBroadcastEmitterToRequestSelectedSiteID().subscribe(()=> {
        console.log("this.selectedSite.id:",this.selectedSite.id)//displays the value of this.selectedSiteID only once.this.selectedSiteID contains only one value as shown in the screen-shot, its value is displayed once
        this._FromSiteMapToVisOptionsService.emitToAckSelectedSiteID(this.selectedSite.id)
    })
</code>```

img

Body:
as shown in the below posted code, i emit an event as shown in section emitting an event. the value to be emitted is a string and the log-statement confirm that as shown in the below posted screen-shot.
the problem i am facing, is as i am registered to listen to the emitted event as shown in section ngOnInit below, i receive several values for the emitted value param as shown in the screen-shot.

in other words, assume that the event in emitting an event section is emitted on button clicks, for the first click

console.log("this.selectedSite.id:",this.selectedSite.id) displays 202207070658 which is the most recent emitted value. this line behave correctly as is displays the most recent value as expected

but the problem is in the ngOnInit section- For the first click "first emittance to the event",

console.log("******************selectedSiteID:",this.selectedSiteID) displays 202226081143
after clicking two times, it displays: 202226081143 and 202228011057
after clicking four time, it displays the values shown in the screen shot

i would like to receive only the most recent emitted value only. how can i achieve that

service:

export class FromSiteMapToVisOptionsService {
private broadcastEmitterToAckSelectedSiteID:Subject<string> = new ReplaySubject<string>();
constructor() { }

  public emitToAckSelectedSiteID(param) {
    this.broadcastEmitterToAckSelectedSiteID.next(param)
  }
  public getBroadcastEmitterToAckSelectedSiteID() {
    return this.broadcastEmitterToAckSelectedSiteID.asObservable()
  }
}

ngOnInit:

 this.subscriptionOnAckSelectedSiteID = this._FromSiteMapToVisOptionsService.getBroadcastEmitterToAckSelectedSiteID().subscribe((param:string)=>{
  this.selectedSiteID = param
  this.storedSelectedSiteID = this._PersistStateService.getItem(this.keySelectedSiteID)
  console.log("******************selectedSiteID:",this.selectedSiteID)
})

emitting an event

// assume it will be emitted on button clicks
this.subscriptionEventEmitterToRequestSelectedSiteID = this._FromVisOptionsToSiteMapService.getBroadcastEmitterToRequestSelectedSiteID().subscribe(()=> {
        console.log("this.selectedSite.id:",this.selectedSite.id)//displays the value of this.selectedSiteID only once.this.selectedSiteID contains only one value as shown in the screen-shot, its value is displayed once
        this._FromSiteMapToVisOptionsService.emitToAckSelectedSiteID(this.selectedSite.id)
    })

img


问:
Can connect with ts-node to service only by ip not by localhost
I have a service that is bound to 0.0.0.0:1337.

The service can be reached on my two network devices by curl at http://localhost:1337 and http://192.168.0.26:1337.

However when I use the following ts code:

```<code>var http = require('http');
var options = {
  host: 'http://localhost:1337',
};

const callback = function(response) {
  var str = '';

  //another chunk of data has been received, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been received, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();
</code>```

and run it with ts-node I get a connection refused. When I use host: 'http://192.168.0.26:1337' then it works. This issue occured today after an ubuntu update.

Why can I do to solve the issue? I tried node version 16 and 18. It's strange the it seems node-related because curl works.

Body:
I have a service that is bound to 0.0.0.0:1337.

The service can be reached on my two network devices by curl at http://localhost:1337 and http://192.168.0.26:1337.

However when I use the following ts code:

var http = require('http');
var options = {
  host: 'http://localhost:1337',
};

const callback = function(response) {
  var str = '';

  //another chunk of data has been received, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been received, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();

and run it with ts-node I get a connection refused. When I use host: 'http://192.168.0.26:1337' then it works. This issue occured today after an ubuntu update.

Why can I do to solve the issue? I tried node version 16 and 18. It's strange the it seems node-related because curl works.


问:
Handle 200Mb response size in rest api
We have an API which connects to oracle database to pull data, max response size for the request is 200mb and record count is 80k. As we have to create 80k objects for each request  I'm  getting out of memory some cases.
What could be the best solution to handle responses , I'm thinking of streaming , webflux. Which could be the best solution here?

I have tried streaming

Title: Handle 200Mb response size in rest api


问:
React Native (Expo) Send an Email with created PDF
I need some help on how to send an Email with a created PDF via Expo and Nodemailer.

I have my Backend Function for the NodeMailer setup and tested to actually work.

In the Frontend I have tried few different Expo Packages but always had something that would not work for me.

How I want it to work is:

On Button Press open the created PDF

When the user wants he can close the File

In the Background send that opened File via my NodeMailer

What I've tried:

```<code> await Print.printAsync({
   html,
   orientation: "portrait",
   printerUrl: this.state.selectedPrinter?.url,
 })
</code>```

This creates my File and I can save it as PDF! Now this would actually work for me if I could automatically rename the File. When I press save as PDF it is called "Document" but I need to have it named dynamically. I guess if I could rename it I might be able to pick it somehow and send it (like Expo DocumentPicker or FileSystem maybe).

Second approach is to save the File and then open it:

```<code>const { uri } = await Print.printToFileAsync({ html });
console.log('File has been saved to:', uri);

try {

  const cUri = await FileSystem.getContentUriAsync(uri);

  await ExpoIntent.startActivityAsync("android.intent.action.VIEW", {
      data: cUri,
      flags: 1,
      type: "application/pdf",
  });
}catch(e){
    console.log(e.message);
}
</code>```

The Code saves my File and opens it up again. Now here is a URI I can access which looks kinda like this:

```<code>file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540xyyxwyx%252FPXXXX/Print/eb03cc8c-9c29-4d08-aed8-f10eXXX87fe5.pdf
</code>```

When I try to use that URI and send it via nodemailer it tells me that the file does not exist!

```<code>Error Mail: Error: ENOENT: no such file or directory, open 'C:\Dev\Programmierung\rn\xxx-Server\file:\data\user\0\host.exp.exponent\cache\ExperienceData\%2540xxyx%252Fxxx\Print\cbcff690-d608-4138-a635-93cxxy72a2ed.pdf'
</code>```

Which makes sense since that file is not available on my PC, its only inside my Emulator. How do I tell Expo the correct URI Link?

So whats important (one of the two):

Renaming the File and save it under the correct name

using the correct URI

I also had some approaches renaming the File using Expo Filesystem and Expo Sharing but not really the way I wanted it. If anyone could give some advice on how to achieve this would be great, or even different approaches with Expo DocumentPicker for example.

Body:
I need some help on how to send an Email with a created PDF via Expo and Nodemailer.

I have my Backend Function for the NodeMailer setup and tested to actually work.

In the Frontend I have tried few different Expo Packages but always had something that would not work for me.

How I want it to work is:

On Button Press open the created PDF

When the user wants he can close the File

In the Background send that opened File via my NodeMailer

What I've tried:

 await Print.printAsync({
   html,
   orientation: "portrait",
   printerUrl: this.state.selectedPrinter?.url,
 })

This creates my File and I can save it as PDF! Now this would actually work for me if I could automatically rename the File. When I press save as PDF it is called "Document" but I need to have it named dynamically. I guess if I could rename it I might be able to pick it somehow and send it (like Expo DocumentPicker or FileSystem maybe).

Second approach is to save the File and then open it:

const { uri } = await Print.printToFileAsync({ html });
console.log('File has been saved to:', uri);

try {

  const cUri = await FileSystem.getContentUriAsync(uri);

  await ExpoIntent.startActivityAsync("android.intent.action.VIEW", {
      data: cUri,
      flags: 1,
      type: "application/pdf",
  });
}catch(e){
    console.log(e.message);
}

The Code saves my File and opens it up again. Now here is a URI I can access which looks kinda like this:

file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540xyyxwyx%252FPXXXX/Print/eb03cc8c-9c29-4d08-aed8-f10eXXX87fe5.pdf

When I try to use that URI and send it via nodemailer it tells me that the file does not exist!

Error Mail: Error: ENOENT: no such file or directory, open 'C:\Dev\Programmierung\rn\xxx-Server\file:\data\user\0\host.exp.exponent\cache\ExperienceData\%2540xxyx%252Fxxx\Print\cbcff690-d608-4138-a635-93cxxy72a2ed.pdf'

Which makes sense since that file is not available on my PC, its only inside my Emulator. How do I tell Expo the correct URI Link?

So whats important (one of the two):

Renaming the File and save it under the correct name

using the correct URI

I also had some approaches renaming the File using Expo Filesystem and Expo Sharing but not really the way I wanted it. If anyone could give some advice on how to achieve this would be great, or even different approaches with Expo DocumentPicker for example.


问:
Line 57:7: Expected an assignment or function call and instead saw an expression no-unused-expressions
Getting this error, i don't know why, use this same method in many files in same project.
Using this function to create an array of Options for React-Select (Multi select) Library.

```<code>import { Button, Grid, IconButton, MenuItem, Modal, Select, TextField, Typography } from '@mui/material';
import { Box } from '@mui/system';
// import { GridCloseIcon } from '@mui/x-data-grid';
import AddIcon from '@mui/icons-material/Add';
import MultiSelect from '../../../components/MultiSelect'
import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux';
import { AddModule, fetchModulesCategories } from '../../../redux/Modules/ModuleActions';
import { useSelector } from 'react-redux';
import CancelIcon from '@mui/icons-material/Cancel';
import SaveIcon from '@mui/icons-material/Save';
</code>```
```<code>  Line 57:7:  Expected an assignment or function call and instead saw
  an expression  no-unused-expressions
</code>```

Body:
Getting this error, i don't know why, use this same method in many files in same project.
Using this function to create an array of Options for React-Select (Multi select) Library.

import { Button, Grid, IconButton, MenuItem, Modal, Select, TextField, Typography } from '@mui/material';
import { Box } from '@mui/system';
// import { GridCloseIcon } from '@mui/x-data-grid';
import AddIcon from '@mui/icons-material/Add';
import MultiSelect from '../../../components/MultiSelect'
import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux';
import { AddModule, fetchModulesCategories } from '../../../redux/Modules/ModuleActions';
import { useSelector } from 'react-redux';
import CancelIcon from '@mui/icons-material/Cancel';
import SaveIcon from '@mui/icons-material/Save';

  Line 57:7:  Expected an assignment or function call and instead saw
  an expression  no-unused-expressions


问:
MAUI Call a function after bound property update
I'm working on a;
.Net7 MAUI app.

CommunityToolkit.Maui 3.1.0
CommunityToolkit.Mvvm 8.1.0-p2

I have a DatePicker in my xaml bound to a DateTime property (date of birth (dob)) in the ViewModel.

```<code>[ObservableProperty]
private DateTime dateOfBirth;
</code>```

After the user changes the dob I want another function that utilizes this value to be called by using another annotation on the dob property.  Something like [AndAlsoCallThisFunction=nameof(myFunc)]

I remember they updated the names of the annotations a while ago.

What is the annotation I need at this time please?

Also, do I need CT.Mvvm when using CT.Maui?

TYIA! :)

Body:
I'm working on a;
.Net7 MAUI app.

CommunityToolkit.Maui 3.1.0
CommunityToolkit.Mvvm 8.1.0-p2

I have a DatePicker in my xaml bound to a DateTime property (date of birth (dob)) in the ViewModel.

[ObservableProperty]
private DateTime dateOfBirth;

After the user changes the dob I want another function that utilizes this value to be called by using another annotation on the dob property.  Something like [AndAlsoCallThisFunction=nameof(myFunc)]

I remember they updated the names of the annotations a while ago.

What is the annotation I need at this time please?

Also, do I need CT.Mvvm when using CT.Maui?

TYIA! :)


问:
couldn't find setup.py file in my cdk project in cloud9
i'm trying to start cdk project (python)
according to the tutorial i need to work on app-stack.py file and set-up.py file
but i can't find the second fileThis Is the created project

this is the tutorial project


问:
Cypress onbeforeload fails only in console run
I get this error only when executing tests with 'npx cypress run '
when I run the same thing in windowed mode 'npx cypress open ', it works properly